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
|
---|---|---|---|---|---|
GP0jm7xAixg | hey hey everybody this is larry this is me going over q1 me going over q1 of the buy weekly contest 38 uh sort of the buy weekly contest 38 uh sort away by increasing frequency away by increasing frequency so this is actually a great so this is actually a great example of using a key sorting by key example of using a key sorting by key instead of comparison so i mean i know instead of comparison so i mean i know that underneath it does comparison that underneath it does comparison but literally um you want to sort by but literally um you want to sort by some value which is the frequency of a some value which is the frequency of a character character and then sort them in decreasing order and then sort them in decreasing order right so i actually missed the right so i actually missed the decreasing order part to be honest decreasing order part to be honest but basically i put everything in a but basically i put everything in a counter and you could counter and you could use this on a a hash table use this on a a hash table and just doing a character or a number and just doing a character or a number by number and then incrementing it in by number and then incrementing it in the hash table the hash table obviously it takes a little bit more obviously it takes a little bit more coding i saw this during the contest in coding i saw this during the contest in about 57 seconds about 57 seconds and you could watch this afterwards uh and you could watch this afterwards uh live and while i stopped during the live and while i stopped during the contest contest so i i got to so i i got to got the number uh for each number how got the number uh for each number how many count is there that's what many count is there that's what this does uh that's what counter does this does uh that's what counter does for me automatically and then i just for me automatically and then i just literally sort by literally sort by um sort by the frequency of the um sort by the frequency of the character which is character which is just 40 named s of x uh but you know just 40 named s of x uh but you know at home you have more time you could do at home you have more time you could do this a little better and this a little better and as a tie breaker we sorted by negative x as a tie breaker we sorted by negative x which is a way to sort by which is a way to sort by from bigger to this uh smaller in terms from bigger to this uh smaller in terms of the number right of the number right so that's basically it uh a three-liner so that's basically it uh a three-liner you could you could maybe just you get done just in one line maybe just you get done just in one line if you really want if you really want uh but you might have to worry about uh but you might have to worry about you know efficiency but still two lines you know efficiency but still two lines of stupid so if you want to play golf of stupid so if you want to play golf but that's basically how i did it and but that's basically how i did it and now you can watch me solve it live now you can watch me solve it live during the contest during the contest next i don't know why i keep pointing next i don't know why i keep pointing that though hey i'm not getting submit uh yeah thanks for watching thanks for hanging out let me know what you think about this explanation um doing a little bit live so yeah hit the like button into subscriber and join me on discord and i will see y'all next | 2024-03-19 15:43:58 | 1,636 | 1636. Sort Array by Increasing Frequency (Leetcode Easy) |
|
R789j1-ZdxE | hello everyone welcome to a Cohiba in this video student solve the problem this video student solve the problem binary search tree before we start the binary search tree before we start the channel how many unique values and is equal to 1 only one unique tree that can be built that is with 1 if n is equal to 2 we can build one as a root and 2 or 2 as a root and 1 2 unique binary trees if n is equal to 2 and if L n is equal to 3 we can build one as a root and 2 and 3 and these 2 can be performed in two different ways so this can be built 1 3 & 2 if you take 2 as a root it can be built in one way and if you take 3 as a root that also can be built in 2 different ways these two can be built with 2 different ways to tell it will be 2 plus 2 plus 1 for each if root is equal to 3 root is equal to 1 and Rho T is equal to 2 is equal to 5 but if you look into the pattern here so if you look into the pattern here if there is one nor it can build one if there is two nodes it can be built in two different ways now we calculated with three it can be built in five different ways so what we can do is let's say if n is equal to 7 we can start by the root node and then go from there so we need to do a multiplication of n minus 1 let's see and is equal to four once we place the root we need to distribute three different nodes two three and four and as we saw two three and four can be distributed in five different ways so we need to have the product of the previous functions so if we can store in some array like how many nodes can be filled like if there are zero nodes it can be one if there is one node and we can build one unique binary tree if there are two nodes we can build two unique binary three trees and if there are three nodes we found out that we can build five unique binary trees so similarly when four comes once we place two one as a root we know how many can we build with four different nodes so we can get this and add it to that similarly we will replace with node two and we will again add it to that so it's a multiplication of the previous nodes so we will use dynamic programming approach where we will take an array of n plus 1 and we will calculate with each node how many unique binary trees can be generated and we will place in the array and go all we need to do is we need to calculate from 0 to n and we will return the nth element once we are done with it let's go ahead and look into how we can actually code this out so let's define an array count with the size and plus 1 now we know two things if the nodes are 0 we would return one unique binary tree so the count of 0 would be 1 and if we have only one node we will we can only generate one unique binary tree binary search tree so we got both of and we need to start from zero it and and we need to start from zero it and count let's say we place one in the root count let's say we place one in the root we are left with one node and we need to we are left with one node and we need to find out how many unique binary search find out how many unique binary search trees can be built with one node since trees can be built with one node since we already have count of one is equal to we already have count of one is equal to one we would add that to the current one one we would add that to the current one so let's go from this is i-4 and J is so let's go from this is i-4 and J is equal to 0 J less than or equal to 2 all equal to 0 J less than or equal to 2 all we need we need to fill up the current we need we need to fill up the current index if there are two nodes given if n index if there are two nodes given if n is equal to 2 how many nodes how many is equal to 2 how many nodes how many unique binary search trees can be built unique binary search trees can be built that is the sum of count of 2 plus count that is the sum of count of 2 plus count of so element is j counter Phi star of so element is j counter Phi star count off J minus I minus 1 so that will count off J minus I minus 1 so that will give us the count and all we need to do give us the count and all we need to do is return count of 10 this is equal to I I - J my bad this is J my bad it should be minus one yeah it went so let's look into what happened here so what we are doing is let's say if the nor is one we will have one unique we will have one unique binary search tree so let's take the array and +1 4 0 1 and 1 now let's say if the N is equal to 2 we come here and count of I which is count of 2 should be count of 2 initially its 0 0 plus count of say J 0 which is this one plus count of say 0 star count of I minus J minus 1 which is 0 which is 2 so we got it right so we will have 2 here now we increment say say would be 1 and J should be less than or equal to minus 1 which in this case is true so we will come down again and so it's 0 plus 1 this is 1 at this point now again we are doing 1 plus count of I is 1 1 plus say is count of 1 which is 1 1 star count of I minus J minus 1 which is 1 so it becomes 2 so now we got 3 what happens here is now we are here we need to fill count of 2 which we will fill that's right and count of 3 what happens is count of 3 initially 0 plus 1 star hi minus J minus 1 which is 2 which gives us - so the count of three would be two initially then we increase the J index now it becomes 2 plus 1 star count of hi minus J minus 1 3 minus 1 minus 1 which results in 1 count of 1 is again 1 which is which becomes 3 now this will become 3 again the loop continues and jet index will be this so we come here with 1 plus jet index to star I minus Z minus 1 0 1 we will end up with 5 this one we will update this with 5 that's how we know we can create why do you need one with search trees I hope it's clear please to like and subscribe this channel thank you | 2024-03-20 13:39:02 | 96 | Leetcode Unique Binary Search Trees Java Solution |
|
mFpnEj0GiSU | hello and welcome to another video today we're going to be working on Implement we're going to be working on Implement stack using cues and this problem is I'd stack using cues and this problem is I'd say not quite an easy problem and say not quite an easy problem and depends on your implementation as well depends on your implementation as well um so I'd say it's closer to a medium um so I'd say it's closer to a medium problem but in this problem you're asked problem but in this problem you're asked to implement a lasting first out stack to implement a lasting first out stack so normal stack using two cues the so normal stack using two cues the implementation should support all the implementation should support all the functions of a normal stack push top pop functions of a normal stack push top pop and empty and then you want to implement and empty and then you want to implement it you want to have a push pop top and it you want to have a push pop top and empty and you can only use standard empty and you can only use standard operations of a queue which means push operations of a queue which means push to back to back Peak from front size and is empty Peak from front size and is empty and so depending on your language and so depending on your language the Q may not be supported natively you the Q may not be supported natively you may simulate it using a list or deck may simulate it using a list or deck as long as you're using a standard like as long as you're using a standard like Q operation so we cannot use pop from Q operation so we cannot use pop from the back the back we can't use we can't look at like the we can't use we can't look at like the last element we can only look at the last element we can only look at the first element and we can only pop from first element and we can only pop from the left the left and here's this example so essentially and here's this example so essentially let's take a look at what it would look let's take a look at what it would look like so you start a stack like so you start a stack and you push one so like what a stack and you push one so like what a stack would look like is you push one then you would look like is you push one then you push two and then you do top which gives push two and then you do top which gives you the last element so we're going to you the last element so we're going to turn two then you would pop which would turn two then you would pop which would pop this to return it and get rid of it pop this to return it and get rid of it and then you checking for empty and it and then you checking for empty and it should return false because there's should return false because there's something in your key something in your key so we're going to do is we're going to so we're going to do is we're going to show the way to do this with two cues show the way to do this with two cues and then the way to do this with one cue and then the way to do this with one cue and the easiest thing honestly I found and the easiest thing honestly I found for this problem or these types of for this problem or these types of problems where you're doing stack with problems where you're doing stack with cues or cues with Stacks is try a few cues or cues with Stacks is try a few numbers and like make sure it makes numbers and like make sure it makes sense and so what we're going to try is sense and so what we're going to try is we're just going to try putting in the we're just going to try putting in the numbers one two and three numbers one two and three and kind of just trying to figure out and kind of just trying to figure out like okay like okay like is there Q okay basically like is there Q okay basically and so there's a few ways to do this so and so there's a few ways to do this so I'm going to show you the two Q ways so I'm going to show you the two Q ways so let's just call this q1 let's just call this q1 it's going to be it's going to be a deck it's going to be it's going to be a deck call this Q2 it's going to be a deck call this Q2 it's going to be a deck and in this first example it's going to and in this first example it's going to be pretty straightforward so we're going be pretty straightforward so we're going to go through these one by one so to go through these one by one so essentially q1 will be our main our main essentially q1 will be our main our main like q and you can do this one you can like q and you can do this one you can do this a few ways essentially it's do this a few ways essentially it's either your push or your pop is going to either your push or your pop is going to be open and then the other one will be be open and then the other one will be over one in my case I decided to make over one in my case I decided to make the push of one and then the pulp o of n the push of one and then the pulp o of n but either one's fine like you can ask but either one's fine like you can ask you know like which operation should I you know like which operation should I prefer maybe in an interview and then if prefer maybe in an interview and then if they said like they're all equal then they said like they're all equal then you could do whatever but if they said you could do whatever but if they said like oh we're going to be doing more like oh we're going to be doing more well I guess you can't really do more well I guess you can't really do more pops but let's say you like maybe if you pops but let's say you like maybe if you have equal amounts of tops pops and have equal amounts of tops pops and pushes pushes um top and pop here would be o of n so um top and pop here would be o of n so maybe you could swap it around to make maybe you could swap it around to make push oven and then Tov and pop open so push oven and then Tov and pop open so those are some things to think about but those are some things to think about but essentially so what we're going to do is essentially so what we're going to do is pretty easy we're just going to insert pretty easy we're just going to insert one two and three and we're going to one two and three and we're going to show what that looks like so when we show what that looks like so when we push in one we're just going to push push in one we're just going to push always into this first Q always into this first Q and that's pretty much it for the push and that's pretty much it for the push we're just gonna do like a normal append we're just gonna do like a normal append and then so we're gonna push in one two and then so we're gonna push in one two three and we're going to show what it three and we're going to show what it looks like to get rid of an element so looks like to get rid of an element so we're gonna push in one we're gonna we're gonna push in one we're gonna pushing two we're gonna push in three pushing two we're gonna push in three and so this is like so nor so our our and so this is like so nor so our our first Q is really like a stack but we're first Q is really like a stack but we're not going to be using any stack not going to be using any stack operation so now if we call Pop operation so now if we call Pop what we are going to do is we're going what we are going to do is we're going to be so we want to pop this last to be so we want to pop this last element element but we can't like plot from the right but we can't like plot from the right so what we're actually going to do is so what we're actually going to do is we're going to pop from the left and we're going to pop from the left and insert into this first cue so we're insert into this first cue so we're going to pop from here and push to this going to pop from here and push to this which is allowed right pop we're using a which is allowed right pop we're using a pop left and an append so that's going pop left and an append so that's going to look like as we pop one we push it in to look like as we pop one we push it in gets rid of the one then we pop two gets rid of the one then we pop two because that's our first element now we because that's our first element now we push it in and now our Q is length one push it in and now our Q is length one and now we could say like okay when the and now we could say like okay when the Q is length one then pop that last Q is length one then pop that last element save it in a variable right so element save it in a variable right so we're going to pop this save it in some we're going to pop this save it in some results variable and then that's what we're going to be returning and our for our second cue now we do the same thing again so we can just say like while we have our second cue let's pop and add back to the first key so we pull up the one we add it over here then we pull off the two and we add it over here and so now our Q is or our one is you know this and our three is popped and top is basically the same thing except instead of returning this three you're literally doing the exact same process except instead of returning here you save the variable and then you push it in at the very end over here so literally pull up and push are or sorry pulp and top are like a one line difference with two cues and so we can write this down here's our steps so pop or sorry push would just be append of one like a normal append pop when we pop left from q1 until one element left or so pop up from one and append to two until one element left in one then Pop That save it save it then pop left from two and append to one then pop left from two and append to one until nothing left in two and then top same as Pop but at the end append the saved element 2y that's pretty much it um pretty straightforward right so that's that's the approach for this and then for our Big O complexity so our push would be o of one because we're just doing a normal append but for the pop we have to take all of our elements from here put them in here and then put them back and so that is going to be of n and top same thing is open so that's one way to do it and empty obviously is like really straightforward we are allowed to use the size so we can just check for the length of it right and if the length is zero then or were you if they say we can even use it as empty so if we can use this empty I don't I don't know if like a deck has is empty but you can just check for the length and then if the length is zero then it's empty pretty straightforward okay so now we're going to focus on the other approach which is going to be the one key approach so we're going to go back delete some of this and we are going to do the one key approach and the one key approach you're going to see is pretty straightforward but there's going to be a difference so I decided for the 1q approach maybe you could do it both ways as well but just for me I decided I want my 1q to be a reverse stack and what that means is let's say if in a stack you would push one two three and it would look like this I want my Q to look like this that way when I pop the pops and tops are really easy right we're just going to pop left and that would that would be the same as this so essentially I want my elements to be inserted backwards now the way to do this is also pretty straightforward and so now our pushes are going to be o of N and our Pops and tops are going to be of one and let's just go through the same thing with like a few elements let's maybe do four elements so essentially for the first element so we're going to have only one Q now so for the first element it's pretty straightforward there's nothing there for the second element what I'm going to do is I'm going to do a normal append but then I will have a loop that says for the length of the Q minus one right we are allowed to get the length here over the Q um yeah so they let you size which is like the length so for the length of the Q minus one in this case it would be one we are going to pop left and append which means we're going to take our element delete it and put it back here and so once we do that our key will look and now if we want to insert a three and now if we want to insert a three let's see what that would look like so let's see what that would look like so we would have two one three we would have two one three and then we're going to say okay for the and then we're going to say okay for the length of the Q minus 1 Let's pop from length of the Q minus 1 Let's pop from the left and a pen to the right right the left and a pen to the right right both valid operations let's look what both valid operations let's look what that's going to look like we have to do that's going to look like we have to do that twice so we're going to pop the 2 that twice so we're going to pop the 2 add it to the back so then we will have add it to the back so then we will have one three two one three two and then we do that one more time and then we do that one more time so we're going to pop the one added to so we're going to pop the one added to the back the back and we'll have three two one so you can and we'll have three two one so you can see like you keep doing this like we're see like you keep doing this like we're gonna do one more maybe so if you want gonna do one more maybe so if you want to add a four you do the same thing you to add a four you do the same thing you would say okay well actually I guess like a slight optimization I mean I guess it doesn't really matter um let me think about that no actually no you do you do need to insert the element first yeah you do need to insert the new amount first because we're not allowed to insert out the front so you do have to insert the new element first and then rotate everything around but yeah so so you would for a four you would add a four you would do a normal append and then you would do this like Loop thing three times so after one iteration you'd have two one four three you would get pushed out and pop back in and you would do it two more times so then you would have this then one more time so four three two one so essentially your Q is a reverse stack and then a pop is really easy because we just pop left and a top is really easy because we are allowed to look at the zeroth element and that's going to be that and then for the empty it's the same thing like you just check for the size so that's the one Q implementation I don't think you can make it more efficient I think you do have to make one one of them o of N and then the other one o one but in this case I kind of swapped it around to show you what that would look like with a 1q and we so for a knit we're gonna have one Q so for a knit we're gonna have one Q so we're gonna call stack so we're gonna call stack but we're going to represent it with a but we're going to represent it with a deck deck for push remember we need to push the for push remember we need to push the element we're going to do a normal element we're going to do a normal appends so self.stack dot push appends so self.stack dot push we're sorry no we can't do click here we're sorry no we can't do click here pen x and now we need to do that Loop pen x and now we need to do that Loop the length of the Q minus one times the length of the Q minus one times because for every element that was in because for every element that was in there before that X we need to rotate it there before that X we need to rotate it around so we could do this we could say around so we could do this we could say for this value that we're not going to for this value that we're not going to be using length self dot stack be using length self dot stack it's one so essentially like if this was it's one so essentially like if this was like three we would do this twice and so like three we would do this twice and so on and if you want to use it if you want on and if you want to use it if you want to have a full Range Loop but you don't to have a full Range Loop but you don't want to like actually use this high want to like actually use this high value you can just do this underscore value you can just do this underscore and that's that'll essentially say like and that's that'll essentially say like I don't want to use this value in my I don't want to use this value in my actual for Loop but I do need to Loop actual for Loop but I do need to Loop you know whatever amount of times this you know whatever amount of times this is is that's how you do that so we're going to that's how you do that so we're going to say self dot stack dot append and then say self dot stack dot append and then we're going to have that pull we're we're going to have that pull we're going to have that popped value you going to have that popped value you could do also do this in two lines if could do also do this in two lines if you want to save the variable so dot you want to save the variable so dot stack dot pop left which is a allowed stack dot pop left which is a allowed operation so essentially we're going to operation so essentially we're going to pop left and then we're going to append pop left and then we're going to append what we popped left what we popped left so if we had something like so if we had something like say we had one two we put on a three we say we had one two we put on a three we would pop the one would pop the one and then we would append it over here and then we would append it over here and we're going to do that twice um yeah now for the pop and the top it's really straightforward because we can just say return self.stack.pop left because now our remember our stack is set up in a way where it's very easy to pop because the the item that would be bought from a stack is now on the left like our cue is a reverse stack essentially then here we could say return cell dot stack zero also really easy because we are allowed to look at the zeroth element um there might be like a top uh method in deck I didn't really look into deck too often I just use the basic stuff in deck like Pulp left push a pen and so on but we are allowed to use a uh Q standards operations including uh Peak pop from front so if there's a peak fall from front that's basically that okay and then for empty also straightforward so we need to return true if it's empty so we can say return true if not self.stack meaning the size of it is zero else false so what this will do is it'll just say like if the stack is like zero that this will evaluate the true and then we will return true otherwise it will be false oh yeah but that's pretty much it so pretty straightforward once you once you like recognize what you're doing and I would say for these problems I think it's pretty important to just like write out your steps and make sure it's kind of correct because it's very easy to it's hard to visualize it so I would try and try if you know if you do two cues two stacks whatever it is try to draw them out and see like okay here's here's like a sample operation here would be a cue with like three elements let's try to like put in the fourth element and so on so let's try to run this work yeah and you can see it's pretty efficient and yeah I don't believe I used anything that was not allowed so a pen was allowed let me just double check real quick though yeah so push to back which is append Peak from front which is Pub left and then Peak from or I guess this is the peak this is the pop so we didn't use anything that wasn't allowed and now let's go through the time and space and we can do this for uh every single methods obviously and it doesn't really matter so for push it's going to be o of n because we have to essentially reverse our stuff then for pop and top and empty it's going to be o of one because we are just doing one pop this as well and pop left in a deck is o1 um and you can actually if you want to and I did do this in JavaScript for example so the way you can make a queue or an array using an object and then if you are if your like front is deleted like normally in an array you have to shift everything over but if you use an object with keys all you have to do is just shift your starting key and your last key and then your your index can just be in your keys uh maybe I'll do the problem on that like later on but essentially like if you're starting key was one and your last key was six and you were accessing like element zero then element zero would be your first key and if you're acting something like element at index two or something you just take whatever your first key is and add two so it would actually be at like key three and so on so you don't actually have to shift if you do this doing an object and I did actually make like a deck-like structure in um JavaScript that was I actually tested it against like a JavaScript deck that you could uh import and it was about the same speed so I was kind of happy with that one because in JavaScript uh it doesn't have it doesn't have a queue either it has an array and if you want to use a queue you have to do like shifts which are o of n but anyway that's uh too long about that okay so yeah so this so we do have like our actual deck right so we do have like our actual deck right so that's o of n because we are like so that's o of n because we are like storing all our numbers storing all our numbers um um but we aren't using any other data but we aren't using any other data structures structures so it is over and with two cues so so it is over and with two cues so pretty much with two cues or one it will pretty much with two cues or one it will be the same thing like either way one of be the same thing like either way one of your things will be oven two of them your things will be oven two of them will be o1 or reverse right pop and top will be o1 or reverse right pop and top are the same top and top are the same uh are the same top and top are the same uh time complexity because they're time complexity because they're basically the same thing basically the same thing and uh your space would also be oven and uh your space would also be oven because you'd have two cues which is because you'd have two cues which is still then it would be total n elements still then it would be total n elements so you're not really saving anything so you're not really saving anything it's more just kind of like a cool it's more just kind of like a cool solution to look at solution to look at but yeah um so it's gonna be for this but yeah um so it's gonna be for this Pro I hope you liked it and if you did Pro I hope you liked it and if you did please like the video and subscribe to please like the video and subscribe to the channel and I'll see in the next one the channel and I'll see in the next one thanks for watching | 2024-03-22 10:59:17 | 225 | Implement Stack Using Queues - LeetCode 225 - Python |
|
Y-uGoJqDtBM | Hello hello everyone welcome to difficult challenge today's question is the largest challenge today's question is the largest time from giving details should give in time from giving details should give in any with after land for india to generate any with after land for india to generate maximum time button video politician id am maximum time button video politician id am id for the time 4 minutes ago id for the time 4 minutes ago 220 this simple question is innovation award 220 this simple question is innovation award recruitment of recruitment of recruitment of day laddu solution and think of doing and Thursday subscribed bigg boss Thursday subscribed bigg boss 102 views one time in two variables maximum 102 views one time in two variables maximum time fix - 110 test max time fix - 110 test max player max and time fix - path of player max and time fix - path of freedom created freedom created freedom created night minute media 20 minutes ago then serial se new year stitch do i will it dropped from i10 i20 that pointers her thrust length that pointers her thrust length and g plus plus and g plus plus e want another law intern k10 k20 2010 e want another law intern k10 k20 2010 k plus k plus k plus Keep In Mind As Always Looks Forward To Feel Right For Its Time That Is And The Other Is Necessary I Is Suggested And The Induction Same Script Is On WWW Subscribe Simply Continue Otherwise What You Want To Is Cute Time Time Time In This Form And The Time With Your Dreams Are Not For The Spot Inter Arts Subject 205 The Signing Different Indices Different Bollywood Stars Pallu Aaj Minutes Of Units Part Hua Ki Peoples To Ki Mujhe Yeh Baje Mujhe School At Times That Vegetables Done With Vegetables Done With Vegetables Done With R Universe And Support Nodal Officer For The R Universe And Support Nodal Officer For The Minute Spot Minute Science Paper E Want Arvind Singh Minutes Units Particular To 9 6 - Is - 2 - K Notification With Logic 6 - - - For 123 Different 6 plus one - - - Subscribe to Different 6 plus one - - - Subscribe to Hello friends the fourth part will Hello friends the fourth part will automatically with two 6 - - - K What automatically with two 6 - - - K What means is maximum wave means is maximum wave that i plus plus k in the equations 512 Calculator for the next in the equations 512 Calculator for the next speaker used this value and calculate speaker used this value and calculate speaker used this value and calculate Soldiers Call Airtel 102 That Album Equals 12 Alex Reed Axel Exactly 6 - Came - From - Decade A Positive A A Writing Turbo and Unlimited Calculate The Art Center Art What Is The Hotspot Ki Khushboo I Laugh I Laugh I Laugh spot aplus aplus 8 minutes means unit record the hotspot 8 minutes means unit record the hotspot turn now spot is aa this election 2014 the turn now spot is aa this election 2014 the course of per limit course of per limit i only minutes equal school day 60th i only minutes equal school day 60th job limit for 2 minutes part job limit for 2 minutes part Ki End Time Fix Total Time Sadhe Loot-Loot Ki End Time Fix Total Time Sadhe Loot-Loot Conversion From 8 Minutes Total Time Conversion From 8 Minutes Total Time Exactly To Ki Aaj * 6 10 Foot Mathematics Yasmin And Defeated Total Time To Be Greater Than Next Time Ki School Image Divya Shringaar Time Bank Will Update The Next Bank Will Update The Next Bank Will Update The Next Time With Total Time That I Will Reduce Information Maths of A Hard Max Minutes of Badot 2 Minute A Hard Max Minutes of Badot 2 Minute Spot Spot That Pandey Almost All Have That Pandey Almost All Have 220m to Take Another Corner How into 220m to Take Another Corner How into Consideration The Facts Consideration The Facts That Sequence Se Minus One The That Sequence Se Minus One The Boys Boys Boys minus one simple tone mp tenth court case details unit when you for the number you for the time using this and twelfth result return i maths i maths and cumbersome's half mic search plus fluid plus minus the To adjust dusu president To adjust dusu president To adjust dusu president fateh nagar contact cassette unit collected fateh nagar contact cassette unit collected for pimples infections kmsraj51 to 180 and not supported sites 935 se bindh part form of two digits of the earth and of minutes with to update whose something like video 945 and easy connection maximo latest A grand salute and A grand salute and A grand salute and creating another method private reduce creating another method private reduce friend drafting password enter number friend drafting password enter number that tomorrow cant board 10 number to spring spr that tomorrow cant board 10 number to spring spr i anil check for sbi dot length ki kursi kursi one in that case close up and ki when bus ki when bus i anil simply i anil simply A written S P R O A written S P R O that institute of mess and all this method that that institute of mess and all this method that parking parking a dark successful method Mridul Padak country a dark successful method Mridul Padak country wise eight phoolan 8 minutes show chhod bhi 808 wise eight phoolan 8 minutes show chhod bhi 808 note 800 cutting third semester system note 800 cutting third semester system is on and test top is on and test top were high court in a grant were high court in a grant were high court in a grant one blind research and one to that Chaupasni time Indological hair hair that Chaupasni time Indological hair hair observed mathematical and exploited by 60 updated on that maybe sorry for that maybe sorry for that order updates Pradhan Sube Singh B | 2024-03-25 12:08:09 | 949 | Largest Time for Given Digits | Leetcode September Challenge (Day1) | Leetcode 949 |
|
5FWc--uZRwo | Everyone welcome to my channel code sari with mike so today we are going to mike so today we are going to do video number 70 of our playlist lead code do video number 70 of our playlist lead code number 1424 is a very easy question number 1424 is a very easy question and already we have made another question which and already we have made another question which is exact same diagonal traverse one is exact same diagonal traverse one on that. on that. on that. playlist, you will get it in the same playlist, today its part two is ok, this has also been added by google3 since names are given, return all elements of names in diagonal order as This one is diagonal, you are looking at the direction of the This one is diagonal, you are looking at the direction of the This one is diagonal, you are looking at the direction of the diagonal, see diagonal, see how it is, is it like this? Look, the first how it is, is it like this? Look, the first diagonal that you see is the one in which diagonal that you see is the one in which element number is one, this one has only element number is one, this one has only one in it, so see, first one is written, after that one in it, so see, first one is written, after that see, it is 42, okay. see, it is 42, okay. see, it is 42, okay. 753, after that 8 6, after that no, this is the answer, see how simple it is, let's see how we can traverse, the most important thing, let me tell you, we will understand this from the example, but before that Always remember that whenever we talk about diagonal traversal, whether it is a tree or a D- matrix, always think about the map. In diagonal traversal part one also we used the map. Okay, we will use the map in diagonal traversal part two also. So we will understand it from two approaches, the first approach is the most trivia, using map is fine and the second approach is quite unique, the second approach is but simple, there is nothing tough in it, it allows us to figure out things, the rest of the code is very So first let's learn from approach one So first let's learn from approach one So first let's learn from approach one and finish it. Okay, so let's and finish it. Okay, so let's follow the values. This is your example, so I follow the values. This is your example, so I told you that in Diagonal Russell Part One, told you that in Diagonal Russell Part One, I told you that either now I told you that either now I told you or not. I told you or not. I told you or not. talk about diagonals, we will use a map, then understand what we do in the map, like the elements of diagonal, like look at this, then look at this, look at this, look at this, look at this, then before the diagonal element, I write, one is the This is mine, let's This is mine, let's This is mine, let's see what its index is: 0 0 is the diagonal see what its index is: 0 0 is the diagonal element and which one is brother 4 2, one is element and which one is brother 4 2, one is fine, this is the second diagonal, let's fine, this is the second diagonal, let's see its index, what is the index of four? 1 is 0 and what is the value of two? is the index of four? 1 is 0 and what is the value of two? is the index of four? 1 is 0 and what is the value of two? after that 753 is 753 what is the sen let's see what is the 2 0 f 1 what is the coordinate of 1 and 3 see so 1 is 2 not one 0 2 is not 0 2 is okay so I if You will write all the diagonal elements. Okay, if you write all the diagonal elements, then look at this diagonal carefully. Its row is zero. If the column is zero, then the row plus column will not be a constant. For this, the row will be zero. Look for this. Let's add more columns. Are there any more 0 Is there not 1 P 0 One has come let's see its 0 P 1 0 P 1 This also one has come so see For this its row plus column is constant For this its row plus column is constant Let's What is the value of row plus column? What is the value of row plus column? What is the value of row plus column? 2 p 0 2 1 p 1 2 0 p 2 2. You are seeing that 2 p 0 2 1 p 1 2 0 p 2 2. You are seeing that this also has a column constant. Sorry, row this also has a column constant. Sorry, row plus column is a constant, so every time we plus column is a constant, so every time we know what we do which is row plus column. know what we do which is row plus column. There are rows There are rows plus rows plus columns in the map, let's take the value of that and plus rows plus columns in the map, let's take the value of that and what values are there in that row plus column, what values are there in that row plus column, store it store it in a vector. Okay, so as the values go by, let's in a vector. Okay, so as the values go by, let's assume that you are here. assume that you are here. Okay, let's remove the diagonal, just Okay, let's remove the diagonal, just assume that you are standing at 0 0. If you are assume that you are standing at 0 0. If you are standing here, what is its row, what is its row and column, what is row, row standing here, what is its row, what is its row and column, what is row, row plus column, what will come, zero will come, row plus column, what will come, zero will come, row plus column will come, zero, who is beyond that? plus column will come, zero, who is beyond that? I have inserted Sa element, who is 0 0 P I have inserted Sa element, who is 0 0 P is one, I have put one. Now let's assume that you is one, I have put one. Now let's assume that you come here, let's look at its rows and columns. Row plus come here, let's look at its rows and columns. Row plus column 0 When P and W came, look at one. This is element column 0 When P and W came, look at one. This is element number two. Okay, now let's look at this. number two. Okay, now let's look at this. P 2 isn't its row zero and column T 0 P 2 P 2 isn't its row zero and column T 0 P 2 2 will come so two on one has come 3 Okay now pay 2 will come so two on one has come 3 Okay now pay attention there are more things to focus on here attention there are more things to focus on here don't miss now don't miss now watch the video here come to this watch the video here come to this watch the video here come to this row is one, column is zero, 1 is 0 and if it comes then there is already one in the map, so we will add it there, which one is 0, four is four, we have put it, we are seeing the benefit of the map. Look, the advantage is that the row plus column is a constant, right, so put 0 and 4 in it, both were members of the same diagonal, okay, let's move ahead now, Abhay, you have come to F, but But But But look, one more element has come, along with 3, 5 has come, look, one more element has come, along with 3, 5 has come, okay, let's look at it. 1 P 2 is 3, okay, let's look at it. 1 P 2 is 3, so there was no t, there was no plus column, so we have so there was no t, there was no plus column, so we have put th here, put six, now let's put th here, put six, now let's come here 2. come here 2. come here 2. column i.e. one more element has come in two so two is 7 ok now come here one more 8 has come in 2 P 1 3 3 ok ok now let's come to the last element what is its row? One last element has come on 2 p 2 4 four. That's right, so now pay attention. If you traverse this map, you will get diagonal elements. Look, which is the first element? So one. Have put one, let's see the second one. 2 fo is ok but see the problem. Now you must be seeing something like 2 4. Do you understand the meaning, every diagonal element is coming upside down? 2 fo has come upside down, whereas How did it have to be done, did How did it have to be done, did How did it have to be done, did n't it have to be done like this, so instead of doing 2 fo's, n't it have to be done like this, so instead of doing 2 fo's, you have to do 4's, either you reverse it, it is here only or it is torn, either reverse it and get it you have to do 4's, either you reverse it, it is here only or it is torn, either reverse it and get it printed, printed, okay, either get it printed from here in this hey. okay, either get it printed from here in this hey. Two, first write four, then Two, first write four, then write two. It's okay, so first we will write two. It's okay, so first we will write four. It's okay and write four. It's okay and after that we will write two. Okay, after that see 357, we will also after that we will write two. Okay, after that see 357, we will also write it in reverse. 753, see write it in reverse. 753, see 753, so why write it in reverse, why was it necessary, 753, so why write it in reverse, why was it necessary, you saw it here. you saw it here. you saw it here. 753. Okay, after that, see 8 6. After that, see, our answer has come. Okay, what you had to pay attention to is that here you will have to traverse upside down. You will have to traverse upside down. When you came here, you did one. If you 86 9 On the contrary, you just have to 86 9 On the contrary, you just have to 86 9 On the contrary, you just have to print the values, so the solution has come here, it print the values, so the solution has come here, it is okay for you, then is okay for you, then one more thing you can do is that when you are one more thing you can do is that when you are storing in the map, then at that time you should storing in the map, then at that time you should store it in such a way that already store it in such a way that already store it in such a way that already meaning there should be 42 stores here instead of 2, 4. How can you do that, I will show you right now, see immediately, anyway you can do it, so see, before starting, I will tell you. Many people may question that brother, how can this brain be used? How will it come to someone's mind that if it has to be printed in reverse in the map then it will have to be done like this? How can it come to in the map then it will have to be done like this? How can it come to someone's mind? So I say, someone's mind? So I say, come on, understand it. come on, understand it. come on, understand it. last time you started your traversal like this, then again like this, it is obvious that you must have started from row number zero, that is why You must have done this, You must have done this, You must have done this, then four would have come, then you are moving upside down. then four would have come, then you are moving upside down. You are moving upside down, that is why it will be You are moving upside down, that is why it will be printed upside down for you, printed upside down for you, how in which order you wanted it in the map, it how in which order you wanted it in the map, it was wanted in this order, because of the value, was wanted in this order, because of the value, look at this diagonal. look at this diagonal. look at this diagonal. then why don't you start the row from here? If you are starting from here, that is why it was printing upside down, that is why I say start the row from the end, because see, It is the same for everyone, this is the It is the same for everyone, this is the It is the same for everyone, this is the correct order, from bottom to top, correct order, from bottom to top, look at the arrow here too, look here, the look at the arrow here too, look here, the arrow is going from bottom to top, so let's start from the bottom arrow, let's see if we can find our solution, otherwise I will tell you. find our solution, otherwise I will tell you. find our solution, otherwise I will tell you. going to start from here, okay, we will start from Sen, what is its row, two is the column, zero is 2, 0, that is, zero has come in it, 7, now let's come to this, what is its row, what is the two column, one, okay, so 2. P has come on 3rd 8 Its row is 2 2 4 It has come on four Okay, after that again we will come here Row on my side Okay now print has come Four row is one column G0 1 P 0 Four on one has come Four has come on 1, okay, now look here, there is no profit, that is, on 1 P, 2, F will come. Look, on T, now F has come. Now see, the order is coming right. First Sen has come, now F is coming, isn't it now 1 P? 2 means that 1 will come on th, see, the order of this is also correct. First A came, then six came, now Ro will go up. On doing Ro minus minus, one went to zero, Ro came to one and 0 came to 1, T came i.e. One more element has arrived at 1 See this also It is being printed in the order 0 P 2 Another element has arrived at 2 3 See this also It is printed exactly in the order This time all the elements have been printed exactly like this Map Pay attention 753 753 8 6 8 6 753 421 9 Look 421 986 753 Okay, it is clear till now that we have corrected the order, yours is correct, now look, pay attention, how should your answer have There There There should be one print first, after that 42 42, should be one print first, after that 42 42, after that 753 753. Okay, so look at the diagonal after that 753 753. Okay, so look at the diagonal number number zero 0 p 0, this one is getting printed first, zero 0 p 0, this one is getting printed first, so let's start from row, that is, I am so let's start from row, that is, I am saying diagonal diagonal or row saying diagonal diagonal or row plus. plus. plus. Okay, let's print the row first, so whoever comes to the row, who is brother, one is one, has printed it. After that, do plus plus on the diagonal, that is, you have reached the second diagonal. Brother, who is on the one diagonal? Print 4 2 4 2 directly on it. There is no need to reverse it. We had printed it in the correct order and stored it in the map. It is ok in the map. Plus the diagonal Okay, Okay, Okay, diagonal number two has come, look, this is it, isn't it? diagonal number two has come, look, this is it, isn't it? Look, this is 753. This is Look, this is 753. This is 753. You are looking at 753. You are looking at 753. After that diagonal diagonal will be called 753. After that diagonal diagonal will be called plus plus. Then plus plus. Then diagonal number three has come. This is diagonal number 8. After that, diagonal number three has come. This is diagonal number 8. After that, diagonal plus. diagonal plus. diagonal plus. four came, isn't it okay? After that, if you did diagonal plus plus then F came, there is no F. That was all from zero till diagonal number four. So my story ends here, my It was simple, good thing It was simple, good thing It was simple, good thing you came to know here that you came to know here that if you had started the traversal from here in the map, then if you had started the traversal from here in the map, then look in the map, the elements stored in the correct order are look in the map, the elements stored in the correct order are 75 386, so 75 386, so let's finish it by coding it quickly let's finish it by coding it quickly and then and then and then come to approach two. Okay, so let's code it quickly. Okay, everything from my first approach, what I said is that we should always need a map, whenever what we are doing is doing diagonal traversal and Of int m where what is int Of int m where what is int Of int m where what is int means what is my row plus column means what is my row plus column and what are the elements in the diagonal of that row plus column corresponding to it, they will store in the vector okay okay let's will store in the vector okay okay let's start and what I said is that start and what I said is that Why did I start the row from numbers dot size -1? I told you why I started from the bottom row, I told you why I started from the bottom row, so that the elements are stored in the map in the correct order so that so that the elements are stored in the map in the correct order so that you do not have to reverse it. > you do not have to reverse it. > = 0 = 0 row was doing minus minus. row was doing minus minus. row was doing minus minus. go in the same order for int column equal to 0 column e lesson names of row dot size means as many columns as there are in that row will go because row because look the column can also be different look look in the last row there are four Look here and there Look here and there Look here and there are only three columns in the second last row, so the columns are only three columns in the second last row, so the columns can be changed, so each row has different column can be changed, so each row has different column size, so look at the numbers of rows, dot size is size, so look at the numbers of rows, dot size is ok, column plus plus ok, column plus plus is ok, now let's find the value of diagonal is ok, now let's find the value of diagonal int diagonal. int diagonal. int diagonal. push in the value of the same diagonal in the map, which one will be pushed, the numbers of row, one will be pushed, the numbers of row, whatever value is there in the comma call, it was very simple, whatever value is there in the comma call, it was very simple, everything must be clear till now, now let's move ahead, everything must be clear till now, now let's move ahead, form our result. form our result. form our result. result int diagonal starts from zero, remember for and keep adding plus plus to the diagonal till how long will you keep doing it until mp5 is the value of the diagonal found is not equal to mp.in If found then the value of the diagonal. Will keep printing the elements of OK for int and nam app, print it from as many elements as possible in this diagonal of the app, ok result dr here nam is printed, save means here nam is printed, save means stored in the result, ok and stored in the result, ok and stored in the result, ok and I had said that keep doing plus plus on the diagonal, as soon as the value of diagonal comes to the value which is not present in the map, then the while loop will break our and return result in the last, ok, let's Fully we should be able to Fully we should be able to Fully we should be able to pass all the cases its time total number of elements because we are visiting all the elements only once maximum is ok so off and time complex is t and its space also if you This is because we have This is because we have This is because we have stored all the elements in the map. Okay, stored all the elements in the map. Okay, so I hope this approach is clear. so I hope this approach is clear. Now quickly let's go to approach two. Indeed yes, Now quickly let's go to approach two. Indeed yes, this approach of ours has been accepted. this approach of ours has been accepted. Quickly now if we understand approach two, then Quickly now if we understand approach two, then look at the approach. look at the approach. look at the approach. see, I will not tell directly that yes it is BFS, then do it like this, I never make it in videos, I always tell the thought process, so I want to tell you that it is very strange, Some people will think that this Some people will think that this Some people will think that this can be done with BFS, okay then I am presenting you Intu and its thought can be done with BFS, okay then I am presenting you Intu and its thought process in my own way. process in my own way. Now try to understand. See if Now try to understand. See if you remember what is the purpose of BFS. Let us you remember what is the purpose of BFS. Let us assume that this is some source. assume that this is some source. assume that this is some source. what BFS does is that you can traverse through this source level by level. Let's assume this is a source, then the next level is this. The number of elements we visit there, after that the next All those elements are All those elements are All those elements are visited at once, isn't it, then the next level is this, the visited at once, isn't it, then the next level is this, the next level is y, and the meaning of the next level is y, and the meaning of the whole level can be understood like this, whole level can be understood like this, meaning it does level by level traversal, meaning it does level by level traversal, that is correct, so this level number has become zero, that is correct, so this level number has become zero, level number. level number. level number. on, okay, that is the purpose of BFS, isn't it? Print all the levels at once, so do you know what is its thought process, if we assume that you have accepted this as the source? Okay, if you consider this as a source, then look, what is the next level of this source, look, it is this one, the next level after that is this one, what is the next level after that, This is the This is the This is the source starting from 0 co 0 source starting from 0 co 0 its next level look this is its its next level look this is its next level then this is its next level then this is the next level then this is its next level then this is the next level then this is the next level this is this this is this next level then this is the next level this is this this is this so what is so what is actually happening in BFS actually happening in BFS actually happening in BFS by level, we have to traverse it, we just have to pay attention in the towsal that the printing should be like this, from bottom to top, okay, here I understood that okay, someone can think that yes, Okay, so as soon as it is Okay, so as soon as it is Okay, so as soon as it is understood that a good BFS understood that a good BFS can be installed, then again the question comes can be installed, then again the question comes that okay, BFS can be installed, that okay, BFS can be installed, now let's see how to install it. Okay, so now let's see how to install it. Okay, so now look, pay attention here I told you. now look, pay attention here I told you. now look, pay attention here I told you. I considered as the source? Have I considered 0 as the source? What did you always do in BFS? Do you remember that you used to put the source in q first? It is obvious that things are starting from there. Okay, this is my We will approach it directly like a thought process, We will approach it directly like a thought process, We will approach it directly like a thought process, I will not I will not tell you to push it like this, not in q, tell you to push it like this, not in q, you should understand the reason, what is the nature of q, that is, you should understand the reason, what is the nature of q, that is, what we used to do in BFS, what we used to do in BFS, first put the source in q, then our first put the source in q, then our source. So What we assume is that the source is my for this, who are its neighbours? One is this one and one is this one and first I will put this one, why this one because first I will put one 0, so yes, it is like that, first that element will be printed and then this It will be printed and the order It will be printed and the order It will be printed and the order should also be the same, so I print its neighbors, should also be the same, so I print its neighbors, so its neighbor one is this one, let's so its neighbor one is this one, let's see who is the one below, let's assume that see who is the one below, let's assume that look, row ji was popped, so if this look, row ji was popped, so if this is row and this column. is row and this column. is row and this column. happen at the bottom, look at it, it will be 'Psv', that is, the 'Pv' column is the same, neither is the 'Pv' column or 'V', I have put '0', that is, it is in my queue right now. Okay, after that, Its second neighbor is this, Its second neighbor is this, Its second neighbor is this, its row is the same but the column is + and, its row is the same but the column is + and, right, that means I am saying that if this right, that means I am saying that if this is r c then r is + 1, this is and this is r + 1 c. So far it is r c then r is + 1, this is and this is r + 1 c. So far it is clear, then what else? is clear, then what else? is clear, then what else? 1, okay, I have put it, now you see what we will do, then we will tell this guy, we will remove him first, see, all his neighbors are covered 0 0, now one more level has been printed, Let's pop this, okay, 1 0 has been Let's pop this, okay, 1 0 has been Let's pop this, okay, 1 0 has been popped, 1 0 has been popped, okay now you popped, 1 0 has been popped, okay now you will say 1 0, if you put your neighbor, then 1 0 will will say 1 0, if you put your neighbor, then 1 0 will be said, brother, my neighbor is one below be said, brother, my neighbor is one below and this one is below, okay now and this one is below, okay now and this one is below, okay now paying attention is a very important part, here see who is this one of your neighbours, see if the one below is 2 0, then put that one is fine and look at the other neighbor, who is Wow, this one is fine, put Wow, These were the two neighbors, he These were the two neighbors, he These were the two neighbors, he printed it, now the next element at this level is printed it, now the next element at this level is Row, I popped 0 and Row, I popped 0 and now look, pay attention, zero earning means this one, now look, pay attention, zero earning means this one, see who are its neighbors, one see who are its neighbors, one is this one, one is this one, so first. is this one, one is this one, so first. is this one, one is this one, so first. print the one below only so that it gets printed in such order. Okay, so first look at the one below, what is its index. What is its index? Just pay attention, Nav, we have already printed it and have added it. There will be And And And Vanav is coming, okay, so either you Vanav is coming, okay, so either you can do it like this, take a map or can do it like this, take a map or make a visit, okay and write there make a visit, okay and write there that if we have put it in Nav, then that if we have put it in Nav, then mark Vanav Kaam as white. mark Vanav Kaam as white. mark Vanav Kaam as white. then you will not put it in the queue again because this guy, look, let me tell you again, this guy has put 0 and he has put this and he has put this, so this guy is also in this level, in the level that was going on, he has If you put it in then see that it has been If you put it in then see that it has been If you put it in then see that it has been inserted twice, otherwise if you had marked the vegetable, it would inserted twice, otherwise if you had marked the vegetable, it would not have been inserted twice, that is fine, then not have been inserted twice, that is fine, then you can take the vegetable separately and you can take the vegetable separately and mark it as true, but it should be there even without the visitor. mark it as true, but it should be there even without the visitor. mark it as true, but it should be there even without the visitor. possible if you put a simple cheque, that check can also be done, let me explain to you, first of all understand that yes, we will mark it as visited, then after that, if it is wasted, then it is not put After this, his next After this, his next After this, his next neighbor was Nana Rotu, so that's the thing, he has neighbor was Nana Rotu, so that's the thing, he has not visited yet, so if I put two, not visited yet, so if I put two, then this is my next level also got printed. then this is my next level also got printed. Look, there were three elements, yes, this, this, Look, there were three elements, yes, this, this, 20, 21, and no, 0 and 02. 20, 21, and no, 0 and 02. 20, 21, and no, 0 and 02. diagonal elements are being printed correctly. As you keep on popping, you will keep on printing the same elements. Remember which one was popped first, 0 0 was popped, so whatever element is there in 0 0, Then the element which was in 'V' was Then the element which was in 'V' was Then the element which was in 'V' was added to the result. added to the result. This was also added to the result. Now the turn This was also added to the result. Now the turn will come for the next level. So look at the next level and will come for the next level. So look at the next level and see who is the first one. We will pop 0 0. see who is the first one. We will pop 0 0. Okay, see which 0 it is. Okay, see which 0 it is. Okay, see which 0 it is. will say that brother, okay, so add this and add this, add 0 0 to 0 and add tv to tv, add tv to it, okay this is popped, who is the next guy, what will he Who is this, this is this and this is this, Who is this, this is this and this is this, Who is this, this is this and this is this, this is going to be added again, so we will this is going to be added again, so we will mark it as a visit so that we will not be able to mark it as a visit so that we will not be able to come again, okay then this and this will be added again, so come again, okay then this and this will be added again, so now you understand what we are doing, now you understand what we are doing, right? right? right? element, like 0 is printed, the element which was in forest is printed, then 0 is popped, then its element is printed, so it is being printed in the same order, is I have understood how to do I have understood how to do I have understood how to do it, I just it, I just want to explain one extra thing to you that I want to avoid the separate preparation that has to be taken, so I will I want to avoid the separate preparation that has to be taken, so I will show you how I will avoid it, show you how I will avoid it, okay see. okay see. okay see. trying to take is to mark the data structure as wasted and want to avoid it, so look here, pay attention, in the beginning I had said that 0 0 k is my source, so Given r c, I am taking Given r c, I am taking Given r c, I am taking it as 0 0, so I popped it, it as 0 0, so I popped it, okay, 0 0, I am taking this as r c, okay, so its neighbor is this, isn't this and this, okay, so its neighbor is this, isn't this and this, so okay, meaning row plus and comma. so okay, meaning row plus and comma. Why do we have to put these two column and row comma column plus Why do we have to put these two column and row comma column plus now i.e. aa psv comma now i.e. aa psv comma column and first put this and after that column column and first put this and after that column sorry row comma col plus and ok we have put both of these Gave it Gave it Gave it and inserted it, now pay attention, and inserted it, now pay attention, it is okay, see, now its turn will come, next it is okay, see, now its turn will come, next time this guy will say that I have to time this guy will say that I have to insert this and after that I have to insert this, okay this insert this and after that I have to insert this, okay this guy will say that I have to insert this, guy will say that I have to insert this, but this has already been inserted. but this has already been inserted. but this has already been inserted. put this one and this one, if you have to put this one, then you are looking at this, if you have not put it again, it is okay, then why not put it again, because this guy had put it and eaten it, it is okay, now let's observe the same thing here, here in this one, it is Now, pay attention, Now, pay attention, Now, pay attention, what will this guy say that I have to put this neighbor what will this guy say that I have to put this neighbor and I have to put this neighbor, okay and I have to put this neighbor, okay because yes, the diagonal element is because yes, the diagonal element is going like this, so first this will come, then this will come, okay, so going like this, so first this will come, then this will come, okay, so he said that I will put this first. he said that I will put this first. After that, I will put it, okay, then what will he After that, I will put it, okay, then what will he do? Will he say, no, I will not do? Will he say, no, I will not put it because it has already been put, that's it, I will put it, put it because it has already been put, that's it, I will put it, okay, I will not put it, okay, I will not put it, he said, I will not put it, it has already been put, just I Have seen Have seen Have seen this, now let's look at this diagonal this, now let's look at this diagonal element, this guy will also say the same thing that I will element, this guy will also say the same thing that I will not put the one below because it has already been not put the one below because it has already been inserted, here I will just inserted, here I will just put this one, so one thing you are paying attention to is that put this one, so one thing you are paying attention to is that only the elements with column zero are column zero. only the elements with column zero are column zero. only the elements with column zero are column zero. bottom element and the right one are able to be inserted. Look at the rest. Pay attention. The rest of the diagonal elements are able to insert only the one on the right side. Okay, what does this mean, like look anywhere, it will be He is the guy with column zero. He is the guy with column zero. He is the guy with column zero. No matter what. Column No matter what. Column is zero. Look, he had put this one too. After is zero. Look, he had put this one too. After that, he had put this one. After that, this guy had that, he had put this one. After that, this guy had not put the one below because he had already not put the one below because he had already put this one. It's fine, he just put this one. It's fine, he just wrote it. wrote it. wrote it. will do the same thing that if the column which is there is zero then it is okay then only who will we put in it means dot push, who is the guy at the bottom brother, the row plus and comma column is clear till here, this That's why I That's why I That's why I told you separately here that if the column is zero then it is told you separately here that if the column is zero then it is right then only the one below will be inserted, right then only the one below will be inserted, look at the column row comma, it will be look at the column row comma, it will be clear from here, again let me tell you why the source has inserted these two. Had these and these, now it is their turn, so first this guy will pop up, he will say, brother, I am column zero, so I will put this one too, and I will put this one too, look, I will put the one below too, see, this one below is the one below, so So it has been inserted and I will put this also, So it has been inserted and I will put this also, So it has been inserted and I will put this also, so both of them have been visited, okay, so both of them have been visited, okay, so I will write v here for now so I will write v here for now that both are printed, now it is its that both are printed, now it is its turn, it will say that brother, I turn, it will say that brother, I am not column zero, right? am not column zero, right? will just put the right one, so if it has been visited, then look, this will just put the right one, so if it has been visited, then look, this diagonal one has been completely visited, okay, that's diagonal one has been completely visited, okay, that's why I have put a check here that the one why I have put a check here that the one with column zero should not only with column zero should not only put the element at the bottom. put the element at the bottom. put the element at the bottom. element has two neighbors, one below and one on the right side, so what about the one on the right side, the row is the same, the column is plus and it will be ok, so there is no check in it, the The row is the same The row is the same The row is the same and the column is plus and these are the two things we have to push, and the column is plus and these are the two things we have to push, one this and one this, it's okay, just one this and one this, it's okay, just check one thing that if you are putting the row float, check one thing that if you are putting the row float, then check that the row float is out then check that the row float is out of bounds. of bounds. of bounds. that row psv which is less than those numbers, dot size should be there, should not be out of bounds. If you are putting column plv here also, then put a check here also if Lesson: whatever row is there, it Lesson: whatever row is there, it Lesson: whatever row is there, it should be less than the column size, it should not be out of bounds, otherwise should be less than the column size, it should not be out of bounds, otherwise you will have to put a check you will have to put a check anyway because if you are putting row plus one, if you are anyway because if you are putting row plus one, if you are putting column plus one, then you will have to put a check for out of bounds. putting column plus one, then you will have to put a check for out of bounds. putting column plus one, then you will have to put a check for out of bounds. most important check was that only those elements in the column which has zero are able to insert the elements below, I am not allowing the rest to be inserted because it will be duplicated, then that is there, see, If you If you If you don't have to see the dry run then try it, I will do a don't have to see the dry run then try it, I will do a simple dry run simple dry run for you 1 2 3 4 5 6 6 789 ok index for you 1 2 3 4 5 6 6 789 ok index number 012 012 ok let's start with K number 012 012 ok let's start with K first put 0 0 ok this one first put 0 0 ok this one first put 0 0 ok this one visited. It has been visited. Let's pop it. 0 0 has been printed. Let's look at its element zero's neighbor of zero, who is four and two, so since its column is zero, this is as, so this is the one below. So he has put 0 and 0 and who has to put 0 and 0? Okay, these are the elements of the next level. Now the first element in the next level is 1 0 1 0. Its row is r and its column is zero. So, since its column is zero, what will we do, we will put its bottom element also, look, we will put this also, two comma 0 and its right element, we will put one comma, vav and so on, you can complete it easily, but I think Main important point is understood let's Main important point is understood let's Main important point is understood let's code quickly and just code quickly and just finish it ok let's make it from approach two finish it ok let's make it from approach two i.e. using BFS i.e. using BFS In BFS what we always take first is In BFS what we always take first is q of int k but since this time we have q of int k but since this time we have q of int k but since this time we have store the coordinates then we take pair of int comma int so that we can store the row comma call. Okay first of all push the source two sources remember who we killed 0 0 is okay and In which as soon as In which as soon as In which as soon as the elements are popped, they will be added to the result, while the elements are popped, they will be added to the result, while not off cud MT, the same not off cud MT, the same old code of our BFS, first of all, take old code of our BFS, first of all, take out the a, row out the a, row comma, call is taken out, q is fine from the front, comma, call is taken out, q is fine from the front, q, the dot is popped, now look, pay attention. q, the dot is popped, now look, pay attention. q, the dot is popped, now look, pay attention. soon as it has been popped, put it in the push under back. You will put this in the numbers of row comma call because you have just popped it. Now look, pay attention. I told you that why do we have to push two people, one is And one is on the right side, And one is on the right side, And one is on the right side, then who has to do row plus one, that is, then who has to do row plus one, that is, this guy is below, the column is the same, this guy is below, the column is the same, but I had said, for but I had said, for whom will we insert the element below, only if the column is zero, otherwise whom will we insert the element below, only if the column is zero, otherwise duplicate elements will come. duplicate elements will come. Okay, and since row. Okay, and since row. Okay, and since row. check for 'Row' whether it is 'Row' or not 'Row plus one', what you are entering should be less than the numbers dot size on the right so that it does not go out of bounds, okay after that the neighbor on the right side Which row will be the same? Which row will be the same? Which row will be the same? Column will change but since row plus Column will change but since row plus column is P then check the out of bounds of column P1. column is P then check the out of bounds of column P1. It should be smaller than the numbers of row dot size. It should be smaller than the numbers of row dot size. Till here it is clear and Till here it is clear and in the last return result to us. in the last return result to us. in the last return result to us. simple code it was but it was one of the most beautiful use of BFS I have ever seen when I did completion and pay a little attention to the space complexity. completion and pay a little attention to the space complexity. What could be the largest size of q What could be the largest size of q which would be the largest diagonal of this number? which would be the largest diagonal of this number? Okay, so I can say like this, the maximum Okay, so I can say like this, the maximum diagonal size is not diagonal, diagonal size is not diagonal, meaning the maximum diagonal is the largest diagonal which will have the meaning the maximum diagonal is the largest diagonal which will have the maximum number of elements. The maximum number of elements. The size of q will be maximum only so much, otherwise it will be size of q will be maximum only so much, otherwise it will be smaller than that. Okay, so the maximum smaller than that. Okay, so the maximum diagonal size can be calculated mathematically in any way you want. diagonal size can be calculated mathematically in any way you want. diagonal size can be calculated mathematically in any way you want. want, you can find it, okay, if we assume that in the year case, n is the cross of n, if you have got it, then you datchi. | 2024-03-21 01:21:02 | 1,424 | Diagonal Traverse II | 2 Approaches | Map | BFS | GOOGLE | Leetcode-1424 |
|
8Nt7R-V0TOQ | hello everyone this is cpedit and in this video we'll be solving this and in this video we'll be solving this problem repeated substring problem repeated substring pattern so in this problem we have to pattern so in this problem we have to tell tell whether we can create this original whether we can create this original string using string using multiple copies of its substring multiple copies of its substring so let's get started so let's get started so for example the input is abab so for example the input is abab so so the example is so so the example is a b a b so a b a b so if we choose this sub string if we choose this sub string and we use this substring two times and we use this substring two times then the substring will be the string then the substring will be the string will become will become a b a b so yes we can create the a b a b so yes we can create the original string using original string using this substring so the answer is true in this substring so the answer is true in this case this case now let's see what happens in this now let's see what happens in this example example abc abc abc abc so you can see that abc abc abc abc so you can see that we can create the original string using we can create the original string using substring of length 3 that is substring of length 3 that is abc so one thing that we can abc so one thing that we can readily observe is that zeroth character readily observe is that zeroth character must be part of that substring which we must be part of that substring which we are choosing are choosing it doesn't make any sense to find the it doesn't make any sense to find the substring substring in between the string so we can find the in between the string so we can find the substring substring in the prefix of the string itself in the prefix of the string itself so the second thing we want to observe so the second thing we want to observe is how many is how many patterns that we can choose patterns that we can choose so if let's say the so if let's say the length of substring is n and let's say length of substring is n and let's say we have we have the character as a 1 a 2 the character as a 1 a 2 a 3 so let's say n a 3 so let's say n is 6 in the first case so a1 is 6 in the first case so a1 a2 a3 a4 a5 and a2 a3 a4 a5 and a6 so in this case we can choose the a6 so in this case we can choose the substring of substring of true length because we can create this true length because we can create this plus this plus this we can also choose plus this plus this we can also choose the substring of the substring of 3 length so the pattern can be this but we cannot choose a substring of length 4 because if we do so we'll end up with only two elements and we won't be able to complete the original string so let's see what happens in n equals to seven so it is a b c d e f and g so we have seven characters in this string so if we choose one we can do so so we can choose one but now we cannot choose any other substring because if we choose even two we won't be able to we'll be left with one extra character at the end and if we choose three we will still be left with one extra character at the end so this gives us an idea that we can only choose the pattern length which is a divisor of m pattern length so we need not check every every prefix so we need not check every every prefix so we won't be checking every prefix so we won't be checking every prefix like this prefix this like this prefix this and then three length then four length and then three length then four length and so on and so forth and so on and so forth we just need all the lengths which are we just need all the lengths which are divisor of n so that gives us a divisor of n so that gives us a very good starting point and let's see very good starting point and let's see what are the constraints what are the constraints so they are saying that the constraints so they are saying that the constraints will be 10 raised to power 4 so length will be 10 raised to power 4 so length of of input will never exceed 10 raised to r4 input will never exceed 10 raised to r4 so if we see how many factors so if we see how many factors how many maximum factors a number of how many maximum factors a number of this size this size can have we find that no number will be can have we find that no number will be having having factors more than 64. so let's see how factors more than 64. so let's see how we can do that we can do that so what we can do is of n check if the prefix of that is a pattern else we can say that no pattern was else we can say that no pattern was found so we can simply return false so let's see how we can code this problem so for i equals to 2 to square root of n we are finding all the factors of m [Music] so for every factor we are checking if this is a valid pattern so we have send two arguments the pattern and the string text itself and then we'll be checking if it is up if it can form the original text so if it can will return true so one thing to note is that this for loop will be called only at most 64 times so this for loop will not be called more than 64 times so yes this is accepted so that's all for this video see you in the next one i hope you like this one please like share and subscribe our channel | 2024-03-22 14:51:47 | 459 | Repeated Substring Pattern | LeetCode | September LeetCoding Challenge | Factorization | Strings |
|
Ccxgs0zMizk | hey everyone so we are looking at leak code 392 is subsequence and this is going to be building off of that work that we've been talking about previously in this data structures and algorithms series so hopefully you've seen the last video where you have a solid understanding of some of the logic and how to approach these coding interview questions so let's jump into this one we're given two strings s and t right and we would just want to return true if it's a subsequence else we're going to return false so what is a subsequence the leak code explanation is here but i think it's a little bit convoluted and we can simplify that by just checking out an example so if we look at example one that we're given here s is equal to a b and c and t is equal to a h b g d and c right so essentially a subsequence will be if all of these characters that we're seeing here in a if all these characters exist somewhere in t in the same order that they are in s right so if there's letters in between like you can see a is here and b is here but we've got an h in between that doesn't matter we can just ignore that h right and then we can see here we have a c but g and d are in the way that doesn't matter we can just ignore g and d and so we can see that yes a is here right b is here and c is here so yes s is a subsequence of t because a b and c exists t in that order and we just ignore the characters in between so that's essentially what a subsequence is so knowing that we can break down this problem and try and tackle okay how how do we actually solve this problem right how do we actually implement this problem into code so what we'll end up doing is we'll be using a counter that's kind of the common naming convention convention for it in python of course like always you could call it whatever you want um but we'll call it um i call it tracker let's say right let's call it a tracker so essentially what we would do is we'd have our tracker value here and we'd start with it set equal to zero so essentially the way that we're going to iterate through t and compare the characters in s and find out if our characters in s are in t is we're going to utilize this tracker and the way that's going to work is we're going to leverage the fact that if we set tracker equal to zero right and then we were to say s tracker right let's say we said s tracker what would that be equal to well that would be equal to a right if we were if we were to call up that s tracker value right because in a b c a is at the zeroth position b is at the first and c is at the second right so knowing that what we can do is we can do a for loop right very very easy we would do a for loop right and we would say something like four chars in t right so we would be looking at all of the characters in t we'd be stepping through them through t and we'd basically be saying is the position at s tracker is that equal to chars right is s tracker equal to chars and so basically what we're saying here is so in this case we would be we'd be iterating through the chars would be representing the various values in t as we're stepping through them and so we'd be comparing their value and so we'd be saying is a equal to chars right in this case so and so we will step through and so we would say okay yes like in this example in example one that leco gives us we'd start by looking at a and then we'd be saying okay now we're going to compare is s tracker in this case a is that equal to chars and so we could say yes char is here and chars and t looking at the characters in t we have a and so yes a is equal to a so what we will then do is we will take our tracker and if that's the case we're gonna take our tracker right and we're gonna set it to plus equal one we're gonna increment one so tracker in this case would now be um b would be the letter b right because tracker is now is now equal to two right tracker now equals two and so this would be if we called s tracker now this would be um equal to the letter b right and so now we're iterating through chars and we're looking for the uh we're looking for the letter b in t and so once we find it of course we would then tracker would then be updated to plus equals one and then we would look for c and so on and so forth until we've iterated through all the characters and we've either found a match or we haven't right so hopefully that makes sense i think once you see it in the code it will kind of clarify everything for you the explanation can be a little bit strange and make it seem a lot more complicated than it actually is so we'll just jump over to lee code now and we'll see what that solution looks like and we're going to code up that solution based on that example and those notes that we took earlier so what's step number one right we want to define our tracker that we talked about so that we can keep track of those values that we've seen in t and make sure that they're equal to the values that we have in our string s so we can confirm it's a subsequence right so our tracker is set equal to zero to start off with because we want to start with the first character and s and then we want to look at all the characters in t so that we can do our comparisons and check the subsequence right and then we're going to say if if s tracker like we talked about if s tracker is equal to chars then we want to update the value of tracker to be plus equal one right so that we can check the next letter and then check the next letter so on and so forth right and then we're going to do our return and we're going to say return tracker equal to the length of s right because if tracker is equal to the length of s then that would be then if that's true then we would you know we would return true this is just basically um this is this is doing uh sort of like a logical operation so it's going to say if basically when we call this return tracker equals length if that's true it'll return true if it's not true it'll return false so that way we don't have to say return true or false that function will just do it here by default and so the only other thing that we need to do here is we need to make sure that we can actually break out of our form we don't want to end up in a sort of infinite for loop here so we need to just have a condition that'll say that if our tracker is equal to the length of s we want to break right we want to break out of that uh that that for loops that we don't just keep going through it infinitely right so if our tracker is equal to our length similar to what we have down here then we want to break out of it so that means that we've seen all of our characters and we're good to go we're good to take off to take off and and and get out of our our for loop so let's run this and just make sure that it works and it does so you can see here that it's really really efficient i didn't mention it in the notes but this is working in o of n time and i can write it here it's o of n time and it is o of o of one space and that's where n is the um the length of our strings all right so this is going to be done at all oven time over one space and yeah you can see here that it's very very efficient and the code is probably easier than you thought it was that explanation could have been a little bit more confusing making the problem seem tougher than it is but essentially it's just levitating this tracker and you can see here iterating through our loops so code is very simple so thank you so much for watching and | 2024-03-24 12:08:56 | 392 | Crush the Coding Interview - Leetcode 392: Is Subsequence (Python) |
|
xDC4-13f6qc | strictly increasing [Music] a problem a problem Mario [Music] foreign foreign foreign foreign so in the render options element [Music] in the values [Music] thank you okay okay so coordinator now the next team is is uh foreign episode okay now the previous APC index is concept now now [Music] is [Music] return [Music] um other than guys uh have a nice day your time Comics are rough n square into login you know in the end score 10 number and the State um okay guys | 2024-03-25 18:18:03 | 1,187 | 1187. Make Array Strictly Increasing || Leetcode || [Tamil] |
|
Gkgs6pGidaM | hey hey everybody this is larry this is me going over weekly contest 219 me going over weekly contest 219 q2 partitioning into minimum number of q2 partitioning into minimum number of deci binary numbers uh hit the like deci binary numbers uh hit the like button hit the subscribe button join me button hit the subscribe button join me in this card let me know what you think in this card let me know what you think about this problem about this problem so for this problem to be honest i was a so for this problem to be honest i was a little bit thrown up by it because i little bit thrown up by it because i wasn't wasn't it felt and i i don't mean this to be it felt and i i don't mean this to be bragging bragging or you know whatever but um but i'm just or you know whatever but um but i'm just going for my thought process when i was going for my thought process when i was solving the problem and you could watch solving the problem and you could watch me me afterwards solve it during the contest afterwards solve it during the contest and the thing that surprised me about and the thing that surprised me about this problem was whether this problem was whether um i felt too easy almost uh and i like um i felt too easy almost uh and i like i said i don't mean i said i don't mean to say that to brag it's more that to say that to brag it's more that i wasn't like i had doubts because it's i wasn't like i had doubts because it's a medium i was like okay this a medium i was like okay this fuse a little bit too easy for medium fuse a little bit too easy for medium and the reason why that is is and the reason why that is is that well this is pretty much it um that well this is pretty much it um so the idea is that okay so you have a so the idea is that okay so you have a number like this number like this you know we take a big number the number the ideas that have a number we can always break it down to uh in a way it's greedy right you always construct a number if you can if this is not zero so here it's it's a two okay this is really long so maybe i'll just take a slightly shorter one for example um okay so that means that the first number will be one one one one one the second number will be one one one one one so this is greedy um and then we have one but we already right now so the two goes to zero so we could go to zero and then one one one um and then so forth right and from that i'm trying to be really careful not myself but uh from that dot dot here i think this is okay which is that if you do no matter what the the digit that has no matter what the the digit that has the highest number the highest number that is to your choke point right that that is to your choke point right that is the the number that is the the number that gives you the most repetition and of gives you the most repetition and of course at most that's gonna be nine course at most that's gonna be nine because because you have nine digits so you can actually you have nine digits so you can actually even simulate the greedy algorithm if even simulate the greedy algorithm if you like you like but during the contest what i did was i but during the contest what i did was i just go for each just go for each each digit in the string and for each each digit in the string and for each digit i just take the max of those digit i just take the max of those digits and i return it digits and i return it that's pretty much it uh this is why i that's pretty much it uh this is why i was very surprised because i was very surprised because i actually solved this during the contest actually solved this during the contest in about one minute and some of that was in about one minute and some of that was just me second guessing and not sure just me second guessing and not sure whether i was right whether i was right um because it was just a little bit um because it was just a little bit yeezy because yeezy because recently also there's been a harder recently also there's been a harder problem so problem so um anyway that's all i have for this um anyway that's all i have for this prom uh it's linear in terms of prom uh it's linear in terms of in terms of uh the time and in space we in terms of uh the time and in space we do not use any extra space it's name do not use any extra space it's name because we look at each digit once because we look at each digit once uh that's all i have watch me stop this uh that's all i have watch me stop this live during the contest live during the contest and ah oh hmm yeah thanks for watching uh let me know yeah thanks for watching uh let me know what you think about today's prom what you think about today's prom and just let me know what you think hit and just let me know what you think hit the like button the like button smash that subscribe button join my smash that subscribe button join my discord more uh discord more uh so you can chat with me and people and so you can chat with me and people and ask questions and ask questions and i will see y'all next contest next farm i will see y'all next contest next farm whatever bye-bye | 2024-03-20 14:12:10 | 1,689 | 1689. Partitioning Into Minimum Number Of Deci-Binary Numbers (Leetcode Medium) |
|
dk9bUv1nDxQ | hey hey everybody this is larry this is day day what q4 delete code uh weekly contest what q4 delete code uh weekly contest 224 224 maximize number of nice divisors um hit maximize number of nice divisors um hit the like button to subscribe and join me the like button to subscribe and join me on discord let me know what you think on discord let me know what you think about today's prom about today's prom so this one it's um you look at this so this one it's um you look at this answer and it's answer and it's it's weird uh it's actually a very ad it's weird uh it's actually a very ad hoc one-off problem hoc one-off problem the short answer is that um the short answer is that um well the one thing that's misleading is well the one thing that's misleading is that um given that um given here right um let's say we look at the here right um let's say we look at the prime factor five prime factor five and you have these dividers right um it and you have these dividers right um it actually doesn't matter actually doesn't matter that um that that um that you know you don't need fives that's you know you don't need fives that's what i'm saying it could have been three what i'm saying it could have been three so so you always just take the minimum devices you always just take the minimum devices and then the question is and then the question is um well how do you figure out how many um well how do you figure out how many nice nice divisors are there right and while the divisors are there right and while the number of number of nice divisors will just be nice divisors will just be um the com the um um the com the um the multiple the the product of the multiple the the product of the the frequency table of this right um the the frequency table of this right um for example there's three twos times two for example there's three twos times two fives or in this case it'll be three fives or in this case it'll be three times two which is six times two which is six and you can kind of see why that is the and you can kind of see why that is the case because case because um you can use that many um you can use that many um you know because this the product of um you know because this the product of this is 200 this is 200 and you can use some subset of uh twos and you can use some subset of uh twos and you use some subset of fives and you use some subset of fives but you have to use at least one two and but you have to use at least one two and one five so that means that one five so that means that you use either either one two you use either either one two two two or three two okay one five or two two or three two okay one five or two five two five so then three times two um so yeah so so then three times two um so yeah so that's basically it that's basically it and then one thing to note is that if and then one thing to note is that if you you put that down by if by the frequency put that down by if by the frequency table then table then um that means that you have this um that means that you have this you know in this case 3 and 2 3 and 2 you know in this case 3 and 2 3 and 2 has to equal to 5. i think that's has to equal to 5. i think that's obvious because that's just the nature obvious because that's just the nature of the thing of the thing so then you have the idea of okay you so then you have the idea of okay you have x sub i have x sub i or x of 0 maybe plus x sub 1 plus x sub or x of 0 maybe plus x sub 1 plus x sub 2 um dot dot dot plus dot you know 2 um dot dot dot plus dot you know plus x sub uh k plus x sub uh k is equal to n right so that's how you is equal to n right so that's how you break it down break it down and then you want to maximize x sub 0 and then you want to maximize x sub 0 times x sub 1 times x sub 1 times x sub 2 dot dot dot right i want to maximize this um and from that there's actually um whoops sorry got a little bit confused um got five wrong answers on this because i i'll talk about it um but yeah so you want to maximize this um yeah and then the idea is okay well how do you maximize this um it turns out that and and for me i actually have solved this problem before now that you've broken down the problem into like this i have solved uh a variation of this problem before um well i've solved this exact problem before just not you know with this formulation where you have to kind of convert that this form this this problem into this problem and now basically you have a sum of k numbers um for some number of k and and yeah and it turns out that the answer is that it's always going to be um you know you could play around some powers and you could play around some stuff um and the answer turns out that it's just uh it's going to be all as many degrees as you can um and the last one would just be whatever is left over so then the answer is for example you have three plus three plus three plus dot dot dot plus three plus dot dot dot uh plus well n minus three or at mod 3 is equal to n right so that's basically um going to be your your maximized answer i'm not going to go over this part too much um you can kind of do the proofs or maybe google that i don't know internet a little bit but but that's the basic idea and and once you kind of you know figure that out then it's just three mod uh three to the you know and dotted by three roughly speaking uh plus you know uh [Music] yeah and that and two to the whatever right two to the and my three roughly um yeah and that's basically the idea here um yeah uh yeah i'm i'm a little bit sick today so my apologies but this is my implementation and um yeah the hardest part is just you know converting this problem into kind of this problem um and and for me actually because i knew i had this code somewhere um but i think the formulation or the so it's a little bit different so the base case is a little bit different but honestly i also got i also got um i was just very careless because i knew that by the time i even started this problem uh this is a little bit better contest speaking um there's a lot of maps so for interviews i probably wouldn't worry about it because this is just a ridiculous problem for an interview but um but yeah because i i just messed up on mods i have basically uh i have five wrong answers on this one is a little bit sad i basically um yeah i basically forgot about the i don't know i'm a little sick today so i'm not even explaining this well my apologies uh leave a comment in the below but basically yeah this is just uh what i said um oh this is actually this is a little bit off this is what it takes to get to three so um but basically that's the idea um yeah uh yeah i i had three wrong answers or two wrong answers because or three wrong answers maybe i just forgot about the mod here um i forgot this mod and i was like as soon as i saw it i was like oh i forgot this one but then i also actually forgot about modding the nz times two and also the answer times four because i am just silly and then i just forgot about the base case because um the other problem that i saw it had different base cases so i was basically copying and pasting mentally um but and that's why sometimes i need to slow down but there was a lot of time pressure because i was like oh i got to get this quickly um but but it turns out um yeah i was uh i was a little bit bad on this one uh cool uh yeah you could watch me sell it during the contest next um you could i think it's kind of funny especially if you fast forward to the parts where i am struggling with the wrong answers and and just kind of i don't know mental i think i think i had the idea and i had to promise something i even used a little piece of paper to kind of write this out um but i think i just lost discipline near the end where i was just like oh like if i had just spent an extra two minutes or whatever slowing it down and getting it right i would have saved myself 25 minutes of wrong answers but i was just rushing it because i saw so many people got this one so fast that i was like oh i have to do it quickly yeah well um hopefully that's uh you know um you know stay with your plan and and uh and yeah um yeah stay with your plan and you know um yeah stay with your plan and you know i i mean because my plan for this contest mean because my plan for this contest was to slow down but i was to slow down but i i still rushed it anyway you can watch i still rushed it anyway you can watch me me sub it live next i'm gonna be asking for number five [Applause] hmm hmm but nine hmm let's see my smart okay oh no okay okay that's unfortunate 64. that's unfortunate 64. i have a typo 64. i messed up oh man i am just careless i i found it huh did i forget no wow i mean i got uh this is the silliest this is the silliest way to get all the this is the silliest way to get all the wrong answers wrong answers did i miss fighters because oh my god i got dwight yeah uh let me oh my god i got dwight yeah uh let me know what you think about this farm and know what you think about this farm and explanations this isn't in my final explanations this isn't in my final ranking there's ranking there's way more penalties because i just i way more penalties because i just i don't know i ate too many don't know i ate too many wrong answer attempts but yeah let me wrong answer attempts but yeah let me know what you think uh hit the like know what you think uh hit the like button and subscribe and join me on button and subscribe and join me on discord discord i hope y'all have a good day have a good i hope y'all have a good day have a good night solve more problems night solve more problems if you like or you know too many acs and if you like or you know too many acs and yeah it's a good mental health i'll see yeah it's a good mental health i'll see you later bye | 2024-03-22 16:08:31 | 1,808 | 1808. Maximize Number of Nice Divisors (Leetcode Hard) |
|
kNUAAWi90Y4 | Which Hybrid Today's Problems Minimum Operations to Reduce First Year Considering The Right Vyati First Year Considering The Right Vyati St Anselms 512 Must Subscribe Now St Anselms 512 Must Subscribe Now To To To To To To To To To To To The Numbers - To To To To To To To To To To To The Numbers - Gabbar Samay Students - 110 Questions Of Make Sure Let's See What This Gabbar Samay Students - 110 Questions Of Make Sure Let's See What This Logic Of Logic Of Inner Wear Limit Subscribe Now To To To To To To To Inner Wear Limit Subscribe Now To To To To To To To To The Numbers Are To The Numbers Are To The Numbers Are Mera Favorite Song Degi Sister Sambhal Four five elements Total Total Subscribe Hai To Hai Next Roots In Arrange December That Way Toot Total Come - And Find The Longest Subscribe To Main Itni Senior Research Have yes easily tower goals to find the longest sub bhare avaghat bhare six feet under 142 coal and six feet under 142 coal and solution hai solution hai that duke 390 consider dec-11 shift that duke 390 consider dec-11 shift remove 14213 dirtiest operations on dec remove 14213 dirtiest operations on dec 14 2012 14 2012 now sleep number operation songs free now sleep number operation songs free now sleep number operation songs free minimum number of operations in solving maths subject maximum do do me rs 0 sequel total sub - k Knowledge in gr and he has taken Knowledge in gr and he has taken example point on to find assam bhrigu submersible target and complete other text pin code off so what are going to where going to check c220 2010 2011 2012 white white white sportive 100 hear considered equal to forget to sportive 100 hear considered equal to forget to subscribe to that assam from its previous induces that space example hair tips 707 what is further placement in liquid plus further placement in liquid plus forces acid subscribe to forces acid subscribe to that hair dresser photog and hair dresser 170 that hair dresser photog and hair dresser 170 soft phone soft phone soft phone office - 07 which means the distance from 27 - 3 support and plus to class for this 27 - 3 support and plus to class for this site again from another day site again from another day that what cutting is pleasant point to that that what cutting is pleasant point to that point to point to me on Monday August and not journey me on Monday August and not journey me on Monday August and not journey beauties have consumed indices Bihar Bengaluru sum 123 hands free - Android subject 4043 159 want two minus one differences on Uttar Pradesh up subtle coast seventh class seventh 400 check a specific to front this inside differences can again For oo For oo For oo aur sunao 3 - 09 - 6a aur sunao 3 - 09 - 6a 251 plated new sab bhare tak test 251 plated new sab bhare tak test theek hai beta WhatsApp to 7 minutes check theek hai beta WhatsApp to 7 minutes check manly from index one subscribe to manly from index one subscribe to are yes thank you calculate dictionary 520 and are yes thank you calculate dictionary 520 and shyam pandey new sab kuch limit for and shyam pandey new sab kuch limit for and subscribe button subscribe to subscribe button subscribe to subscribe button subscribe to happened from this Khusro quantity station, seeing Salman proved that till 228 seeing Salman proved that till 228 Sarpanch of Portion 7 - Ronit Ronit Roy Dictionary Sarpanch of Portion 7 - Ronit Ronit Roy Dictionary Video Subscribe Length is Video Subscribe Length is that Subhash has to share it that Subhash has to share it and welcome was the latest wallpaper going was the latest wallpaper going was the latest wallpaper going bluetooth requested specific person bluetooth requested specific person Ronit Ronit [ Ronit Ronit [ Music] hai tu states minor dheer wa 12345 ko 22 - - 1000 positions - subscribe aa Number Zara Tractor Sauveer 1234 No Recent Episode 368 Subscribe To Computer Total Ka Hai Kar Do Hua Hai Jhaal Jhaal On Karo Aur Suna Aur Samay Khel Ke Latest Current Affair Going To Find Work At Hotel - 2 Hua Hai Brothers Lions Month in Brothers Lions Month in Brothers Lions Month in English Ki English Ki Noida Relax Now Ajay Ko Hua Hai Temple Run Khelo Cash Now Navsari Hai Tatti Trainee Every Time She Enters Rupse The Tatti Trainee Every Time She Enters Rupse The Pratikshaan Hai And Anshu 113 You Are The Hua Tha Hua Tha Ke Samne Na Aa A Ke Samne Na Aa A Target Tak Hai Net Video Song Hafte Mein Target Tak Hai Net Video Song Hafte Mein Result A Result A Lootere Car Music System This Lootere Car Music System This Independence Day Loot Is Independence Day Loot Is Ghat E Want To Know Kar Do Loot Ajay Ko And Sunao Hua Song Mister Small Condition President Hua Song Mister Small Condition President Sea Road and Extension - Subscribe to Sea Road and Extension - Subscribe to Shopping in Recent Speech 30.25 This is Shopping in Recent Speech 30.25 This is how - Not Trust People combined | 2024-03-19 18:43:27 | 1,658 | Minimum Operations to Reduce X to Zero | LeetCode 1658 Jan 14/2021 | Coders Camp |
|
Wv6DlL0Sawg | Hello Hello Guys Welcome Back To Back Door And This Video Will See The Video Will See The Largest Divisible Most Problem Wishes From List To Date Largest Divisible Most Problem Wishes From List To Date 18th June Challenge So Let's Follow 18th June Challenge So Let's Follow Problem Statement Problem Years And Give Problem Statement Problem Years And Give Winners Of Distinct Possibilities For Winners Of Distinct Possibilities For The Largest Subscribe My Of Elements The Largest Subscribe My Of Elements In This Subscribe In This Subscribe In This Subscribe subscribe center problem no latest do the giver 467 on Thursday and with oo hai so in this case your feet ek sadhe sab always latest take off but istri most it because the largest williams second notification latest 110 012 sleep * Sudhir Vve Nov 14 2012 Subsidy Avoid The Center And Subscribe My Channel Must Subscribe Now Within Border Is Not Important Within Border Is Not Important So You Can Transform 2512 Less And Policies So You Can Transform 2512 Less And Policies And This To Deposit 126 And Center Problem And This To Deposit 126 And Center Problem Life Even Today What Is Life Even Today What Is Life Even Today What Is start from every element which is the largest subscribe now to options with only in the subscribe this Video subscribe Video to play list between options and will make all possible developed calls on there will be to take off This This This check that is checking and give element can be check that is checking and give element can be included in this now half hour mode on included in this now half hour mode on two and off one burst fuse brute force in this will also be two and off one burst fuse brute force in this will also be mode off and show your time mode off and show your time complexity will be order of uninterrupted complexity will be order of uninterrupted power and water from device this power and water from device this power and water from device this Award Winners Will Be More Raw To Three Four And So Even Easier To Make Decorative Approach Will Take Explanation Time Complexity The For This Is Not Feasible Approach To Solve This Problem This Problem Variant Of Increasing Subscribe Solitaire Zoom This Subscribe Subscribe Subscribe few days West Indies in subsequent will come out with 126 ok indicate they want to 610 will be your subjects where is element Balbir 126 no problem will again be having subscribe The Video then subscribe to the Page if you liked The then subscribe to the Page if you then subscribe to the Page if you then subscribe to the Page if you liked The Video then subscribe to the liked The Video then subscribe to the Page Alarm of Birth 208 Otherwise Straight Should Be Equal To Zero No One Will This Later This Mode 2009 2013 Otherwise Beat Only Desire To Be Divided Into This Element In Short A Flu Say This point six pieces a lips element so let's subscribe free mode of birth place 200 subscribe free mode of birth place 200 gram sambse gram sambse hai but they need to manipulate the condition of the sub hai but they need to manipulate the condition of the sub always 2nd position is not included in the always 2nd position is not included in the same subject ko dabocha dividing same subject ko dabocha dividing as per the question they request to short tor as per the question they request to short tor records they have been sorted should not require records they have been sorted should not require 200 test wickets in this can see your 200 test wickets in this can see your feet from this tournament 0.2 60 feet from this tournament 0.2 60 and mode and mode and mode can be present in the same condition after applying a quote that so you can only apply mode also 2015 virva is divisible and 98100 only one who are you doing so let's unite in these directions Middle of the Middle of the Middle of the limits of water will have to the number of the limits of water will have to the number of the mission and mother but you will only one mode of mission and mother but you will only one mode of operation in Delhi and saw this time to boys 210 Main Hanskar is obscene very-very lal chandan and long and you can take hamla reservation Compare So I Thing This is Better Life Gives and Another Day Used in This Little But It's Not Solved This Problem in subscribe The Video then subscribe to the Video then subscribe to the Page if you liked The Liye Bill Computer Literate For Each Liye Bill Computer Literate For Each Liye Bill Computer Literate For Each Element From Left To Listen Or Current Element Services Only One Element Yudh Left One Can Divide To And Also For The Length Of This Most Including One Is Equal To 2 And Defeat Can Divide To When They Can Actually Increase The Subject Science One plus one is better than this one will increase the One plus one is better than this one will increase the One plus one is better than this one will increase the size of this to you in this case one plus one size of this to you in this case one plus one is better than is better than one-dayer between two cigarettes improved this one-dayer between two cigarettes improved this one and to in and subject the longest one and to in and subject the longest increasing subject according to and increasing subject according to and giving constraint will be giving constraint will be giving constraint will be size two do not want to connect with sister in law will start from the first divide divide share dividend with oo is this one plus one who does one plus one will be twitter message vansh will update nov12 next point which is this two 9 10 Two Can Not Divide Free Software Not Possible To Be Converted To Know All This Element Search 120 Move To The 6 Will Start From This One So One Can Divide 60000000 Increase The Giver 2.22 Channel Ko subscribe to the subscribe to [Music] [Music] West Indies And Inter Duetable Which Same To West Indies And Inter Duetable Which Same To The Longest River In Subsequent So In This The Longest River In Subsequent So In This Case Will Keep Updating Max Value What Case Will Keep Updating Max Value What Is The Maximum Value For Is The Maximum Value For Long-Distance Relationship Sequence In This Is It Long-Distance Relationship Sequence In This Is It Is Equal To Three Love You Want Is Equal To Three Love You Want Is Equal To Three Love You Want Practice Max Value Because Will Help Subscribe Like and Subscribe This Subscribe Like and Subscribe This is Not Computing with All the Best Meaning This is Not Computing with All the Best Meaning This is the Subscribe Created from This Value is the Subscribe Created from This Value 223 But Not Computing with All the Element Subscribe 159 This and Counter So That The House Were Counter So That The House Were Counter So That The House Were Just Checking With Three Candidates Should Just Checking With Three Candidates Should Not Were Not Setting Where One Can Also Not Were Not Setting Where One Can Also Be Divided And Would Not Do This Because While Including This Would Make Be Divided And Would Not Do This Because While Including This Would Make Them Check Them Check With Its Previous Element And Fair With Its Previous Element And Fair Award Winner Previous Element In This Element With This Award Winner Previous Element In This Element With This Element This Elementary Element This Elementary Level Divisible By Its Previous Element Level Divisible By Its Previous Element And Divide Next Element This Is The Next Element And Divide Next Element This Is The Next Element Will Avoid Simple Will Avoid Simple Mathematics In Relationship Element ABC Mathematics In Relationship Element ABC Latest Noida Land Acquisition Element Is Latest Noida Land Acquisition Element Is Divide Divide Development Will See Mode Of Divide Divide Development Will See Mode Of Birth 2018 Birth 2018 Airplane Mode They Will Be Equal To Zero Airplane Mode They Will Be Equal To Zero Swadeshi Nothing But Swadeshi Nothing But Swadeshi Nothing But Confused Years Who Is Explained That No One In Your Language Increasing Sequence They Want To Find The Exact Subscribe Suvichar This Is Not Find A Way Are One Two Three Four Table Spoon 123 Likes And Subscribe Now To Subscribe Subscribe Our Channel Like This Is Subscribe Our Channel Like This Is Subscribe Our Channel Like This Is The Question Clearly Mentioned It May Be The Question Clearly Mentioned It May Be Possible subscribe and subscribe the Possible subscribe and subscribe the Page Clement Sex Novel Decrement The Value Page Clement Sex Novel Decrement The Value Of This Max 2 And Will Stop This Of This Max 2 And Will Stop This Previous Element Devils To The Servi 699 Previous Element Devils To The Servi 699 Will Move To The Previous Song This Is To 9 Will Move To The Previous Song This Is To 9 IF IF IF Video subscribe Video then subscribe to the Page if you liked The Video then subscribe to the Video then subscribe to the Big Apne One Okay so this is equal to and max value no will see its element as per previous Element 300 divided over this one is this true wealth will push one and subject and all elements 910 to rs 600 in case you can clearly see basically the subscribe to the Page if you liked The subscribe to the Page if you liked The Video then subscribe to the Page Video then subscribe to the Page Video then subscribe to the Page liked The Video then subscribe to the Complexity and Dynamic Programming And Over Again First Your Finding 10 Subject Which Saw And Because I Was Doing A Single Traversal Member Total Time Complexity This Fans Ko Arnav Latest Look At The Code Swift Code Where Loud Twist Number One Loud Twist Number One Loud Twist Number One After Shopping Viewers Mining Longest After Shopping Viewers Mining Longest Increasing Subscribe Number Two And After Increasing Subscribe Number Two And After Doing All Subscribe What They Are Doing On Thursday A Person Data Is That Is The subscribe to The Amazing And They Will Be subscribe to The Amazing And They Will Be Able To Understand When The Able To Understand When The Able To Understand When The in different languages subscribe hours benefit from it like share and video subscribe our channel involved in this | 2024-03-24 11:30:35 | 368 | Largest Divisible Subset | Dynamic programming | Leetcode #368 |
|
PWcmzhZMkrs | Hello everyone welcome to our channel question and you want to talk about one of the heart one of the heart problems soft code no problem you problems soft code no problem you support super first entrance end 1.06 ok so support super first entrance end 1.06 ok so iss rule se reduce problem shubh iss rule se reduce problem shubh related sampan roaming type ok so let's unite related sampan roaming type ok so let's unite for street problem and together for street problem and together for street problem and together definitely idea solve this problem in the best solution and friends mukesh so let's move this positive integer uninstall super follow rom don't take tension is the number is it white room other this all subscribe ok kha condition set up vriksha repeat oneself in day Share Number Share Number And Determine The Number Super Talent From Cities In The Inclusive Range Electrolyte OK Software To Basically Account The Total Amrit Superpower In This Can Reach OK Review By You Sam And Subscribe For Example Sun Need To Worry About So Let's Talk About Not Front Front Front Android Mountain Very Up To That Is The Length Android Mountain Very Up To That Is The Length Of The Artist In Various Tools Pet Means Of The Artist In Various Tools Pet Means Earth Can Have Liked And Party's Earth Can Have Liked And Party's Value Addition Medical Value Distance Value Addition Medical Value Distance Left And Right The Present In Teachers Left And Right The Present In Teachers Indore Range One 210 Positive Incident Indore Range One 210 Positive Incident First Prize Software Is Not Wish To First Prize Software Is Not Wish To Aware of this type of question is stressed Aware of this type of question is stressed under it Delhi World 1 Inch Its Speed under it Delhi World 1 Inch Its Speed Acidity COD Solve This Problem Like If Two Acidity COD Solve This Problem Like If Two Time Limit Exceeded The Gruesome Time Limit Exceeded The Gruesome Act Bigg Boss Modifying Something Okay Then Act Bigg Boss Modifying Something Okay Then Adjust Or Six Planning What Is The Adjust Or Six Planning What Is The Point Of Mistake Also That Main Course Point Of Mistake Also That Main Course Point Of Mistake Also That Main Course * In This Question OK So Let's Try To Understand This Problem In Point The Best Solution Of This Problem In The Best Possible Way Let's Move Further On The Latest Top Of The Help Of Strathearn Example Life In Giving Android Android In Roots Roots Roots Approach Will Not Be Able To Quit His Approach Will Not Work Will Have Two Approach Will Not Be Able To Quit His Approach Will Not Work Will Have Two Of Three And Subscribe And Subscribe And Subscribe The Channel Please Subscribe And The Channel Please Subscribe And Subscirbe Not He Did Not Even Length Subscirbe Not He Did Not Even Length And Width I First Rome Relation Between And Width I First Rome Relation Between Equals Two Subscribe First Ok Maximum Equals Two Subscribe First Ok Maximum Malik Ko Buildings Palan Romantic A Building Sampann Low Medium Just Doing The Same Time To Is Like Subscribe Now To Receive New Updates Tree Not To Withdraw From 01-02-2014 Paas Ki Hai Ok So And Strive To Build A Sainik Boys Will Also Give Palan Boys Will Also Give Palan Boys Will Also Give Palan Room And Also People And Room And Also People And Destroy To Build And Ok How Can They Destroy To Build And Ok How Can They Reduce And Hidden Under The Con Is On Call Reduce And Hidden Under The Con Is On Call Center Time Limit And Under The Hydration Center Time Limit And Under The Hydration 15.12 Field Ok Latest Tattoo Photos For The 15.12 Field Ok Latest Tattoo Photos For The Latest From This Dynasty Before In Rome Latest From This Dynasty Before In Rome Consisting of a point to ponder over Consisting of a point to ponder over evil and acted s plus plus of address evil and acted s plus plus of address correct random screen latest edition more correct random screen latest edition more subscribe only belongs to side subscribe only belongs to side 1st id porn 1st id porn 68 mode 10.4 hydration if possible then 68 mode 10.4 hydration if possible then straight point is equal to 9 straight point is equal to 9 advertisement distic coordinator that advertisement distic coordinator that default default default Sworn In S You Can Very Apt Like F-18 Vikram Who Times Know A Plus Revert Subscribe Expert That Ali Khan So Proven Shadowlands And Distances Itself From Characters Paint Wishes For 9 And Destroy To Build Tattoo Difference One More Tattoo Difference One More Tattoo Difference One More Night Come Hair And Can Go Up To Like Night Come Hair And Can Go Up To Like Practice Make Some Places Left Can't Job Practice Make Some Places Left Can't Job Doctor Strange Okay So Tips Doctor Strange Okay So Tips Media Something To Check Investigate Android Condition Was Media Something To Check Investigate Android Condition Was Not Based Splendor Pro Follow His Not Based Splendor Pro Follow His Actual Key String Consisting Of Actual Key String Consisting Of Vegetable Hotspot Sight Jack Vegetable Hotspot Sight Jack Vegetable Hotspot Sight Jack Settings Where Hotspot of District OK So Let's Get Suvidha And Rather Than Is Waiting For Insta Per Tempo 93 Strobe Light Off Sports Mode Interiors And This Will Have Committed To Avoid Jad To Build Beam Consisting Of Price Follow Up This Point Key Key Key principal and this interesting to principal and this interesting to maximum link to no witch hunter distance maximum link to no witch hunter distance trends and if any special android easily trends and if any special android easily square this and to point porn point square this and to point porn point to your Rome give back gear pig rearing draw to your Rome give back gear pig rearing draw and add text to be included in foreign and add text to be included in foreign soil in the next absolutely nickel soil in the next absolutely nickel soil in the next absolutely nickel next many writers help one message to ethical like and share key points from president starting from extra to start from this and point and widespread and wish to follow and service and find x n x to printer not included under the given time Suffering 21018 Maximum Icon Decided To Suffering 21018 Maximum Icon Decided To Suffering 21018 Maximum Icon Decided To Vote And Support That Time Stands For Vote And Support That Time Stands For Volunteers Turned From One Hundred Volunteers Turned From One Hundred Words Related To Every I Don't Points And Which Were Words Related To Every I Don't Points And Which Were 15.91 Is This Is Black 15.91 Is This Is Black Questions And Squares And Fixtures Questions And Squares And Fixtures Follow Up On Rome Bite Object Rome He Guys Give Follow Up On Rome Bite Object Rome He Guys Give In Access In Access In Access absolutely maintenance ok so latest to implementation health coding for it's ok so your seal testis of fast 100 second patience function in this chakra is mighty before trump and not talk and akshay different balance long spree continues it's ok Slice row and Slice row and Slice row and electronic trading in the form of electronic trading in the form of fertile land that can easily see live fertile land that can easily see live news stone function it is not aware of news stone function it is not aware of this unknown is previous converting this unknown is previous converting strings * enter particular data is strings * enter particular data is active user login more religious can go up to active user login more religious can go up to think positive a waste oil aspect think positive a waste oil aspect think positive a waste oil aspect 210 Power Foods And Reduce The Come Electricity Bill Is That Store Tractor 35 Fix Total Posts Product Range Of Pilot Rooms Of Clans Dynasty Is Decade Just Tweet And Previous Storing String Events And Just Avoid Further Told I Can Easily See All Ditties Mike Mike Mike Fennell Please Like This Is One of the Fennell Please Like This Is One of the Greatest Splendor Plus Time When School to Greatest Splendor Plus Time When School to 9 End Subscribe 9 End Subscribe Quality Award Uniform Distic* Maze Quality Award Uniform Distic* Maze Store Twitter Up to 110 Stores Previous Store Twitter Up to 110 Stores Previous Install The Con Is On To My Channel Install The Con Is On To My Channel Subscribe Button More subscribe and Subscribe Button More subscribe and subscribe the Channel subscribe subscribe the Channel subscribe subscribe the Channel subscribe subscribe and subscribe the Channel Please subscribe and subscribe the Channel Please subscribe and subscribe check date number isko 21 up first introvert and under give in the name of improvement my answer is nuskhe ko blacklisted in this is like a special staff withdrawal and After Maternal End Tak Hum Ise Palat After Maternal End Tak Hum Ise Palat After Maternal End Tak Hum Ise Palat Room Din Thi Next9 Otherwise Distic Witch Ke Room Din Thi Next9 Otherwise Distic Witch Ke Play To Finally Data On The Answer Will Give You All Play To Finally Data On The Answer Will Give You All The Test Cases For Most Frequent Ult The Test Cases For Most Frequent Ult Milna Jo Comment Section Of The Video Milna Jo Comment Section Of The Video Bana Mila Suicide Due Share This Video At Do Bana Mila Suicide Due Share This Video At Do Subscribe Subscribe Subscribe Updates Thank You For Watching This Video | 2024-03-25 10:31:06 | 906 | Super Palindromes | Strings | Maths | 906 LeetCode | LeetCode Explore | Day 08 |
|
DDT6P-9eN5U | hello everyone today's question cheapest flights within K stops so there are in flights within K stops so there are in cities connected by implied each flight cities connected by implied each flight starts from CTU and arrives at B with a starts from CTU and arrives at B with a price W so now given all the cities and price W so now given all the cities and flights together with starting city s RC flights together with starting city s RC and destination DST so your task is to and destination DST so your task is to find the cheapest price from is her find the cheapest price from is her source that is SRC to destination DST source that is SRC to destination DST with up to K stops so if there is no with up to K stops so if there is no such route output minus one okay so now such route output minus one okay so now I will move to pen and paper and I will move to pen and paper and understand this problem statement what understand this problem statement what we have to do basically we have to find we have to do basically we have to find find the cheapest price from source to find the cheapest price from source to destination and taking up to K stop okay destination and taking up to K stop okay and if there is no route between our and if there is no route between our source to destination then we will source to destination then we will simply written minus one so now our simply written minus one so now our source is zero and this nation is our source is zero and this nation is our three now we will calculate our source three now we will calculate our source to destination minimum cost to destination minimum cost okay we'll calculate source to okay we'll calculate source to destination minimum cost so first we destination minimum cost so first we will take a dictionary to store we check will take a dictionary to store we check from our source point okay so our source from our source point okay so our source point is zero so from zero it can go you point is zero so from zero it can go you can go one with the cost hundred bucks can go one with the cost hundred bucks from zero to 1 so we'll take zero as a from zero to 1 so we'll take zero as a key inside this 0t we will take a nested key inside this 0t we will take a nested key that is 1 and this cost is suppose this is a dictionary zero and then one that is cost hundred and from zero to there's another path from zero to we directly go three go to see three so this is cost three cost four hundred bucks so from zero we can directly go to CT one and say T 3 CT one will cost hundred works and CT 3 will cost 400 bucks ok and now we will move to next point so that is point 1 so from point 1 you can easily go from point 1 to we go only one city that is CT - so this one - we can go to cost hundred bucks and same point - - we can go three and it will cost one 150 bucks okay so that's our dictionary so we will store this information inside our dictionary now what I will do now I will take a hip QQ and inside the CPU of the store the number of stop to reach this position and cost and the current destination current cost current destination and number of stop ok so I will take IQ and first at the store suppose if I go from 0 to 0 0 to 0 from will cost zero cause we're already in will cost zero cause we're already in this position so first is cost and next this position so first is cost and next is our current destination is zero and is our current destination is zero and and initially we store our number number and initially we store our number number up stop K is zero and here we would take up stop K is zero and here we would take k plus one and when we will we will k plus one and when we will we will we'll store it again and then we will we'll store it again and then we will reduce this one k plus one first reduce this one k plus one first understood and then pop this will take a understood and then pop this will take a while loop while loop and pop this while loop while loop and pop this element one by one and then we will element one by one and then we will check we are in our our current check we are in our our current destination is our final destination or destination is our final destination or not so our current destination is our not so our current destination is our final final destination then we will final final destination then we will return this value suppose if we have return this value suppose if we have zero two zero and now we will move to zero two zero and now we will move to this point so if we go to zero to 1 then this point so if we go to zero to 1 then our heap Lu you know L will be our our heap Lu you know L will be our current destination is 1 and cause this current destination is 1 and cause this hundred cost is hundred how we calculate hundred cost is hundred how we calculate this cost which is check our current this cost which is check our current cost plus zero to one cost will pick cost plus zero to one cost will pick this cost from here and add it in our this cost from here and add it in our hip and our our destination point is hip and our our destination point is this one that is our number of stop is K this one that is our number of stop is K minus one so k is now 1 1 minus that is minus one so k is now 1 1 minus that is zero so without without taking any stop zero so without without taking any stop we can directly reach zero so but here we can directly reach zero so but here we have to we have to visit we have to we have to we have to visit we have to go our destination without taking any go our destination without taking any stop stop cause our K is zero so here if we if we cause our K is zero so here if we if we go to taking to stop then we have to go to taking to stop then we have to have to pay 350 bucks but if we directly have to pay 350 bucks but if we directly go to city three then we have to pay 400 go to city three then we have to pay 400 bucks but here we cannot take any stop bucks but here we cannot take any stop so our answer will be 400 bucks okay so so our answer will be 400 bucks okay so now I mention but in our implementation now I mention but in our implementation part first input hip queue now import part first input hip queue now import from collections input default Dix will from collections input default Dix will represent our crop using default represent our crop using default dictionary so I will take a default dictionary so I will take a default dictionary type Dix and now I will dictionary type Dix and now I will Travis the flights value start in a Travis the flights value start in a flight hold the three will start end and flight hold the three will start end and cost so I will take start as a key the cost so I will take start as a key the source point and end is another key source point and end is another key under start and value is cost now I will under start and value is cost now I will take a hip cue to store current cost and take a hip cue to store current cost and current destination current cost is zero current destination current cost is zero and current destination is SRC and and current destination is SRC and number of stock is k plus one now I will number of stock is k plus one now I will just take a visited dictionary to check just take a visited dictionary to check our current destination is previously our current destination is previously visited or not so now I will take while visited or not so now I will take while loop and check our cube is H cube is loop and check our cube is H cube is null or not so now pop this value null or not so now pop this value current cost current destination and k4 current cost current destination and k4 mower hip Q with Q dot it's Q and now mower hip Q with Q dot it's Q and now now I store this current destination now I store this current destination inside our visited dictionary and now current destination is equal to our final destination then simple return the current cost if current destination is not equal structural destination then we will take our K is greater equal to 0 K is greater equal to 0 then I will check our next next stop that we can we can go for more current destination so next or next destination is Jay I will check our next destination is already present in our visited this is dick scenario or not so J is our destination so now I just check K minus 1 get the wrinkles to visited cell so now just continue otherwise our J is our next destination and now I put it you know HQ so our cost is current cost plus plus our source to a current destination cost that is current cost plus scrap correct destination destination current destination key and and next destination that is J and now our current we now we push as our current destination and stop minus 1 so now I just returned - if there is no route between source to destination so now we check our code is working or not it's if you have any doubts or suggestion if you have any doubts or suggestion leave a comment below if you like this leave a comment below if you like this video please give me a thumbs up and video please give me a thumbs up and thank you for watching this video please thank you for watching this video please consider subscribe if you are new to the consider subscribe if you are new to the channel and don't forget to hit the bell channel and don't forget to hit the bell icon | 2024-03-21 16:51:23 | 787 | Cheapest flights within k stops - Facebook interview question | Dijkstra Algorithm | leetcode 787 |
|
_JYE_M3uD-Y | in this video we're going to take a look at a legal problem called word break at a legal problem called word break so given a non-empty string s and a so given a non-empty string s and a dictionary dictionary um containing a list of non-empty words um containing a list of non-empty words determine if string s can be segmented determine if string s can be segmented into a space separate sequence of one or into a space separate sequence of one or more dictionary words more dictionary words so in this case the same word in a so in this case the same word in a dictionary might dictionary might reuse multiple times in the segmentation reuse multiple times in the segmentation you might assume that dictionary you might assume that dictionary uh does not contain duplicate words so uh does not contain duplicate words so here you can see we have a string right here you can see we have a string right this case this case this lead code the dictionary you can this lead code the dictionary you can see we have elite and code see we have elite and code and then here you can see it's true and then here you can see it's true because we can basically because we can basically split a because we can segment lead code split a because we can segment lead code to lead code which all contains in the to lead code which all contains in the dictionary dictionary right in this case lead contains in right in this case lead contains in dictionary code is also contained in the dictionary code is also contained in the in the dictionary if we have e in the dictionary if we have e like this and we have a space here and like this and we have a space here and then we have then we have t c o d that's not going to work because t c o d that's not going to work because this does not contain a dictionary this does not contain a dictionary and this does not contain the dictionary and this does not contain the dictionary right right we want to segment the string so that we want to segment the string so that all the all the um all the all the um all the words in the string um contains all the words in the string um contains in this in this uh in the word uh in the dictionary in uh in the word uh in the dictionary in this case right so here you can see we this case right so here you can see we have have another string and then we have a word another string and then we have a word dictionary dictionary we have apple and pin in this case we we have apple and pin in this case we will return true because we can be able will return true because we can be able to reuse to reuse apple right we in this case here you can apple right we in this case here you can see we can be able to reuse multiple see we can be able to reuse multiple times times in some segmentation so here you can see in some segmentation so here you can see we can have apple pin apple we can have apple pin apple so in this case we can split so in this case we can split apple pen apple in this case right so apple pen apple in this case right so so in this case we're going to return so in this case we're going to return true true and here you can see we have another and here you can see we have another string in this case cats string in this case cats and a dog or whatever but basically and a dog or whatever but basically here you can see we have a dictionary here you can see we have a dictionary which has cats dog sand which has cats dog sand and cat in this case it won't work and cat in this case it won't work because because send in this case um sorry yeah send in this case um sorry yeah n in this case um contains that n in this case um contains that in the dictionary cast also contain in the dictionary cast also contain dictionary but dictionary but og does not contain a dictionary so og does not contain a dictionary so we're just going to return false we're just going to return false okay so how can we solve this problem okay so how can we solve this problem so to solve this problem the naive so to solve this problem the naive solution or the brute force approach solution or the brute force approach will be to check each and every single will be to check each and every single element in the string element in the string and have a pointer and for each pointer and have a pointer and for each pointer for the current pointer that the for the current pointer that the um that is pointing to we're going to um that is pointing to we're going to have a left substring in the right have a left substring in the right substring and then for the left substring and then for the left substring we're going to check to see if substring we're going to check to see if this left sub string this left sub string is contained inside the dictionary and is contained inside the dictionary and for the right sub string we're going to for the right sub string we're going to see if it is a valid uh word see if it is a valid uh word word break right so in this case we're word break right so in this case we're starting at index one starting at index one uh we're basically splitting you can see uh we're basically splitting you can see we're splitting a um we're splitting a um we have a left sub drink left substring we have a left sub drink left substring which is l which is l and the right sub string which is e e t and the right sub string which is e e t c o d e c o d e and then we want to see if it's a valid and then we want to see if it's a valid um um valid word break on the right substring valid word break on the right substring in this case the the right side in this case the the right side and the left side both returns false and and the left side both returns false and you can see there's an or you can see there's an or operator the reason why is that if one operator the reason why is that if one of those statements true of those statements true we can just return true for this entire we can just return true for this entire condition for this entire method condition for this entire method so in this case we have we keep so in this case we have we keep iterating we we now iterating we we now at the index two in this case we split at the index two in this case we split we see we see elite in this case lee and e t elite in this case lee and e t c o d e right we see if those are c o d e right we see if those are if those two conditions are true in this if those two conditions are true in this case we don't case we don't we continue until we have this point we continue until we have this point where we have lead where we have lead right and code and i think it's in right and code and i think it's in 0 1 2 3 4 in this case index 4 0 1 2 3 4 in this case index 4 right so what we're going to do then is right so what we're going to do then is we're going to we're going to now we know this condition is true right now we know this condition is true right we know elite is inside the dictionary we know elite is inside the dictionary and we're passing the code which is the and we're passing the code which is the right sub string right sub string then we're going to do is we're going to then we're going to do is we're going to see if code see if code we do the same procedure we're starting we do the same procedure we're starting at the um at the um index one right we split we have a left index one right we split we have a left substring which is substring which is c we have a right substring which is ode c we have a right substring which is ode and what we're going to do is we're and what we're going to do is we're going to continue to do this until we going to continue to do this until we get to here right get to here right in this case because those statements in this case because those statements are false those conditions are false are false those conditions are false what we're going to do is we're going to what we're going to do is we're going to [Music] [Music] pass in code and now the right substring pass in code and now the right substring is empty is empty if right substring is empty where if any if right substring is empty where if any string string we pass into wb is empty we can just we pass into wb is empty we can just return true because we want to re return true because we want to re because we want to see if the left because we want to see if the left substring substring is actually contained in the dictionary is actually contained in the dictionary right we want to see if the left sub right we want to see if the left sub string is can d string is can d to contain the dictionary that's why we to contain the dictionary that's why we have we want to make sure that this have we want to make sure that this condition is is true if this is true and condition is is true if this is true and this is true this is true then this is true right this whole then this is true right this whole method will return true so you will method will return true so you will notice that if we were to really do this notice that if we were to really do this the time complexity will be big o of 2 the time complexity will be big o of 2 to the power of n which means is an to the power of n which means is an exponential so if we because exponential so if we because in this case you can see that this right in this case you can see that this right here here computed twice um computed twice um not this one sorry my bad um wb not this one sorry my bad um wb ode is computed twice here ode is computed twice here if and you can see de also computed if and you can see de also computed twice twice e also computed twice right e also computed twice right not only those for each of those method not only those for each of those method that we call it recursively that we call it recursively we will have repeated computation so we will have repeated computation so what can do is that is we can use what can do is that is we can use a um um a hash map or a table to a um um a hash map or a table to memoize the data the the um the computer memoize the data the the um the computer solution right solution right so in that way what we can do is we can so in that way what we can do is we can save the save the the computed result onto this hash map the computed result onto this hash map and then we can and then we can retrieve the data in a in um retrieve the data in a in um in constant time right so in this case in constant time right so in this case what's gonna happen is if we were to what's gonna happen is if we were to really implement them really implement them uh uh dynamic programming using sorry uh uh dynamic programming using sorry this this this problem using a memoization this problem using a memoization what we're going to do is we're going to what we're going to do is we're going to bring the time complexity down to big o bring the time complexity down to big o of of n to the power 3. the reason why it's n to the power 3. the reason why it's imp to the power of 3 imp to the power of 3 instead of n square is because of the um instead of n square is because of the um the substring method because for java the substring method because for java this dot substring method it will give this dot substring method it will give us a linear time complex us a linear time complex so in that case the time complexity will so in that case the time complexity will be n be n n to the power of three so let's try to n to the power of three so let's try to do this problem do this problem in code so our first step will be to in code so our first step will be to use a hash set uh convert this word use a hash set uh convert this word dictionary to a hash set because this dictionary to a hash set because this will give us will give us a easier way to access a easier way to access elements to see if it exists in the list elements to see if it exists in the list right so we're going to use a global right so we're going to use a global variable variable which is a type string we're going to which is a type string we're going to use use we're going to call it dictionary we're we're going to call it dictionary we're going to do is we're going to assign going to do is we're going to assign dictionary dictionary is equal to a new hash set is equal to a new hash set we're going to pass in word dictionary we're going to pass in word dictionary and then we also have a string what and then we also have a string what we're going to do is we're going to use we're going to do is we're going to use a hash map to memoize which a hash map to memoize which the key is string and the value in this the key is string and the value in this case is going to boolean case is going to boolean okay basically we're going to do is okay basically we're going to do is we're going to we're going to cache the result right so in this case cache the result right so in this case hash map and then we're going to do is we're going to return we're going to use a helper method which basically picks a string and we're going to recursively um recursively splitting the the string right just like i would mention here we're going to split the string which we have a left string at the left substring we're going to see if it's in the dictionary and the right substring we're going to see if it's a valid word break so we're going to do this recursively so we're going to have a private boolean which returns boolean and we're going to call a helper and takes a string okay first of all we want to make sure that because when we're splitting right there could be a situation where the string is empty just like this one then we're going to do is we want to make sure that the string is if it's null we're going to return true okay because we want to make sure that we are focusing on the right sub the left substring in this case we're focusing on the left substring to see if it's actually inside the dictionary if it is then we want to make sure this is also true right otherwise if this is true and this is not true that won't that will not make sense so in this case we want to make sure this is true then we want to make sure that we also don't have the string computed in the like we basically want to make sure that we did compute this string in the cache in this case it contains this string we want to make sure that if cache.contains this key we want to return this element right inside the cache dot git s okay because we don't want to compute this thing another time so what we're going to do then is we're going to iterate so we're going to traverse starting from index um starting from the next one okay what we're going to do is we're going to traverse and is equal to s dot length while i is less than equal to n because we want to include the last element when we split in okay because when we say substring we want to pass in the star index the n index including the last element right so in this case we all we will also um iterate the last element as well so we're going to do is we're going to to get the substring the left substring is basically equal to that's the substring okay we passed the substring starts and i right so in this case we the left is basically the left side of the current pointer and the right substring okay is equal to as the substring high at all the way to the end right in this case we're all all the way to the last element in this in the in the string so in this case the current pointer all the way to the very very right or the last element um including the last element in the string then we're going to do is we're going to see just like what we talked about here right we want to see if the left sub string is actually in the dictionary so in this case dictionary dot contains i'm going to see if this contains the left substring and we want to make sure that if helper contains the right substring if that's the case then we're going to do is we don't want to compute this again of course we're going to return true but we don't want to compute this again so we're going to do is we're going to use cache.put we're going to put right sorry we're going to put s as the current string right so so this current string the current this current string we already computed so we don't want to compute this again so this this s is going to be the key the value is going to be true because we already checked that the current string is true it is a valid word break okay so we can just return true and we will make sure that we save this result in the cache then what we're going to do is after we've done iterating we know that this is going to be false because there it didn't really satisfy this condition so we're going to do is we're going to say cache.put s is going to be false okay because we know that this is nothing really happens we're going to another thing we have to do is there another thing we have to do is there could be a empty could be a empty string in this case so what we're going string in this case so what we're going to do is we're going to say if s the to do is we're going to say if s the length length is equal to 0 then we can also return is equal to 0 then we can also return true true okay so now let's try to run the code okay so now let's try to run the code and let's try to submit and let's try to submit so now you know how to solve this so now you know how to solve this problem and problem and as you can see the substring method as you can see the substring method takes a linear time complexity so takes a linear time complexity so therefore our therefore our our time complexity is not going to be our time complexity is not going to be big o of n big o of n and square instead instead we're we're and square instead instead we're we're having a big o having a big o of n to the power 3 for time complexity of n to the power 3 for time complexity okay and um basically for space okay and um basically for space complexity complexity is going to be big o of n where n is is going to be big o of n where n is number of characters in the string right number of characters in the string right um yeah basically here you can see we um yeah basically here you can see we have have cash right so you can see every time cash right so you can see every time when we save an element when we save an element computer result we save the result onto computer result we save the result onto the cache the cache hash map right so therefore we have n hash map right so therefore we have n elements in the cache so elements in the cache so there you have it right so basically i there you have it right so basically i know it takes know it takes it is a very hard problem um to digest it is a very hard problem um to digest but i believe that um the more you do but i believe that um the more you do dynamic programming problems the more dynamic programming problems the more you get good at them and as long as you you get good at them and as long as you know how know how you can do them like the the core you can do them like the the core idea behind solve solving this word idea behind solve solving this word break problem break problem you should be able to solve this problem you should be able to solve this problem easily there you have it and thank you easily there you have it and thank you for watching | 2024-03-21 12:23:45 | 139 | [Java] Leetcode 139. Word Break [DP Distinct Ways #7] |
|
3YHSz5GLmFo | hey everyone uh in this video i'm going to explain the solution to explain the solution for a lead code question called game of for a lead code question called game of life life which is is by some big tech companies which is is by some big tech companies and also at the same time i'm going to and also at the same time i'm going to go through the go through the steps we should follow in the real code steps we should follow in the real code interview so let's get started interview so let's get started so in the real coding interview the so in the real coding interview the first step is always try to understand first step is always try to understand the question the question and uh if there is any there if there is and uh if there is any there if there is any any ambiguous part feel free to bring out ambiguous part feel free to bring out the question and the question and at the same time think about some ash at the same time think about some ash cases cases that can potentially break the general that can potentially break the general solution in the next step solution in the next step so let's go through this question so let's go through this question briefly so according to the wikipedia briefly so according to the wikipedia the game of life also known the game of life also known simply as life is a cellular automat simply as life is a cellular automat automaton device by the british automaton device by the british mass medicine whatever so the board is mass medicine whatever so the board is made up of made up of an m by n grade of cells where an m by n grade of cells where cell where each cell has an initial cell where each cell has an initial state life state life which is represented by one and that which is represented by one and that represented by zero represented by zero so each cell interacts with its eight so each cell interacts with its eight neighbors neighbors and there are four connections so for and there are four connections so for lifestyle lifestyle if there are fewer than two neighbors uh if there are fewer than two neighbors uh fewer than two fewer than two life neighbors it will die if there are life neighbors it will die if there are more than three left neighbor it will more than three left neighbor it will die die if there are two or three left neighbors if there are two or three left neighbors then it will continue to live then it will continue to live for the dead cell uh when there are for the dead cell uh when there are exactly three life neighbors then it exactly three life neighbors then it will become a live cell will become a live cell so this is a uh example so this is a uh example like a transition example so the like a transition example so the question is question is the next date so the next date is the next date so the next date is created by created by applying the above rule simultaneously applying the above rule simultaneously to every cell to every cell in the current state so we are going to in the current state so we are going to try to figure out try to figure out the next step and the next state for the the next step and the next state for the grade given the current grade grade given the current grade so this is an example so let's see some so this is an example so let's see some constraints constraints so it says that the given uh so it says that the given uh board is not going to be empty so we board is not going to be empty so we don't need to worry about that kind of don't need to worry about that kind of ash case ash case and also there will not there won't be and also there will not there won't be any illegal inputs because any illegal inputs because each of the cell is going to be either 0 each of the cell is going to be either 0 or 1. or 1. so and there is some follow-up question so and there is some follow-up question asking asking is it possible to do it in place the is it possible to do it in place the answer is answer is yes so this is exactly what our solution yes so this is exactly what our solution is about is about so the solution is a m by the runtime is so the solution is a m by the runtime is om by n and there is no extra space used om by n and there is no extra space used in this solution in this solution so the solution is in general uh so the solution is in general uh we we use two additional integers we we use two additional integers to represent a new states so to represent a new states so uh integer two means uh integer two means in the next day in the next state it is in the next day in the next state it is going to turn from that going to turn from that to live and for integer three it means to live and for integer three it means currently it is live but next next state currently it is live but next next state for it is that for it is that so um this so in so um this so in when we find so after we find the when we find so after we find the solution then we do some coding work on solution then we do some coding work on top of the top of the ideas about the solution so ideas about the solution so it is quite simple after we figure out it is quite simple after we figure out how we do it in place by introducing how we do it in place by introducing extra state so in here we introduce an extra state so in here we introduce an helper function which is uh to count helper function which is uh to count how many left neighbors are there for how many left neighbors are there for for for given a corresponding cell so there are given a corresponding cell so there are three parameters passed into it three parameters passed into it the board the row and the column so we the board the row and the column so we are going to return are going to return how many life neighbors are there for how many life neighbors are there for the given the current state the given the current state given the current row and the current given the current row and the current column column so within the major function so within the major function um every time we just um every time we just call the helper function to count the call the helper function to count the left neighbors left neighbors and follow the rules to update and follow the rules to update the corresponding board to the new state the corresponding board to the new state if possible and after that we have a new if possible and after that we have a new board we need to turn board we need to turn the intermediate states which are 2 and the intermediate states which are 2 and 3 3 into 0 and 1 and translated into 0 and 1 and translated after the translation the board is going after the translation the board is going to be the next to be the next state so that's essentially how we solve state so that's essentially how we solve this problem this problem so after you find the solution and you so after you find the solution and you discuss with your interior about the discuss with your interior about the solution solution you will do some coding work take care you will do some coding work take care about the correctness about the correctness readability and also uh don't be too readability and also uh don't be too slow in the coding part slow in the coding part and after you're done with coding it's and after you're done with coding it's not not a time to call it succeed you still need a time to call it succeed you still need to do some uh to do some uh testing uh to introduce some test cases testing uh to introduce some test cases twice to uh to inspect if there is any twice to uh to inspect if there is any bug within the code bug within the code so that's it for uh this uh question so so that's it for uh this uh question so if you have any questions about the if you have any questions about the puzzle or about the code puzzle or about the code feel free to leave some comments below feel free to leave some comments below if you like this video please help if you like this video please help subscribe to this channel subscribe to this channel i'll see you next time thanks for i'll see you next time thanks for watching | 2024-03-22 14:20:26 | 289 | Microsoft Coding Interview Question | Leetcode 289 | Game of Life |
|
luFZl0KmKzI | Hello hello everyone welcome to our channel audition in this video will be discussing the lowest in this video will be discussing the lowest comment and sister for * I am very famous comment and sister for * I am very famous problem that is present and internet code where it's nx is problem that is present and internet code where it's nx is 236 setting 236 setting categorized medium problem dalit and right categorized medium problem dalit and right for this problem meanwhile for this problem meanwhile for this problem meanwhile Problem and Deception Interesting Problems Can See the Number Flights Where is Very Huge Amount and This Problem Which College Teachers The Concept of Military Adventures of But Can Write Down the Scene Subscribe Button Records in Café Subscribe to a Point Cut to Length West End Sister Mother To Give It's Okay subscribe The Channel Eyes And The Giver Notes In The Present In The Giver That Me To Find The Best Method Best Results Method Where We Can Do The Thing So The Definition Of Alsi Battery Saving Events & Subscribe Details Water Retention How We Can Find A Solution For This Problem So Let's Do The Definition Of The Lowest Comments Subscribe Notes PM PM PM Nov 29 2013 By Both His Descendants Were Not Appear Different Topics Like It Is Pe That Notification our Channel and press the Video then subscribe to the Hai To Happy Is Adhed Review Me Times Discussed About Okay So Let's Look At The Constraints Number Of Units Industries Co * * * * * 10.51 To Write In Edition Solution Edition After And Solution Every It's Executive Who Can See The It's Executive Who Can See The It's Executive Who Can See The Maximum Number Of Votes Maximum Number Of Votes Standard To The Power 5325 Turn Off An Standard To The Power 5325 Turn Off An Object Solutions Chapter Notes Values Object Solutions Chapter Notes Values Like And Toys Is Going To Liquid Water Like And Toys Is Going To Liquid Water Not Valid Notes Will You Must Bring To Not Valid Notes Will You Must Bring To Front NFC Of Units wwin.com.in PM Front NFC Of Units wwin.com.in PM Must Must Must Complexity Like Sid Difficulty Problem Increase Pairs Aby Samaddar Ki Sampoorna And Let's Celebrate And Soapy Thank You Will Exist In The Tree Shodhak Hain Yes A Helping Others Charity Organization Peace Not Able To Give And Not For On subscribe difficulty this problem On subscribe difficulty this problem On subscribe difficulty this problem subscribe so subscribe so let's check the definition of subscribe the let's check the definition of subscribe the Channel please subscribe and subscribe Channel please subscribe and subscribe the Channel subscribe so you can just for the Channel subscribe so you can just for the definition of the different between both the definition of the different between both presidents loot ok sorry presidents loot ok sorry darshan point to definition we will darshan point to definition we will consider the best definition of consider the best definition of SCS SCS SCS not where is a p and q to the root node and white apart from the no data is the tree why not broken find the first common intersection of the notes present in the past few can see the first woman Coming Reduce Note Member Coming Reduce Note Member Coming Reduce Note Member LC Of The Two Not Let Me Take Another To Said LC Of The Two Not Let Me Take Another To Said Black Much More Clear To Understand And Black Much More Clear To Understand And Definition Of Subscribe 99264 Okay What Definition Of Subscribe 99264 Okay What Is The Part Of From Today No Differences 65 Is The Part Of From Today No Differences 65 Sui And What Is The Part Of The 232 The Sui And What Is The Part Of The 232 The Five Five Have Entry Have Entry Have Entry where is like comment It is intercepting in 12th part That is the first not starting from this They release after days Apache 160 258 125 Lowest comment on this and sister of K Sauce How To Build K Sauce How To Build K Sauce How To Build Up The Record Solution To Find The Lowest Up The Record Solution To Find The Lowest Comment And Sister Of Do Not Speak When You Were Comment And Sister Of Do Not Speak When You Were Painted Notes Address Okay Yashodhara Painted Notes Address Okay Yashodhara To Possible K Cystitis K So Let Me Just To Possible K Cystitis K So Let Me Just Take A Basic Sham Pal Yes Okay So We Are Take A Basic Sham Pal Yes Okay So We Are Talking Word Verification Pal Talking Word Verification Pal Talking Word Verification Pal This Is The Not Give Ok So This Is The Not Give Ok So This Is The Not Give Ok So Subscribe To This Channel Must Subscribe The Subscribe Skimming No David Doraemon PM Why Light To Keval Se Alsi That That Belongs To Is The Chappi And Why Tota To Is The Chappi And Why Tota Darad Possible How Time Stock Investors Darad Possible How Time Stock Investors Very First Day Test Ke Swa The Not Very First Day Test Ke Swa The Not Very First Day Test Ke Swa The Not one can see the first international and national president of the lord will stop at another ki subscribe the case me ka haq so sapoch agar is rumor note speed andar siddha note ki vacancy celsius coming about water shortage cs5 loot celsius coming soon test live Hakeem Saud RCA So How To Figure Out How To Write An Hakeem Saud RCA So How To Figure Out How To Write An Hakeem Saud RCA So How To Figure Out How To Write An Application To Record Just Application To Record Just Solution Improve To Write To Catchup The LCA Solution Improve To Write To Catchup The LCA Interest Test In Just One Record Se Interest Test In Just One Record Se Twist Ok 100 Withdraw It's Ok Is Twist Ok 100 Withdraw It's Ok Is Basically Pappu Safed Just Talking About This Basically Pappu Safed Just Talking About This Close Its Clear 2009 Dec Close Its Clear 2009 Dec us office let me down clearly don't know the us office let me down clearly don't know the spirit to ride on record saying step spirit to ride on record saying step in the country were always just trying to fetch daru left the work on work on me myself writing down route left and me myself writing down route left and points to * base route route ok sir points to * base route route ok sir points to * base route route ok sir thing is like you can see and just kidding may top right now in tamil explain it acetic acid something has been written in the record seat function in see free mode start ok so let's have been stored in a valuable student's so let's something King returned with equal roots love and something King returned with equal roots love and something King returned with equal roots love and something is king and twinkle fruits right ok ok is king and twinkle fruits right ok ok 9 after writing 20 two steps 9 after writing 20 two steps with daily up-to-date with no one thing what with daily up-to-date with no one thing what is that one thing ok so in this current notice is that one thing ok so in this current notice form note from this here equal to speed form note from this here equal to speed form note from this here equal to speed mic content note this inch width equal to do not disturb time current notice to you can easily set s e can we have that is my route not match with national scene compromise this current node ok so effect matches with appear key vacancy dot sm Going To Be Town Root Okay Dear Not Understanding Enmity Stuart Broad Pendant Music Play List With The Help Of Diagram Withdrawal Will Just Fee No Dinner Activist I Will Be Town Root Which Can Be A Shadow Over Arvind Fee No I Will Return And Such Incident Which Does And Such Incident Which Does And Such Incident Which Does Not This Is Not Regret And Again And Not This Is Not Regret And Again And Destructive Values And Again And Destructive Values And Again And Deposit And Withdrawal See Now Not Deposit And Withdrawal See Now Not Withdrawal It's Not Considered This It's Something In Withdrawal It's Not Considered This It's Something In Return From Left And Something In Return Return From Left And Something In Return For Not Considered Thing But Also For Not Considered Thing But Also Let Me Do Something Take Let Me Do Something Take Let Me Do Something Take note 5 day wear note 6 and they have something that note does not sit that note 4 ok not considered a sin and talking about this is the giver not and disappeared and you can see the alsi apn thing The note 5 The note 5 The note 5 ok happy because just how to this ok happy because just how to this determine from here root of baroda se nazar determine from here root of baroda se nazar matching with speech e not matching with you matching with speech e not matching with you work with her boobs and so before writing this work with her boobs and so before writing this point to write down one thing in what point to write down one thing in what is that one thing ok so let's is that one thing ok so let's is that one thing ok so let's best speech and I don't think so ifin e-mail yes not equal to null ki and are you should not equal to null ka hak re kyun is i lash not na lene and is nodal every town mic current route dushmane This Is My Lazy Dhak Hai Not Understanding Is No Need To This Is My Lazy Dhak Hai Not Understanding Is No Need To This Is My Lazy Dhak Hai Not Understanding Is No Need To Worry About Worry About Sports In This Is Like Profile Route Sports In This Is Like Profile Route Notice Under Certain Developed Step That Is Notice Under Certain Developed Step That Is My Route Maz Pay You Can See I Will Return My Route Maz Pay You Can See I Will Return In This Route With Its Node Raat Dushman Naagin In This Route With Its Node Raat Dushman Naagin More Steps Will More Steps Will More Steps Will Return Key Okay No One Comes With His Position But I Will Have Developed As Not And Will Have The Right To Airtel Dish Not Okay So Let's Not Not Not Nil Nil Return On Equity Will Return Dushman Dushman Truth And Must Subscribe 9 Must Subscribe 9 Must Subscribe 9 This Is Not Sufficient I Need To Include One This Is Not Sufficient I Need To Include One More Condition And Digests Sexual Tourist Complete More Condition And Digests Sexual Tourist Complete The System Of The Lines On This Code The System Of The Lines On This Code To Feel You Much Better Ok So Button Ko Incident To Feel You Much Better Ok So Button Ko Incident This Statement Of Root Fruit Is Not This Statement Of Root Fruit Is Not Subscribe This Video Not Loot Subscribe This Video Not Loot Subscribe This Video Not Loot Something Is The Definition Subscribe In A Reader And Will Do Not Disturb Me Less Will Do The Thing And You Cannot Be Tried To Celebrate Its Roots And There's Something On That Narmada Ashtak In Copy Down Narmada Ashtak In Copy Down Photo Copy Dentist In Varied Them Just Photo Copy Dentist In Varied Them Just Root Root Root Build Up Something More Interesting Than What Is That Something Interesting Facts About My Root Mez Pe Mod Root Subscribe Must Try That Now Before Doing Something They Remind Me Possibilities Day Celebrate And 8 Reasons But This Is And is not valid means loot descendant of And is not valid means loot descendant of And is not valid means loot descendant of migrant mode of but on migrant mode of but on pc in mid term node in left difficult to pc in mid term node in left difficult to pc in and construction odd node in r pc in and construction odd node in r independent medium to p and q here and there can be independent medium to p and q here and there can be anything ok tribes and anything ok tribes and reduced now electronics route this reduced now electronics route this reduced now electronics route this My Difficult Type-2 Egg Subscribe To I Your Show Writing This Is Patient And Want To Win A Tourist Include Everything Okay What Is The Thing You Can See What Will Happen In The Certain Record Acid This Point Distinguish Rich Person This Point Is Point To You can directly share the left hand side is returning nothing android 24900 hair pack to 9 9 subscribe this Video not withdrawal voice having no develop it's not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not only only only 209 209 hai submit dispute ki awardee submitted isko driver vacancy dasharan times and very much good runtime vitamin superintendent missions hakeem time when best and typing yes ok 151 do it means the comment section yadav video and don't forget to ask any five Bilas for Doubts Bilas for Doubts Bilas for Doubts the Best Like this Video Status Video the Best Like this Video Status Video with subscribe our YouTube Channel Par with subscribe our YouTube Channel Par Latest Updates Thank You for Watching this Latest Updates Thank You for Watching this Video | 2024-03-22 11:27:48 | 236 | Lowest Common Ancestor of a Binary Tree | Binary Tree | 236 LeetCode | LeetCode Explore | Day 30 |
|
NklXHcUS7mM | hi everyone it's Cen today we have a problem when we are planning a travel problem when we are planning a travel one year in advance and for example one year in advance and for example let's take this scenario we are let's take this scenario we are traveling let's say that on the 1st 4th traveling let's say that on the 1st 4th 6 7 8 and the 20th day of the year and 6 7 8 and the 20th day of the year and we need to calculate the how the minimum we need to calculate the how the minimum number of the minimum number of dollars number of the minimum number of dollars so minimum amount that we can pay for so minimum amount that we can pay for our travel so minimum number and for one our travel so minimum number and for one day pass we are paying cost zero we are day pass we are paying cost zero we are also given the costs so for a 7 day we also given the costs so for a 7 day we are paying for example in this case $7 are paying for example in this case $7 and for the 30-day we are paying $15 and and for the 30-day we are paying $15 and we need to calculate what's the minimum we need to calculate what's the minimum number of what's the minimum amount we number of what's the minimum amount we can pay for our travel so for example can pay for our travel so for example let's take this case in this case we let's take this case in this case we have for the first day we can pay $2 have for the first day we can pay $2 right for one day pass for the next four right for one day pass for the next four days we can pay $7 because it will cover days we can pay $7 because it will cover all these days right it will cover all these days right it will cover fourth 6 7 and eight and for the last fourth 6 7 and eight and for the last day we can pay $2 and 2 + 7 day we can pay $2 and 2 + 7 + 2 gives us $11 which we are returning + 2 gives us $11 which we are returning so the way we are going to solve this so the way we are going to solve this problem we are going to use a dynamic problem we are going to use a dynamic programming bottomup approach let's take programming bottomup approach let's take the example that we had earlier the example that we had earlier 4 6 4 6 7 8 and 20 so what's the idea behind 7 8 and 20 so what's the idea behind dynamic programming bottom up approach dynamic programming bottom up approach the idea is that we are solving a sub the idea is that we are solving a sub problems of the problem that helps us to problems of the problem that helps us to build up to our solution so for example build up to our solution so for example in this case we are creating an array in this case we are creating an array with the same size as of our of our with the same size as of our of our array and we are also adding here zero array and we are also adding here zero I'm going to explain why in a second so I'm going to explain why in a second so we are so it's the same size of our as we are so it's the same size of our as our array and um and also we have we we our array and um and also we have we we are going to put here in our case two are going to put here in our case two pointers I and the J right so let's say pointers I and the J right so let's say that we are just paying for the one day that we are just paying for the one day pass and we are for example for the pass and we are for example for the first one day pass we are paying for the first one day pass we are paying for the first day right we are paying $2 for the first day right we are paying $2 for the next day so we here we are adding that next day so we here we are adding that the total number of total amount that we the total number of total amount that we are paying for our travel right so for are paying for our travel right so for the first day we are paying $2 for the the first day we are paying $2 for the next day we are paying also $2 right so next day we are paying also $2 right so 2 +2 is $4 so and for the next for the 2 +2 is $4 so and for the next for the six again we are using so we have one six again we are using so we have one day which is in our case $2 for the day which is in our case $2 for the second for the seven days we are paying second for the seven days we are paying $7 and for Theif for the 30 $7 and for Theif for the 30 days for the 30 days we can pay $15 days for the 30 days we can pay $15 right so now we are using only one day right so now we are using only one day pass for now just we are paying for $4 pass for now just we are paying for $4 and here we are paying for we are paying and here we are paying for we are paying our our also for one day pass so 4 + 2 is 6 here also for one day pass so 4 + 2 is 6 here we are paying for the seventh day of the we are paying for the seventh day of the year we are paying all for one day we year we are paying all for one day we are buying one day pass so it's $8 and are buying one day pass so it's $8 and now we moved our I and the J pointer now we moved our I and the J pointer here so the idea is in our case that we here so the idea is in our case that we are let's solve this sub problem right are let's solve this sub problem right let's say that for only these four days let's say that for only these four days can we do better than that can we pay can we do better than that can we pay for the for these days right for 176 for the for these days right for 176 uh 4 6 7 can we pay less than $7 yes we uh 4 6 7 can we pay less than $7 yes we can the way we are going to do that the can the way we are going to do that the way we are our approaches we are going way we are our approaches we are going to move our JP pointer backwards as far to move our JP pointer backwards as far as we can and uh let's say that as far as we can and uh let's say that as far as we can until it's for example first as we can until it's for example first we are checking for the 15 then we are we are checking for the 15 then we are checking for the 30 days right so first checking for the 30 days right so first we are going to check for the 7 day so we are going to check for the 7 day so we are moving our J pointer until the we are moving our J pointer until the difference of the I and the J so difference of the I and the J so basically this days days I right minus basically this days days I right minus days J so this difference is this this days J so this difference is this this difference is less than or equal to 7 so difference is less than or equal to 7 so it's less than or equal to 7 so for it's less than or equal to 7 so for example we can move our J until this example we can move our J until this point right until the beginning of the point right until the beginning of the array right until we can we can move our array right until we can we can move our J pointer here so it means that the this J pointer here so it means that the this port portion right this portion of the port portion right this portion of the array this portion of the array we can array this portion of the array we can replace with the cost I with the 7 Days replace with the cost I with the 7 Days right we can replace that with the cost right we can replace that with the cost I cost I cost one actually in our case I cost I cost one actually in our case we can replace with the cost one and now we can replace with the cost one and now we are checking now we are comparing so we are checking now we are comparing so at each step we are taking the minimum at each step we are taking the minimum value minimum value of whatever the value minimum value of whatever the value is here whatever the value is here value is here whatever the value is here DPI right whatever the value is here or DPI right whatever the value is here or we are taking either eight in our case we are taking either eight in our case it's eight right or we are taking that it's eight right or we are taking that whatever our dpj wherever we moved whatever our dpj wherever we moved because up to this point we have because up to this point we have calculated our total sum right now we calculated our total sum right now we want to replace this part with the with want to replace this part with the with our cost one so with the seven days so our cost one so with the seven days so now we are taking we are doing exactly now we are taking we are doing exactly that one here so we are doing the PJ that one here so we are doing the PJ right the PJ so this part plus this part right the PJ so this part plus this part right this part plus this part Plus right this part plus this part Plus whatever the value of the cost I cost whatever the value of the cost I cost one right whatever the value of cost one one right whatever the value of cost one it's our it's our costs right so whatever the value is so costs right so whatever the value is so for example in this case this value is for example in this case this value is zero let me put that in another color so zero let me put that in another color so this value is eight right this value is this value is eight right this value is eight from here and this value is 0 + 7 eight from here and this value is 0 + 7 right so yes we can do better than that right so yes we can do better than that we are replacing eight with this with we are replacing eight with this with the seven here so right right we are the seven here so right right we are setting seven here so that is the our setting seven here so that is the our approach so basically at each step we approach so basically at each step we are we have two pointers right I and J are we have two pointers right I and J at each step we are moving our J pointer at each step we are moving our J pointer as far as we can move for example in the as far as we can move for example in the first case we are doing that for the first case we are doing that for the seven days so we are moving seven we are seven days so we are moving seven we are moving until this value is less than or moving until this value is less than or equal this this equation is less than or equal this this equation is less than or equals to 7 so we are moving our J and equals to 7 so we are moving our J and in the second case we are moving our J in the second case we are moving our J until this equation is less than or until this equation is less than or equal to 30 and we are replacing that equal to 30 and we are replacing that part of the array right that part of the part of the array right that part of the array whatever the cost is either cost array whatever the cost is either cost one or cost two plus whatever the sum is one or cost two plus whatever the sum is up to that uh first thing to do let's up to that uh first thing to do let's take the size of our array let's call it take the size of our array let's call it n and because we are going to use that a n and because we are going to use that a lot so let's take the days lot so let's take the days length Okay and now let's create our length Okay and now let's create our array where we are going to store our array where we are going to store our total amount DP right which we are going total amount DP right which we are going to return at the end so what's the to return at the end so what's the what's going to be the size of it the what's going to be the size of it the size of it we are going to take int and size of it we are going to take int and we are going to take that n + one right we are going to take that n + one right because we are also using the zero index because we are also using the zero index so and also at the end we are going to so and also at the end we are going to return the P let's just return it right return the P let's just return it right away we are going to return whatever the away we are going to return whatever the last element is whatever the value of last element is whatever the value of last element is okay now we can go over last element is okay now we can go over our array and we can populate our DP uh our array and we can populate our DP uh array of integers so for that let's array of integers so for that let's start we are going to start from the one start we are going to start from the one right we're going to start I is equals right we're going to start I is equals to 1 I is less than or equal to n and uh to 1 I is less than or equal to n and uh I I ++ ++ so what we are going to do here first so what we are going to do here first let's add just a direct cost for the for let's add just a direct cost for the for the the for one pass right and then we are going for one pass right and then we are going to see that the can we can we improve to see that the can we can we improve that so that's what exactly we are going that so that's what exactly we are going to do here we are adding DPI so we are to do here we are adding DPI so we are adding so whatever the previous value is adding so whatever the previous value is right whatever the previous value is we right whatever the previous value is we are adding our current cost so we are are adding our current cost so we are adding our cost for one day pass which adding our cost for one day pass which is zero okay so now what we are going to is zero okay so now what we are going to do we are going to check that can we do we are going to check that can we replace that with the seven or 15 so now replace that with the seven or 15 so now let's check for first for the four so let's check for first for the four so now let's check for first for um now now let's check for first for um now let's check for first for seven days so let's check for first for seven days so for that we are going to do inj is for that we are going to do inj is equals to we are setting our J that is equals to we are setting our J that is equals to one but not one but the uh not equals to one but not one but the uh not not not I but the IUS one right IUS not not I but the IUS one right IUS one and now we are starting to move our one and now we are starting to move our J point as far as possible so to do that J point as far as possible so to do that we are going to move that until it's we are going to move that until it's equals or more than more than one right equals or more than more than one right equals or more than one actually vice equals or more than one actually vice versa and and also the another condition versa and and also the another condition is that it should be less than the is that it should be less than the difference should be less than 7 days so difference should be less than 7 days so then the i - one i i - one minus days then the i - one i i - one minus days J minus one J minus one it should be J minus one J minus one it should be less than less than S so we are moving as far as possible S so we are moving as far as possible and we are decrementing our J so at the and we are decrementing our J so at the next step what we are going to do we are next step what we are going to do we are going to then take the minimum so now going to then take the minimum so now for the DPI for each step we are going for the DPI for each step we are going to repeat the same so we are going to to repeat the same so we are going to check that the okay what is the can we check that the okay what is the can we replace that portion of the array right replace that portion of the array right so min minimum we are going to so min minimum we are going to take the PI right the value that we have take the PI right the value that we have at this point for example in our case it at this point for example in our case it was eight right or the PJ the PJ so we was eight right or the PJ the PJ so we moved our J now we are taking J plus the moved our J now we are taking J plus the cost that we have at one right so we are cost that we have at one right so we are trying to replace it whatever is the trying to replace it whatever is the minimum we if if let's say this value minimum we if if let's say this value right we moved our J so let's say that right we moved our J so let's say that the Value at0 Plus 7even if that is less the Value at0 Plus 7even if that is less than that then we are going to set to than that then we are going to set to our to our DPI we are going to set this our to our DPI we are going to set this value all right so now exactly the same value all right so now exactly the same exactly the same we are going to do for exactly the same we are going to do for for 15 for 30 days right so exactly the for 15 for 30 days right so exactly the same we are going to do same we are going to do for for 30 days here and uh it's going for for 30 days here and uh it's going to be cost of to be cost of two cost of of two cost of of two yeah that's it let's run it okay we forgot to add the return statement here also it should be costs costs time yeah here we already did defined J okay it works as expected now let's calculate the time and space complexity what's the time complexity of this solution we are solving this problem in one pass right but we are moving our J point ERS at each at each step so but they are constant right we are moving seven at at most we can move seven and the 15 so our we that we are not taking that into equation so our time complexity is of n how about the space complexity it's defined by the size of our DP array and in our case it's n let's just go over it one more time so idea is that we are using dynamic programming bottom up approach so at first what we do we are first calculating the direct cost here right we are calculating the direct cost direct cost meaning that for one day pass and then we are at each step we are checking that can we do better than that so we are moving our J pointer until it's either until it's uh less than until the difference is less than 7 days so which means that the for all days that is that we can include in the in those seven days and we are taking that okay the day so whatever the sum was the before that right before those seven days that and the plus the cost one which means that for seven days is it less than that the current amount that we have if it's less than we are updating that exactly the same we are doing for 15 days okay I hope you like my content if you like it please hit the like button and subscribe my channel see you next | 2024-03-25 14:28:02 | 983 | LeetCode - 983. Minimum Cost For Tickets | Dynamic Programming Bottom Up | Java |
|
YkQpLyf6i2I | what's up guys episode is here with another lead code question and today another lead code question and today we're solving leak code 451 sort we're solving leak code 451 sort characters by frequency once again if characters by frequency once again if you want to solve this problem please you want to solve this problem please take the time to solve it and come back take the time to solve it and come back to this video once you've solved the to this video once you've solved the problem problem awesome so for this problem we're given awesome so for this problem we're given a string and we need to sort it in a string and we need to sort it in decreasing order based on the frequency decreasing order based on the frequency of the characters and as you can see the of the characters and as you can see the constraints are as follows our string constraints are as follows our string only consists of uppercase and lowercase only consists of uppercase and lowercase English letters and digits so that means English letters and digits so that means we're not going to get any characters we're not going to get any characters that are not letters in digits so let's that are not letters in digits so let's go ahead and get into our examples and go ahead and get into our examples and our examples are pretty much our examples are pretty much self-explanatory for the first one we self-explanatory for the first one we have our input tree and we return this have our input tree and we return this as our output and that's very as our output and that's very self-explanatory and similarly for self-explanatory and similarly for example two we have this is our input example two we have this is our input and we return this as our output and you and we return this as our output and you can see by our explanation we could can see by our explanation we could either have our A's appear first or we either have our A's appear first or we could have our C's appear first and could have our C's appear first and they're interchangeable because they they're interchangeable because they pair with the same amount of frequency pair with the same amount of frequency and example three is really when we and example three is really when we actually get into some form of an edge actually get into some form of an edge case and the reason why is because we case and the reason why is because we have two occurrences of a one uppercase have two occurrences of a one uppercase and one lowercase and by the explanation and one lowercase and by the explanation you can see that this problem is case you can see that this problem is case sensitive so we count these two two sensitive so we count these two two letters differently so now let's letters differently so now let's actually talk about how we would solve actually talk about how we would solve this problem and solving this problem in this problem and solving this problem in code is very similar to how we would code is very similar to how we would solve it when writing it down or how we solve it when writing it down or how we would solve it as a human so let's get would solve it as a human so let's get into that let's solve this problem using into that let's solve this problem using example three since it's our most example three since it's our most comprehensive case so basically what we comprehensive case so basically what we would do as a human is we would look at would do as a human is we would look at our string and see which characters our string and see which characters appear within our string so we have appear within our string so we have uppercase a uppercase a lowercase a and lowercase b lowercase a and lowercase b and then we would count how many times and then we would count how many times each of those characters appear within each of those characters appear within our string so uppercase a pairs one time our string so uppercase a pairs one time lowercase a also appears one time and lowercase a also appears one time and lowercase b occurs two times now that we lowercase b occurs two times now that we know the frequency of each character now know the frequency of each character now let's sort them by their frequency in let's sort them by their frequency in descending order descending order so we know that b occurs first and then so we know that b occurs first and then a lowercase and a uppercase occur second a lowercase and a uppercase occur second or third because they're interchangeable or third because they're interchangeable and then now when we want to construct and then now when we want to construct our string we can just construct our our string we can just construct our string by going through our sorted list string by going through our sorted list and then inputting each character the and then inputting each character the amount of times it occurs within our amount of times it occurs within our original string so for example B occurs original string so for example B occurs two times so we would have B in our two times so we would have B in our result string two times lowercase a result string two times lowercase a occurs once so it comes in there one occurs once so it comes in there one time and similarly uppercase a occurs time and similarly uppercase a occurs once once and this is our result stream and as and this is our result stream and as explanation for example three shows explanation for example three shows lowercase a and uppercase a can be lowercase a and uppercase a can be switched in the order of our result switched in the order of our result string because they are interchangeable string because they are interchangeable and that's pretty much it for the idea and that's pretty much it for the idea behind the code now let's get into the behind the code now let's get into the code code and the code for this kind of makes this and the code for this kind of makes this a sort of easier medium problem so let's a sort of easier medium problem so let's go ahead and get into the code so the go ahead and get into the code so the first thing that we actually need is a first thing that we actually need is a dictionary and this dictionary is going dictionary and this dictionary is going to keep track of the frequency of each to keep track of the frequency of each character that appears in our string and character that appears in our string and then we also need our result string then we also need our result string which we are going to return which we are going to return and the first thing we're going to do is and the first thing we're going to do is we're going to Loop through each we're going to Loop through each character in our string and we're going character in our string and we're going to count its frequency within the string to count its frequency within the string and we do that with the following line and we do that with the following line frequency r0 r0 plus one and basically when basically plus one and basically when basically what this piece of code right here does what this piece of code right here does is that if our character isn't in our is that if our character isn't in our dictionary it's going to fill that value dictionary it's going to fill that value with 0 and then add one if it is in our with 0 and then add one if it is in our dictionary then it's just going to dictionary then it's just going to return the value that we already had for return the value that we already had for frequency so this is our first pass over frequency so this is our first pass over our string and then what we want to do our string and then what we want to do now that we have the frequency of each now that we have the frequency of each character within our string we want to character within our string we want to sort those frequencies in descending sort those frequencies in descending order and we can just do that with the order and we can just do that with the built-in python function sorted built-in python function sorted and we want to sort and we want to sort our frequencies based on the values in our frequencies based on the values in our dictionary so we just use some our dictionary so we just use some Lambda Lambda some Lambda calculus and then since we want it to be descending we want to set reverse to true okay so now this is our frequency dictionary sorted in descending order and it's now a list and now what we want to do is we want to go through that list and go ahead and create our result string so for card count and our descending list what we want to do is you want to set result equal to or this is pretty much just adding the car the character uh the amount of times it appears within our original string and then we just want to go ahead and return that result and this should be all the code for this problem and we can go ahead and submit that and see if this works so we see that this works and the percentages are pretty low but on other tries the percentages will be high for the memory and the runtimes that we beat so the actual run time for this problem is o n plus log n because we have two linear operations this is this first linear operation and this is our second linear operation and then our logarithmic operation is actually sorting our frequency dictionary and sorted takes log and time in Python so this is an oath n plus log n solution in terms of runtime so yeah that's all for this problem and please make sure to like And subscribe it helps a lot with the channel and I hope to see you again | 2024-03-22 14:18:33 | 451 | How to Solve Sort Characters By Frequency | Leetcode 451 | Python |
|
o3nfQf3I-AY | hello uh uh today i'm gonna solve the problem today i'm gonna solve the problem a minimum limit of volts in the back a minimum limit of volts in the back this problem this problem is quite hard is quite hard for me for the first time for me for the first time but once you but once you got got the way of the way of thinking it will be pretty simple thinking it will be pretty simple and arrogant and arrogant so let's get started so first of all we are given noms array and also max operations integers [Music] and [Music] we need to divide each number into two parts by one operation for example if you have nine and we can divide it into [Music] one and eight or we can choose uh any number four and five like that sorry and one thing to note is like we cannot choose 0 i mean 0 and negative numbers we just need to choose positive numbers more than one and we have two operations and we have two operations so we can divide it once more like one so we can divide it once more like one one nine one nine [Music] [Music] and let's say and let's say two two four four two two three like this three like this and after the operation we need to find the maximum number in this case maximum number is seven in this case maximum number is seven right right and in this case maximum number is four we we i we i we we want we need to return we want we need to return uh the division way uh the division way of minimizing of minimizing uh uh the maximum number in the result array we don't need to operate all the time i mean if max operations for example if we have a lot of operations for let's say we have 100 operations he's allowed it the best scenario is one one one the best scenario is one one one one one right one one right so in this case we don't need all of so in this case we don't need all of operations we just need 9 operations in operations we just need 9 operations in this case sorry 8 maybe 8 operations so in this case once the answer is one let's think about our operation is to we we if we have two operations so as example said the best scenario is three three three so the maximum number of disarray is three so we need to return three not seven not four so so the first i mean the first i mean in my intuition in my intuition i thought i thought we just need to pick we just need to pick a a most largest value i sold i will choose largest value so in this case in this case 8 is the largest right in this case 8 is the largest right so so we we i want to minimize 8 into some smaller i want to minimize 8 into some smaller parts parts so x and y right so generally we want to minimize x and y i mean both x and y so i thought oh we just need to divide by two in this case wonderful is a best approach and we we will uh loop this operation so for i range operations [Music] we will uh choose max value in array choose max value in array and divide max value by 2 and we we just and we we just iterate all the time and first of all we need to return max value in array but as you know this doesn't work let's think about simple example 9 in this case [Music] so in the previous approach we will divide it into 4 and five and we will choose five in this case right so we create two and three so we answer will be four but it's wrong right because the answer is three so i was stuck there so second thought so second thought [Music] [Music] is like is like we we we can think about the we can think about the best case scenario best scenario and best case scenario best scenario and what scenario what scenario the last scenario is simple the last scenario is simple if max operations is zero we we just if max operations is zero we we just need to return the maximum value right so so it means it means the answer the answer is between 1 and is between 1 and is is is between 1 and 9 in this case is between 1 and 9 in this case so it means so it means if we have answer let's say max value is between one and max right [Music] how can we know that for example in this case if you the best case scenario is one right but how can we know one is feasible in this case let's think about this array and and some operation i mean some operation i mean after after some operations we can get one one one some operations we can get one one one one one right one one right but but at least how many operations do we need it's simple because in order to get one deconstruct deconstruct two two in this case in this case so so in order to combat 2 into 1 in order to combat 2 into 1 we need 2 operations at least we need 2 operations at least same as 4 same as 4 we need four operations so so it means it means at least we need at least we need 6 14 16 operations in this case the minimum version should be uh oh i'm sorry oh i'm sorry that's my miss and that's my miss and we need minus one here and and sorry i i don't want to sorry i i don't want to write or write or so let's skip it but the total number should be 12 operations so how about 2 2 4 8 2 somehow we will have two two two two so in this case we we we need to have we we we need to have two divided by two minus one two divided by two minus one [Music] plus blah blah blah right before three plus one four operations [Music] because in order to combat eight to two we will create two six and two two four and two two two two say at least we need three operations about four about eight [Music] so what happened if we two two three three it means we don't need to set it one we wish we don't need to know is in the array so in this case we don't need to operate two so we just need to add to divide it to divide it by three plus four [Music] [Music] actually we don't need to actually we don't need to subtract one in this case so we need to substract one if two so right okay let's think about it simple so we will create this operation to maximum value [Music] so for each number we we will create operations we need to calculate operations we need to find we need to find the the point when we cannot i mean when operation is lower for example if max operation is 4 we for example if max operation is 4 we need to return 2 in this case need to return 2 in this case [Music] so if we cannot meet requirement we need to return this i so for each number we need so for each number we need let's think about if we set it as let's think about if we set it as already already will be n will be n and maximum number i don't know maximum and maximum number i don't know maximum number but let's think let's call it as number but let's think let's call it as fm we need n squared mn so one thing to note one thing to note is is operation operation is purely decreasing is purely decreasing in this case in this case [Music] [Music] i mean minimum required operations i mean minimum required operations is purely decreasing is purely decreasing it might be same but it's decreasing right so it we can use binary search to reduce the we can use binary search to reduce the calculation cost calculation cost so so if we use if we use binary search binary search it will be it will be o and rogen [Music] [Music] so let's write the code now so first of all we need to create helper function to calculate minimum required operations so card card hops we need to take noms array target value so response is 0 so response is 0 for each number for each number [Music] [Music] if [Music] [Music] we don't need to return else else it means it means model is zero in this case model is zero in this case uh we uh we need need to to substract by one let me write a simple test so [Music] [Music] is three is three three three three three three three two one like this two one like this and target [Music] [Music] what will happen so three cannot be divided by two i mean completely divided by two so it means we need to return numbers divided by target so this is one minus one zero zero so return number is one so return number is one and this is correct and this is correct okay it seems to work else else not to return not to return let's press [Music] [Music] so so max will be max will be maximum numbs so we will do by research in this case l l is equal one and max [Music] and for why is draw as than now now plus now plus uh minus 1 minus l divided by 2. so if so if serve dot so if serve dot corrupts is in this case in this case this mid is too small this mid is too small for the answer so we need to search for new value search for new value else we will move r hmm not well we need to return r in this not well we need to return r in this case maybe [Music] no it's very hard to consider edge cases every time in binary search program so so if we have one so if we have one two two three four five six three four five six seven what middle should be here are here and middle should be zero one two three four five zero one two three four five six so it means 0 plus 3 is so 4 is valid and next middle and next middle is here is here because zero press uh because zero press uh one is here right one is here right so so if 2 is not let's say let's say 2 is not valid we will have l is here m will be here right so l is not stereopartic so we will have next will be l and r here so answers should be current i mean they're in the last statement l equals to r so we we can return each one i mean e either one so so in the last statement if it's not valid in the last statement if it's not valid we will we will yeah sorry if it's valid we will move r yeah sorry if it's valid we will move r to here so to here so yeah yeah i think it works well let's avoid it [Music] to be honest this is my first submit and i'm very glad to pass it okay so this problem is i mean the implementation is pretty simple but uh the way of thinking is pretty complicated and also in order to implement binary search correctly we we need a little bit talk we we need to have template you can refer to this great post you can refer to this great post as a buyer such template as a buyer such template you need to you need to uh uh understand the core logic of wine understand the core logic of wine research research and you can easily make back and you can easily make back so let's please i mean so let's please i mean take care of it take care of it yeah so if if we didn't met if didn't we yeah so if if we didn't met if didn't we if if the condition isn't the condition isn't met met we need to this is a basic template and it's very applicable to our problem using mine research so | 2024-03-22 12:36:02 | 1,760 | 1760. Minimum Limit of Balls in a Bag |
|
e97RTYqLVHs | what is up everybody welcome back to my channel this is tony aka one lead code channel this is tony aka one lead code one day if you're new here this channel one day if you're new here this channel does one lead code per day following the does one lead code per day following the pattern of topics or series that is i'm pattern of topics or series that is i'm going to be solving with you together on going to be solving with you together on a lead code problem i have never a lead code problem i have never attempted before attempted before you heard that right there is no you heard that right there is no prescribed hit enter prescribed hit enter we are on the same page here but don't we are on the same page here but don't you worry i got your back and i promise you worry i got your back and i promise that i will submit at least one average that i will submit at least one average code code average performance code at the end of average performance code at the end of each video so here's a little bit about each video so here's a little bit about myself myself i come from a non-computer science i come from a non-computer science background background so i am no better off than most if not so i am no better off than most if not all of you guys in terms of coding all of you guys in terms of coding knowledge but that is okay if i can do knowledge but that is okay if i can do it you can do it it is all about it you can do it it is all about learning on the go and you can think of learning on the go and you can think of this video as a first person game play this video as a first person game play of cracking lead codes and who doesn't of cracking lead codes and who doesn't like first person gameplays like first person gameplays so without a do let's start today's code so without a do let's start today's code problem problem um today we continue on series one um today we continue on series one everything about dynamic programming and everything about dynamic programming and the problem is one five two maximum the problem is one five two maximum product sub array product sub array also i would like to announce a change also i would like to announce a change of strategy of strategy taking from lessons uh yesterday so taking from lessons uh yesterday so yesterday if you watched my yesterday's yesterday if you watched my yesterday's video um i did video um i did problem problem 918 918 maximum sum circular sub-array and i maximum sum circular sub-array and i took took about 12 hours to actually about 12 hours to actually finish and manage to submit that problem finish and manage to submit that problem um um it was a heck of a day and it was a heck of a day and i went through a lot to actually get i went through a lot to actually get something something right right but but here's the lesson here's the lesson if you're just taking lead code for code if you're just taking lead code for code practice practice towards a skill set maybe for a job or towards a skill set maybe for a job or for your career for your career path um path um optimizations optimizations then do not then do not like spend all day long on just one like spend all day long on just one problem because that's not what lead problem because that's not what lead code is intended for code is intended for um so um so rather you would you would just try rather you would you would just try experiment the problem on your own for a experiment the problem on your own for a bit maybe an hour maybe or two um bit maybe an hour maybe or two um depending on your pace and then if you depending on your pace and then if you don't get it that's fine just take a don't get it that's fine just take a look at the solution or some other look at the solution or some other people's code submitted people's code submitted and then try to learn the structure the and then try to learn the structure the the algorithm that people are using the algorithm that people are using and then just try to implement that on and then just try to implement that on your own your own um so there's no shame in uh um so there's no shame in uh not finishing one lead code completely not finishing one lead code completely by your own because nobody does every by your own because nobody does every lead code on their own lead code on their own eventually someday some problem will get eventually someday some problem will get you i promise you that although i've you i promise you that although i've only done like about 10 lead codes only done like about 10 lead codes up to now up to now but i think that is going to happen for but i think that is going to happen for almost everybody um almost everybody um like like don't really don't i hate to say this don't really don't i hate to say this but don't treat yourself special okay but don't treat yourself special okay you're not you're probably not that you know 0.01 coding genius that is born to do this without you know the proper education background in algorithms so i'm pretty sure i'm not that guy so um i did the i did the wrong choice yesterday to you know spend all day long on one problem and and so i'm going to change my strategy today and i'm going to work on this um problems from today on uh on a time problems from today on uh on a time limit so limit so uh uh for the first hour i'm going to try to for the first hour i'm going to try to come up with something that works and if come up with something that works and if if i don't find any uh hope of finishing if i don't find any uh hope of finishing it um it um uh uh within the next 30 minutes after one within the next 30 minutes after one hour or so hour or so i'm going to look at a problem solution i'm going to look at a problem solution and i'm trying to learn from it and i'm trying to learn from it and then i'm trying to implement that on and then i'm trying to implement that on my own my own after reading the solution or some some after reading the solution or some some other people's code so this is going to other people's code so this is going to be the change of strategy be the change of strategy uh and let's see how it goes all right uh and let's see how it goes all right that being said let's get into the that being said let's get into the problem okay maximum product sub array medium given integer array find a contiguous non-empty subarray contiguous means it's like a continuous right um within the array that has the largest largest product what is what does it largest product what is what does it mean by product or return the product mean by product or return the product the test cases are generated so that the the test cases are generated so that the answer will fit a 32-bit integer a sub-array is a contiguous subsequence the largest product is the largest product is 6 6 right because you don't want to multiply right because you don't want to multiply odd numbers of odd numbers of negative numbers negative numbers right example two right example two uh for this one actually it's going to uh for this one actually it's going to be zero be zero got it got it and then we have some constraints length and then we have some constraints length is between one and a large number is between one and a large number uh uh actually this is good like the actually this is good like the um the values of each um the values of each uh uh values of each number values of each number in the list is just between minus 10 to in the list is just between minus 10 to 10 so 10 so uh relatively small but if you think uh relatively small but if you think about you know about you know this is because because this is like a this is because because this is like a product so these things better be small product so these things better be small right the product of any prefix or right the product of any prefix or suffix of nums suffix of nums uh it's guaranteed to fit a 32-bit uh it's guaranteed to fit a 32-bit integer well that's good we don't have integer well that's good we don't have to talk about you know to talk about you know uh data type overflows in this case so uh data type overflows in this case so anyway anyway we're going to we're going to we're going to work on it for a bit uh let's start a python notebook first and rename that with today's lead code problem number 152 and whoops where's it here 152. now we're going to just put a mark down here and some examples and some examples so example one there so example one there right example one just right now copy the constraints in just right now copy the constraints in there there to remind us what constraints maybe we to remind us what constraints maybe we can exploit on our own yes there you go yes there you go and then we're going to copy the and then we're going to copy the solution template there solution template there right and now we're going to go back to right and now we're going to go back to think about the problem how to solve it think about the problem how to solve it so it is a so it is a maximum product problem so and it's within like a list or an array and we want to find a sub array uh so this naturally can be solved by dynamic programming because we're looking for a maximum of something and and it's sub array so and and it's sub array so looking for a subarray it could be maybe looking for a subarray it could be maybe generalized into generalized into sub problems and we sub problems and we solve solve we can do the bottom-up approach and we can do the bottom-up approach and solve sub-problems and then you know solve sub-problems and then you know solve eventually the the big problem solve eventually the the big problem let's you know without hesitation get let's you know without hesitation get into into uh prototyping and um and um how do we do that i mean we can iterate how do we do that i mean we can iterate but but that's probably not the best thing to do that's probably not the best thing to do um um or we can or we can or we can try to or we can try to be more strategic and think about what's be more strategic and think about what's what's the special thing about product what's the special thing about product product right um product right um so instead of sum when we talk about so instead of sum when we talk about products you want to first make sure products you want to first make sure that you know the signs matter right that you know the signs matter right signs matter that's the first thing that probably you should take into account like you don't want your final product to be negative so um so only take so only take uh negative uh negative negative values negative values in in in pairs right in pairs in in in pairs right in pairs and never singles yeah and never singles yeah only take them in pairs only take them in pairs right right yeah or let's say a multiple yeah or let's say a multiple of two or not or not you know or not take them or don't take them yeah or don't take them yeah so this is just the first lesson here um so this is just the first lesson here um i think it's important and then i think it's important and then of course of course aside from you know the negatives maybe aside from you know the negatives maybe well we can just split the list into well we can just split the list into maybe two sub lists right one is like maybe two sub lists right one is like positive one is negative positive one is negative and then you pick and then you pick and then of course you um and then of course you um but but because their position matters but but because their position matters too so a negative number is kind of like a door or like a barrier that you have to consider whether you're going to cross because because just like a door just like a door but then but then you want to you want to cross two doors at the same time like cross two doors at the same time like you don't want to just cross one door you don't want to just cross one door right and for multiplication you want really as many factors as you can because even because the the absolute values are like between minus between 1 and 10 and they're all integers so nothing hurts the only thing that can hurt you is the minus sign here right the only thing is the minus sign if just take just take all all as many as many numbers numbers as possible as possible in subarray in subarray right right in fact you want to take them all if you in fact you want to take them all if you can can and you only stop so just write that in fact so just write that in fact you want to take them all you only stop when when you know you know uh uh um when there there is like when there's when there's one one negative negative value left value left when there's one negative value left when there's one negative value left uh uh up uh uh up in front of you and you know and maybe some positive there's only one eight value left okay so right i think this is a good thinking right i think this is a good thinking picture this after you picked your picture maximum you are you're left with you are you're left with the you know the you know what's what's left left in the what's left in the array is one nothing one one negative negative value value and some on one side of it one side of the negative value the only negative value right so so this is a really good picture yeah yeah that's a really good relevation for that's a really good relevation for example example just for this problem right so after just for this problem right so after you've picked your after you've taken you've picked your after you've taken your pick your pick of your optimal of your optimal subarray you're always left with subarray you're always left with um um one one negative value either one negative value negative value either one negative value and some remainders and some remainders here write some remainder here write some remainder we're going to just use this bracket to we're going to just use this bracket to indicate the remainder indicate the remainder so this is the you know the one negative so this is the you know the one negative value that we're talking about the one negative valley left yeah uh and then you're gonna have maybe some positive remaining yeah this is some kind of like yeah the sum positive remaining on one side on one side yeah yeah so this and this is optional as well but this is you know optional existence existence of one of one negative value left negative value left yeah so this is like the optional of the yeah so this is like the optional of the optional right so in some cases you're just left with nothing right for example you could have an even easier case if you just have you know a plus two right right left with nothing so in this case we're left with nothing um what about let's say another case where you have you know uh a minus somewhere here right if this this case then um you know you're left with just a negative one negative value and that's it so in this case you know in this case you just take them all in this case you just take this right so yeah yeah these are like the the only three types of possible ending of the story uh right so these are like possible you know you know possible leftovers are you know possible leftovers are just like these three i think that just like these three i think that covers at all you're either left with covers at all you're either left with nothing or you're left with one nothing or you're left with one uh negative value uh negative value or you're left with or you're left with uh uh one negative value and the one negative value and the trailing uh set of positive values trailing uh set of positive values it could be on the left hand side it it could be on the left hand side it could be on the right hand side doesn't could be on the right hand side doesn't matter matter because you know because you know yeah let me just be more specific i yeah let me just be more specific i guess to explain this guess to explain this you know a fact if if you have you know if if you have you know 2k 2k plus plus 1 1 negative negative values values in nums you'll always use 2k of you always take yeah i always take 2k of and leave and leave one one unpicked unpicked that makes sense right that makes sense right i mean as long as you take i mean as long as you take as long as you can take you know as long as you can take you know um as long as you take um um as long as you take um a multiple of two of uh negative numbers a multiple of two of uh negative numbers you can just treat them as one you can just treat negative numbers as if they are as long as you take as long as you take uh i should take them in pairs a multiple a multiple of two right of two right this is like a further for the fact this is like a further for the fact that you uh that you uh that you're going to that you're going to that you're going to have to accept that you're going to have to accept right yes right yes but the fact you can just but the fact you can just treat negative numbers as if they're treat negative numbers as if they're positive as long as you take them in positive as long as you take them in models of two right and uh um and that's a really powerful thing so you can ignore the signs partially right and just treat the array as like a positive array and then if it's a positive way you're going to take them all right so you really just want to um search from the both ends right right so here's going to be my strategy count the total number of negative values right that's the first step and if the number is uh even just return if the number just determine uh which just you know just yeah just pick uh uh the one or two you know most sideway yeah most sideway most sideways are negative you know n1 you know n1 uh uh numbers and decide numbers and decide which which one which one and and and the trailing you know positive numbers uh uh to to remove you know to to uh to uh to to remove you know to to uh to give up right to give up give up right to give up yeah that's that's the strategy so yeah that's that's the strategy so i'm going to just say that right uh i'm going to just say that right uh let me just demonstrate what i mean by let me just demonstrate what i mean by saying that saying that i think i just found the solution at i think i just found the solution at this time hopefully it'll be quick but this time hopefully it'll be quick but uh uh let's just draw what i mean okay yeah what i mean is that um a list of numbers right a list of numbers right a list of numbers a list of numbers uh in the case in the case one if like uh in the case in the case one if like number is even you just multiply all of number is even you just multiply all of them and in the case that you know the them and in the case that you know the number of negative numbers is odd number of negative numbers is odd then maybe like one is here right like then maybe like one is here right like this is like this is like uh uh n1 n1 this is like negative right this is like negative right negative negative then maybe you have an n2 somewhere here it's a negative so you're going to take you're of course going to take all of them all of these inside right all of these in between you're just going to take them because you have um an even number of um negative numbers in between you can take them all and then you're going to decide whether you're going to ditch these or you're gonna ditch these right for this part it's positive this part is positive right and this is like you know yeah this is like money in the bank i'm just again gonna say it's money in the bank and mitb for money in the bank so it's something you're definitely going to take and then you're going to determine um whether to to throw up uh to this is a question this is a question um to decide um to decide you know and this could be decided by you know and this could be decided by uh uh uh by uh by by calculating let me just you know right let's just see let's just say that right let's just see let's just say that if you multiply them all this is gonna if you multiply them all this is gonna be be uh the union uh the union right right is it union is it union uh uh what what you know it's not sum right like you know it's not sum right like sigma means sums um sigma means sums um what is the what is the what is this what is this i guess what is the uh i guess what is the uh um sign for like all the products i'm just going to say p right this is p1 and this is p2 right the product of all of those if i uh uh uh uh well sorry i mean if the total number is well sorry i mean if the total number is odd that means we have odd that means we have you know you know uh odd uh odd number of number of negatives negatives within this within this right that means this right that means this within this part within this part so we just need one more negative number so we just need one more negative number which is to you know choose which one to which is to you know choose which one to take and take and choose and also take the uh choose and also take the uh uh the positives um you know just the uh the positives um you know just the trailing positives behind it trailing positives behind it uh so uh so which one to ditch which one to give up which one to ditch which one to give up we're gonna calculate we're gonna calculate um um which one's larger right like calculate which one's larger right like calculate p1 times p1 times uh uh minus n1 minus n1 and then versus and then versus p2 p2 times times minus n2 minus n2 and then you know it'll give up let give give up just keep keep the larger yep oops that's uh yep that's about it it's uh i guess a simple enough solution it's uh i guess a simple enough solution to implement to implement so now let's try to implement this and so now let's try to implement this and see if it works so now the first step is we're just going to count the total number of negative values right all right step one count the negatives um right for loop for k in range uh or let's say just k in um for num and nums right uh um if count plus count plus plus uh count plus equal to one right plus uh count plus equal to one right we're gonna just uh we're gonna just uh say net count right net count equal to say net count right net count equal to zero zero let's just say net count let's just say net count uh uh let's just say end neck right let's just say end neck right an egg right so this is how you're going to count the number of negatives and we're going to decide all right if yeah yeah if if an egg an egg is even is even just return just return the full full um the full full um full list full list right right just return the product with the full just return the product with the full list uh do we really want to return the product yes so if uh neg uh divided by two equal to y equal to zero is that how you do it like python mod right the percentage operator right the percentage operator by the modulo operator basics so 15 by the modulo operator basics so 15 modulo modulo 4 becomes 3 which makes sense 17 modulo 4 becomes 3 which makes sense 17 modulo 12 is 5 makes sense 12 is 5 makes sense so yeah that's what we wanted so yeah that's what we wanted if the modular is 0 right then we're just going to return how do you say you know python product of list how do you do that multiply all numbers in the list four different ways um wow we need a for loop maybe right yeah something like that for loop result that's one way of doing it numpy prod well we don't have numpy um there's a lambda function way of doing it okay i think we're not gonna do anything fancy so we're just gonna use and also and also maybe uh and also maybe uh maybe we can just maybe we can just also accumulate the product and also accumulate the product and let's not do that let's just say let's not do that let's just say um for product equals uh product uh let's say uh let's say initialize initialize product as one right initialize that product initialize that's one well maybe we should initialize it uh if that if that and we're going to do this for loop and we're going to do this for loop now we're going to return the product um right else else meaning if the number of negative is is odd then we're gonna decide then we're gonna decide um and we're gonna decide if pick the one or two most sideways pick the one or two most sideways negative numbers and decide which one to negative numbers and decide which one to give up give up right right right right so so [Music] [Music] right you're gonna have a left most negative right n1 leftmost negative number and n2 is the rightmost negative number um they could be the same value um they could be the same value if we only have if we only have right we're gonna say that okay right we're gonna say that okay and one and and two could and one and and two could be the same value be the same value if we have if we have only one negative value in the list which is okay because we're still gonna just give up uh um give up um you know either that or that right so it's not a special case it's generalizable so else find the left most negative and one and the right most negative i think i think we could have done that i think i think we could have done that in this first for loop as well right in this first for loop as well right so um if and neg equal to zero right so that means if if it's like the first one we're finding then you know n1 is going to be num num but hey we also want but hey we also want we also want the uh we also want the uh the index number right so the index number right so yes so actually we would like to you know plus equal to one we also want to plus equal to one we also want to you know you know find the indices right k find the indices right k go to zero this is like go to zero this is like index of index in the array index of index in the array in the list right in the list right um so this will happen whatsoever and one let's say k1 equals to k yeah right and then of course for the last for the last uh for the next for the last yeah no just uh uh uh mark the first index this um k2 equals to k as well you know be be will eventually mark will eventually mark the last the last negative negative index right index right we're just going to use one for loop we're just going to use one for loop well well don't you think that it's going to be easier if you just go for a loop and backwards yeah inefficient i know it's inefficient but let's just work out a solution here we already found them so it's k1 and k2 we already found them so it's k1 and k2 here here uh uh and decide which one to give up right by by decide which one to give up right by by comparing right so the leftmost negative and one is by k1 k2 so fine by k1 k2 so fine um um compare the product of of p1 times n1 negative and you know n2 negative n2 times p2 let's say let's say prod 1 is this prod 1 is this uh uh prod 2 is this and um leave the lesser one yeah or just say take larger one so prod one equals to uh what is p1 so because n1 is uh so it's going to be a for loop for k for k in range k1 k1 right so k1 is like right so k1 is like the index before the index before on the index before um on the index before um yeah the index of the first yeah the index of the first of the first uh of the first uh negative so negative so this these case will stand for all the this these case will stand for all the positive values in p1 positive values in p1 so um so um product right product right prop 1. i'm going to initialize prop 1 with 1 plot 2 equal to 1 as well we're gonna just initialize those plot one uh equals to prod one times uh nums of k right so that is going to be you know multiply in p1 in p1 and then of course you're gonna have to and then of course you're gonna have to uh n1 n1 so this is n1 right multiply right right you're going to do the same for you're going to do the same for um for um for p2 so so now this is going to be k2 um wait um that is if we still have anything so range k2 plus 1 so range k2 plus 1 um um if it exists at all like if they exist at all right uh uh um k2 plus one k2 plus one all the way to the end but maybe k2 is the last index possible it's possible right so maybe this is out of the uh um you so maybe this is out of the uh um you know yeah i could know yeah i could how do we express this like right maybe we just use an if condition if uh if k2 is less than um lengths of minus 1 minus 1 meaning there's still some positive meaning there's still some positive values left there's still positive numbers then then um we're going to do range k k2 plus 1 yeah so let's say n equals to yeah so let's say n equals to length of nums and this is going to be then it's going to be then it's going to be that to n right the range of that that to n right the range of that and then we're gonna just multiply all and then we're gonna just multiply all possible values in p2 possible values in p2 and then of course we're going to and then of course we're going to multiply it by minus n2 right multiply it by minus n2 right that's it that's it well if there's an if right we only actually multiply them in p2 um if not it'll just be one if not it'll just be one like we initialized yeah if there are if there if there are still values in there we'll multiply all of them otherwise we don't and then product two is like that and now we have plot one and plot two now we have plot one and plot two right so we're going to compare uh if prod one is greater than right then we're going to take um um mitb money in the bank right we're going to compute money in uh compute money in the bank actually what that means is that take all take all um you know take um you know take the product the product between between num zero and nums uh let's say it'll be k2 [Music] right 0 and k2 minus 1 yeah so we're gonna do a for loop so we're gonna do a for loop for num in nums for num in nums uh product product equals to equals to product times product times num num right and we're going to return product else we're going to take the product between nums um if if the if n2 times p2 wins we're going to ditch p1n1 we're going to take values from k1 plus 1 all the way to the end yeah siren going on outside um k1 plus 1 the last and minus one so the last and minus one so um we're gonna do uh nums in um uh all the way to the end right and return product so i think we got it but maybe we have not taken into account like the small um the special cases like just one value in there find some test cases find some test cases like that but now like that but now for now let me just for now let me just copy paste and start to use the syntax for the solution template what is the function name max product what is the function name max product all right so let's just run it and see all right so let's just run it and see what we've got what we've got whoops um we only got six why is that well in this case we're going to put a debugger on because in this case you know n1 and n2 are the k1 and k2 are supposed to be the same k1 and k2 are supposed to be the same thing and we we're going to see if thing and we we're going to see if that's the case that's the case okay okay k1 and k2 k1 and k2 should all be like one but uh now now let's see let's see k1 is k1 is 2 k2 is 2 right they're they're both 2 2 k2 is 2 right they're they're both 2 right that's that's correct right that's that's correct so if they're both too so if they're both too the next break point we're going to the next break point we're going to place a neg is one right so because neg is uh a neg is one right so because neg is uh is is odd so we're going to go into the is is odd so we're going to go into the else condition else condition and then we're going to compute prod 1 and plot 2 and what do you think is plot 1 well plot 1 is going to be all of these 6 by 2 so it's going to be 6 by 2 so it's going to be plus 2 is going to be 2 by 4 it's 8 right plot 1 should be 12 plus 2 should be let's just yeah put this big point at line 36 and yeah put this big point at line 36 and see if plot 1 is 12 and plot 2 is see if plot 1 is 12 and plot 2 is indeed 8 that's what i want to see indeed 8 that's what i want to see prod 1 prod 1 12 part 2 8 that's exactly right and that's what we want to see right and therefore and therefore we should uh oh hold on we should take the product um in this then we're gonna take all of these and then we're gonna take all of these and multiply by the money in the bank multiply by the money in the bank or you know or you know um this number all the way up to and two and two right so it'll be right so it'll be uh uh zero all the way to k2 minus one all right and k2 minus one because k2 is k2 is 2 so k2 minus 1 is going to be 1 right for nums and nums for nums and nums uh k2 minus 1 um product equals to product times num so the first one is going to oh sh i i think it should be num instead of numbs anyway so that's a typo there um num and nums right so that's a quick fix that we should oh we should get hey but why is it two we're getting less um let's just uh yes product yeah we're still going to need let's let's just try you know maybe this you know a simple you know a simple syntax right i think maybe let's say four five six right and four you know there's ace numbers numbers for for number and numbers number and numbers right print right print print number yeah it is going to print everything all right what about let's say numbers in numbers all of that two oh right right you know for these kind of like indexing add one always add one to the last right right so you add one to the last so this becomes that right because you need to add one and this one here i think this one is fine yep yep that's correct that's correct the next test case uh this one should the next test case uh this one should return zero return zero it's kind of like a special test case it's kind of like a special test case right right so this so this is gonna be some kind of a special test is gonna be some kind of a special test case it should give you zero yep all right it should give you zero yep all right so so how about let's just test ourselves the how about let's just test ourselves the special case when there's only just one special case when there's only just one value in there value in there if there's just one zero in there if there's just one zero in there we should also expect zero right let's see if it actually gets zero yep um what if we only have like a one value of like minus two right well that's the thing like if we have a minus value there yeah this is going to be a problem yeah this is going to be a problem because you have to take into account because you have to take into account if there's only just one negative value if there's only just one negative value right right what if there's just one negative value what if there's just one negative value what do you do um so now we have counted that there's like odd numbers of negative because there's only one well the easiest way you know to do everything is if you can just calculate this n here and then if n equal to one nums and that's it and that's it right right that way that way yep yep i think this is a more complete answer i think this is a more complete answer now and let's submit it for test examples test examples correct correct let's submit okay let's submit okay whoa whoa zero two and we're expecting two wow zero two and we're expecting two wow okay okay new test case to be looked at right i see 0 shouldn't be treated as right right right right right right so we need to take a lesson here so we need to take a lesson here yeah take a listen zeros shouldn't be treated it ain't that you know it ain't that you know ain't that obvious ain't that obvious so zeros so zeros are are like like resetters right right i wasn't actually you know i wasn't actually taking into account zeros in any of these right so we were just counting negatives yeah so negative and zeros they they yeah so negative and zeros they they play a very different role play a very different role um in um in multiplication so multiplication so uh do i want zeros i mean we want positive numbers so we don't want zeros right so this is gonna be our our um right so this is gonna be our our um our strategy you know our strategy you know avoid uh hitting avoid uh hitting zeros zeros at all costs the only the only time when we actually take a zero everything else everything else are negative values is negative everything else is negative yeah the only chance the only time when we actually take a zero use of everything else is negative so then what do we do well so zeros are like resetters if you find like a zero uh somewhere in the array you don't run across it you your heart so yeah when we run into zeros in the array in the list so they're like so they're like spacers that you know or they're like spacers that you know or they're like you know you know those um those um compartment compartment doors right compartment compartment doors right uh uh that that shuts the whole array into different uh compartments zeros zeros are like compartment doors are like compartment doors that that isolates the full list into compartments compartments right inner compartments that right inner compartments that yeah the isolate um yeah the isolate um the full list into compartments the full list into compartments that's true that's true and any number i'm just a braid the largest product right so so i think so i think we have not really worried about zeros right so let's just go ahead let's say let's say you know everything here uh uh was not was not considered in this page zeros were not considered in this page on this page so we're gonna dedicate a new page for zeros this page this page address address the zeros the zeros yeah yeah and the zeros are like compartment doors and the zeros are like compartment doors they're like isolators right compartment they're like isolators right compartment doors doors we're going to just take them you know zeros the compartment doors right so if you want to you know just kind of like draw a comic to show what they yeah if you want to just draw a comic to yeah if you want to just draw a comic to show what they are show what they are and use three pixels wow my pen is again throwing a tantrum wow my pen is again throwing a tantrum at me so in this case i'm just going to use my so for example if this is your list right and you're gonna have like zeros at these locations like zero uh zero and zero then they're like compartment doors and you know this is like compartment one compartment two compartment three compartment four so these are your sub problems right c1 c2 c3 c4 uh it shuts them into compartments and then you're going to have to worry about right so right so actually know what we can still reuse actually know what we can still reuse this this but this is like but this is like this is not max product this is not max product this is like this is like max product without zeros max product without zeros and zero free right but we're still gonna have to um you know you know that address this general zero um that address this general zero um problem problem so what we're gonna do is we're gonna so what we're gonna do is we're gonna find all the find all the zeros zeros you know doors you know doors compartment compartment doors doors ryan wagner and our strategy is like ryan wagner and our strategy is like so yeah we're going to just basically so yeah we're going to just basically say our strategy here okay say our strategy here okay strategy find all zeros i'll identify um you know and then separate then split the full array full list into a separate compartment then um then um then calculate the max then calculate the max uh max uh max product array within each within each and take and take the max the max yeah so this is my strategy here yeah so this is my strategy here uh first we find all zeros then we can uh first we find all zeros then we can split them into separate compartment split them into separate compartment sub-lists sub-lists yeah split the original list into uh sub-lists divided by the zeros right and then compute the maximum of the sub list product sub list max products right so that's how you do it um final the zeros well how do you do that you're just going to use a for loop search right um num num and and nums nums right or actually just to k for k in let's say n equals to let's say n equals to length of nums length of nums right for k in range right for k in range of of n n we're going to we're going to um um see if see if nums of k nums of k well actually this is not gonna be very well actually this is not gonna be very efficient you know why efficient you know why because if you look up lists you're because if you look up lists you're gonna have to scan the list and it's gonna have to scan the list and it's gonna be slow gonna be slow um so but it's okay i mean we're going to optimize it later if num list k equal to zero if we found a zero right uh we're going to add that to we're gonna split how about let's split we're gonna split how about let's split them in here them in here uh now uh now um we can append a list right we can append a list right um zero list i'm gonna do that and uh zero list append yeah so i found we found all the zeros yeah so i found we found all the zeros here here in the zeros list but if you know how to check if it's empty uh python check list empty how to check um if list is empty makes sense makes sense if length of if length of zeros list zeros list equals to zero equals to zero we're just going to return um self dot max product zero free of nums because we know it's zero free um um we're gonna divide or else we're going to split the original list into sub lists divided by so for each so for each um for each zero in zeros list for each of the zero and zeros list um for each of the zero and zeros list um it is going to be it is going to be how do we how do we chop it how do we how do we how do we chop it how do we chop this uh chop this uh list list so let's just draw that so let's just draw that so this is like the first one right so this is like the first one right we're going to have a zeros list let's say it contains what here k1 k2 k3 uh that's the case here right because this is gonna be well no let's forget it well no let's forget it um this is um this is k1 this is k2 and this is k3 okay and these are our zeros and so the way we're gonna split all these lists the first list you know the first list sub um sublist one of course is going to be uh from the original nums of uh from zero from you know the beginning all the way to k1 minus 1 right but we're gonna just use k1 because that's how this column works uh it's only going to count up to k1 yeah yeah uh uh right and uh after we've done that yeah we're gonna update yeah we're gonna update we're gonna update like the we're gonna update like the the beginning yeah the beginning yeah and and start right and start we're going to start right and start we're going to update update and start and start yeah we're going to do like an instart first aw0 of course that's you know initializing and then k1 and then we're gonna update and start this now it's becoming k one plus one that's the new start right and then the second list will be n start all the way to k2 right and then we're gonna again update this in start to be k2 plus 1 and then the next sub list will be and start will be k3 right right 2 sub list 3 um okay three equal plus one and uh if we okay three equal plus one and uh if we do have a sub list four do have a sub list four there there um it'll be it'll be you know to the end i mean you know to the end i mean something like that um that is if you know if we still have something yeah let's say if you know k3 is less than it only happens if if k three is less it only happens if if k three is less than n minus one than n minus one then we're going to have then we're going to have uh this right because there's a chance that you know this zero is the last one in the the original list so here we go we have a uh an iterator yep so um for zeros and zeros list we're gonna see and start yeah we're gonna end start equal to zero you know initial uh sublist start index in original nums list right um so for that sub list equal to um and start all the way to and start all the way to uh zero right uh zero right because yeah that's how you do it because yeah that's how you do it um to the first zero um there's an if condition there's an if condition if if zero zero is less than n minus one is less than n minus one right right if we're still not at the end of it if we're still not at the end of it we're gonna do this we're gonna do this and we're gonna do this and we're gonna and we're gonna do this and we're gonna um um send the sub list what to to calculate that right um bright um sub list max sub list max append append right we're gonna append that right we're gonna append that and uh selpus max we're gonna say it's that uh container for max max products i'm going to append that right so in the for loop like that we're gonna we have implemented this if condition right so this helps to define you know if if we're hitting the end of it and so we're going to do this until k1 this until k2 and then we're going to update and start and then we're going to update and start after we've done that uh update and start how do we update and start well end start equals to zero plus one um shall we actually use a while loop because well since we have three of them this is only since we have three of them this is only going to create three going to create three sub arrays sub arrays sub yes a brace and it's not going to sub yes a brace and it's not going to work on the number four right so this number four is something you know all these are like this is going to be like a for loop for loop uh and this is like the the last treatment right the special treatment and for the for loop we really don't and for the for loop we really don't need to worry about um need to worry about um this because we're just taking this because we're just taking the sub array before these the sub array before these zeros zeros so right and you know after all of that you know see if there are still numbers after the last numbers after the last zero uh if zero last if this is like less than if this is like less than n minus one n minus one that means yeah we do still have that means yeah we do still have some array there some array there then we're gonna do then we're gonna do another sub list another sub list equals to you know and start and start which is going to be 0 minus 1 uh plus 1 all the way to the end right and then we're going to still do this sublist append and then we're gonna compute the maximum all right i think that's all the sub lists uh we're gonna compute the maximum of the sub list max uh product so we're gonna return actually the max sublist max sublist max right right yeah so this is a prototype i don't expect it to fully work all right so there's something here subscriptable oh subscriptable oh okay because there's only one zero okay because there's only one zero so so i guess that's why it i guess that's why it throws a tantrum at me actually we're at the last zero right oh zeros uh yeah zeros you should you should say zeros name zeros is not defined okay okay zeros list okay okay that worked what about that worked what about the rest the rest six well this went wrong wait expected six this is like weird expect six right this is like weird expect six right um let's see um let's see expect zero minus two 0 -1 let's see let's see um well this one actually produced minus um well this one actually produced minus one wow okay so these two are problematic we have two problematic cases but i think i know what's going on because we said that excuse me if you remember we said that um that we uh when we actually take a zero that we uh when we actually take a zero is if everything else is negative is if everything else is negative we have not implemented that right we have not implemented that right um um if everything else is negative if everything else is negative which is the case here then we're going which is the case here then we're going to to take a zero so where do we put that take a zero so where do we put that special case special case if like if like everything else is negative um right because we don't really care about the because we don't really care about the value of the sub lists in here we only value of the sub lists in here we only care about it at the last moment care about it at the last moment right right so if let's say it um are right right can we still return negative somehow can we still return negative somehow yeah we could still return negative yeah we could still return negative somehow somehow um if all the sub-arrays um if all the sub-arrays are negative are negative we rather we rather just just return return zero yeah i'll just calculate um result you know you know sub list sub list result if sublist um is less than zero return else return this this is probably going to fix one of those problems but then what if we only have one zero if we only have one zero in there yeah so what happens if we only have one um um again we want to add this in there again we want to add this in there right if n equals to one we just you know return yep all right so i think uh yep all right so i think uh we just did a hot fix for that singular we just did a hot fix for that singular case case and now six zero zero minus two two and now six zero zero minus two two um um looks alright let's just submit it to looks alright let's just submit it to leeco to see if it now leeco to see if it now satisfies the problem definition simple test cases were correct but we still got our own answer here so 0 minus two zero we should expect a zero so so there's something that we're still not there's something that we're still not considering correctly considering correctly oops what what did we just do zero minus two zero um for this one we're expecting zero we are getting huh but hey i mean um shouldn't we in this case i mean return zero because in this case the sub list result is like less than uh all of them are like less than zero and you should just return zero right okay restart the kernel and after that we start the debugger and we set the breakpoint at um here want to know what are the sub list results because according to this the sub list results should be like a minus 2 or something wait oh yeah did it go there yeah sub list max and um it's got a and um it's got a one and a minus two wow one and a minus two wow how come we have two sub lists um right so lists okay this is where we for zero sub list because the first zero is at zero so it's going to be numbs um zero to zero okay it's going to be numbs zero to zero right just because yeah right just because yeah the in start is zero right and then the the in start is zero right and then the first zero first zero because the zeros list is going to be because the zeros list is going to be zero and uh 0 and 2 right zero and uh 0 and 2 right yeah so this is going to be 0 0 yeah so this is going to be 0 0 and what happens and what happens with nums 0 to 0 with nums 0 to 0 i don't know we'll find out like yeah what is going to be numbers uh 0 to 0 let's try that empty okay so if it's empty max product zero free with an empty sub max product zero free with an empty sub list list so what do we so what do we do do with empty sublist yeah we're going to return something yeah we're going to return something called a uh and that is totally wrong so we're gonna have to account for cases where so what to do if so what to do if the max product of that is like the max product of that is like we shouldn't be sending empty we shouldn't be sending empty empty lists to uh empty lists to uh to it here to it here right right because by design we want to make sure because by design we want to make sure that you know that you know this zero the first induction of the this zero the first induction of the zero zero um is not zero because if the first element is zero right we want to make sure that the first one is not zero uh if right if uh if k y equal to zero just ignore it if k k one equal to zero just ignore it if k k one equal to zero just ignore it so how do we ignore it well zero's list let's say yeah we can afford if zero is not equal to zero we can afford this right because there won't be like a huge number of zeros so we can afford yep uh but actually even for um even for this yeah we're still gonna update and start in that case yeah so it's just that you know we don't make a sub list for the first if 0 equals to 0 if the first zero is at index zero we don't do that yeah whoa what is wrong um um a column right so that is okay and let's try everything else expected minus two zero zero yep now this seems correct uh let's just submit it again to leak let's just directly submit it okay let's just directly submit it okay accept it um great and you know accept it um great and you know our runtime actually beats most people our runtime actually beats most people great great so that means our algorithm great great so that means our algorithm really is is pretty really is is pretty it's pretty neat and efficient and it's pretty neat and efficient and memory usage is is fine because i think memory usage is is fine because i think we could still improve by we could still improve by you know um removing some of the unnecessary variables i guess we can improve that still but i mean this is not bad right beats 99 let's uh submit it again whoops um it only beats 19 and now this beats uh and now this beats uh 76 so it's i guess it's like above 76 so it's i guess it's like above average average so all right um so all right um it turned out today's coding is pretty it turned out today's coding is pretty smooth and i'm going to smooth and i'm going to so before i wrap it up so before i wrap it up let's take a look again at what we have let's take a look again at what we have so we had so we had basically basically several key insights into the problem several key insights into the problem the first insight is that you know signs the first insight is that you know signs matter and the only thing that can hurt the product value is the minus sign so we need to be careful how we deal with and uh and uh uh uh the only thing we need to differentiate the only thing we need to differentiate is whether there's like odd numbers of is whether there's like odd numbers of amount of signs or amount of signs or negative signs or uh or even numbers of negative signs or uh or even numbers of negative signs negative signs so for the so for the for the odd case for the odd case for the even case we just take them all for the even case we just take them all for the even case for the even case um for the for the even case we take um for the for the even case we take them off with the odd case them off with the odd case we're just gonna have to make a choice we're just gonna have to make a choice between between taking the left most negative sign or taking the left most negative sign or taking the right most negative sign taking the right most negative sign we're of course going to take everything we're of course going to take everything in between as well in between as well and this discussion is you know without and this discussion is you know without the consideration of zeros the consideration of zeros so then so then we went on and we went on and took the consideration took the consideration of zeros of zeros so zeros so zeros for multiplication tasks they're like for multiplication tasks they're like compartment doors you know compartment doors you know they shut the they shut the list into separate compartments list into separate compartments and that's what we did so we had a and that's what we did so we had a more higher super level higher level more higher super level higher level function that function that identifies these compartments and then identifies these compartments and then we're going to use we're going to use another another subroutine or another function to subroutine or another function to compute the max compute the max within each of those compartments and within each of those compartments and then come up with the the maximum of then come up with the the maximum of them them and that is it guys that's our algorithm and that is it guys that's our algorithm and it and it worked beautifully and it and it worked beautifully um um we got accepted uh and then we got accepted uh and then an internet above average code an internet above average code um so that's it um so that's it uh lastly let's take a look at some of uh lastly let's take a look at some of the solutions the solutions there there there's of course the brute force there's of course the brute force iterate everything your complexity to be iterate everything your complexity to be high oh by the way what what is our high oh by the way what what is our complexity complexity i mean i mean for our problem um for our problem um our complexity right uh we probably have in terms of uh time complexity um oh if uh and because we didn't have anything that a for loop inside a for loop uh with a for loop inside a for loop uh with respect to n so we probably only has respect to n so we probably only has that and in terms of in terms of space that and in terms of in terms of space complexity complexity are we remembering anything like extra complicated um well we do have for loops right but for loop is not a memory uh we are sending we are sending the sub array the sub array into functions so i don't know it's somewhere between of of one and o of n i guess somewhere between all of right right yes something between there yes something between there i'm not quite sure but yeah i'm not quite sure but yeah now this complexity now this complexity yeah the computation is pretty heavy yeah the computation is pretty heavy because if you use brute force because if you use brute force you're gonna have to sweep you're gonna have to sweep the beginning and the end dynamic programming yeah two things can disrupt you combined uh zero is negative numbers right zeros will reset negative numbers a little bit tricky single right so you're going to have to think about you're going to use dynamic programming you're going to use dynamic programming to compute your your thing to compute your your thing and it's on and one so actually um i and it's on and one so actually um i think we could have tried the dynamic think we could have tried the dynamic programming approach here programming approach here using your using this using your using this uh uh using this intuition here using this intuition here but but ours is not bad so i'm gonna just sit on ours is not bad so i'm gonna just sit on it and it and uh if you're interested you can you can uh if you're interested you can you can take a look at the solution here take a look at the solution here uh uh for the dynamic programming for the dynamic programming solution solution right it's a python3 dynamic programming solution and then wow okay you can find people's solution wow okay you can find people's solution there there this guy's face show up a lot i guess this guy's face show up a lot i guess he's really he's really cool he's really he's really cool um right and you can you can read some of the codes in there more simple wow anyways there are multiple ways you can anyways there are multiple ways you can attack this problem um attack this problem um and i just did it in my intuition and i just did it in my intuition um um let me know if you found you know my let me know if you found you know my code could be improved in any certain code could be improved in any certain ways ways or or if you found like a smarter trick if you found like a smarter trick let me know in the comments let me know in the comments and uh thanks for staying along with me and uh thanks for staying along with me and i'll see you in and i'll see you in the next video oh wait hold on um the next video oh wait hold on um today's summary i think we just uh today's summary i think we just uh walked through our summary walked through our summary so all right that's it i'll see you in so all right that's it i'll see you in the next video | 2024-03-21 13:13:45 | 152 | 1 Leetcode 1 Day 152 Maximum Product Subarray |
|
ydh8I8RzcqI | let's solve 1925 count Square some triplets so the question says that you triplets so the question says that you need to find all Pythagoras need to find all Pythagoras triplets triplets until the number n so say for example of until the number n so say for example of the N is 10 okay n is equal to the N is 10 okay n is equal to 10 so I need to find all Pythagoras 10 so I need to find all Pythagoras triplets under 10 so triplets under 10 so the first one would be 3 4 and the first one would be 3 4 and five where three square of 3 + square of five where three square of 3 + square of 4 is equal to square 4 is equal to square 5 right 5 right similarly there would be similarly there would be 6 6 8 and 8 and 10 we just double all the numbers and it 10 we just double all the numbers and it also becomes Pythagoras triplet which is also becomes Pythagoras triplet which is 66 66 36 88 are 64 36 + 64 is equal to 10 10 36 88 are 64 36 + 64 is equal to 10 10 are are 100 100 so that is it since n is 10 this is the so that is it since n is 10 this is the most we can get now let's look at some most we can get now let's look at some other pyus triet under other pyus triet under 10 then there 10 then there is variation of this is variation of this so three 4 5 4 3 and 5 is so three 4 5 4 3 and 5 is also a Pythagoras TR similarly 68 9 8 6 also a Pythagoras TR similarly 68 9 8 6 and 9 is also 8 6 and 10 is also and 9 is also 8 6 and 10 is also Pythagoras Pythagoras triplet right so we just swap these two triplet right so we just swap these two numbers and we get another Pythagoras numbers and we get another Pythagoras triplet similarly there triplet similarly there is so that's it so there are four pyus is so that's it so there are four pyus triet under okay to find triet under okay to find out Pythagoras tripletes up to n that is out Pythagoras tripletes up to n that is a interesting method say my pyas trip is a interesting method say my pyas trip is say anything any number say 10 or 15 or say anything any number say 10 or 15 or anything right so what will I do is I'll anything right so what will I do is I'll go for all go for all the numbers the numbers between 1 and between 1 and 15 15 okay and take it as X okay and I'll take okay and take it as X okay and I'll take all the numbers all the numbers from 1 and from 1 and x and take it as Y and I'll just check x and take it as Y and I'll just check if first of all I check if X and Y both if first of all I check if X and Y both are are even then I can ignore it if X and Y even then I can ignore it if X and Y both are odd I can ignore it and if gcd both are odd I can ignore it and if gcd of of X and Y is greater than one then I of of X and Y is greater than one then I can ignore it okay can ignore it okay well uh so if gcd of X and Y is greater well uh so if gcd of X and Y is greater than than one it cannot be a pyus triet but if one it cannot be a pyus triet but if it's even numbers or both even it's even numbers or both even numbers or both are odd numbers then numbers or both are odd numbers then also we can avoid also we can avoid it and finally I need to check so if can it and finally I need to check so if can find Pythagoras triet by doing find Pythagoras triet by doing x² that is X into X Plus X Y into Y and 2 x y and x into x - Y into y so this gives us 3 numbers which are Pythagoras triet okay that's a method of figuring out that's one way of figuring out Pythagoras trib so we are going to use this method logic and as we have seen in the example that once we have a Pythagoras triplet we just need to add the same numbers in it and we get another Pythagoras Tri in like in case of 3 4 and 5 double of 3 + 3 6 4 + 4 8 5 + 5 10 9 uh 9 uh 12 and 15 are another Pythor triplate 12 and 15 are another Pythor triplate and so on right so you just keep adding and so on right so you just keep adding the same numbers once you find one the same numbers once you find one Pythagoras triet Pythagoras triet until the third value is less than or until the third value is less than or equal to n which is provided to us okay equal to n which is provided to us okay let's code it let's code it up so what I'll do is I'll first of all up so what I'll do is I'll first of all what I need to return is I need to what I need to return is I need to return the count how many pyas tripletes return the count how many pyas tripletes are there so I'll maintain a variable are there so I'll maintain a variable count initialize it to count initialize it to zero then I'll do zero then I'll do for X in for X in range 1A range 1A n + 1 n + 1 for y in for y in range 1 comma X okay so in that case I can even be be two right because one will never be an two right because one will never be an option okay and then I can check I can option okay and then I can check I can do a three do the three checks do a three do the three checks if odd and Y is OD okay even even and Y is also and Y is also even even or gcd or gcd of X comma of X comma Y is greater than Y is greater than one then don't do anything just continue one then don't do anything just continue skip this Loop and continue to the next skip this Loop and continue to the next now we are calculating gcd here so I now we are calculating gcd here so I need to create a function named gcd so I need to create a function named gcd so I can do that can do that here gcd it takes an A and a while a while a a comma B is equal a a comma B is equal to B comma a person to B comma a person B and finally return B right that will give me the gcd that's the one way of calculating um gcd and then if it pass if it doesn't pass through any of these conditions then it continues to the next line and there we see we calculate the third value only see we calculate the third value only this we need to check the largest value this we need to check the largest value among the triplet if it is less than n among the triplet if it is less than n less than or equal to n so the third less than or equal to n so the third value would be X into X + Y into if if x if to sorry the spelling is incorrect third third is greater third is greater than n third 1 1 and thir is greater than n then we return C right and after this what will do us this condition basically says that if thir + x into X which will give us the this entire oh sorry not third if Y is 1 and X n then return X then we'll check if Y is = to 1 and thir is greater than n in that case I'll return C and if not then I'll out more SE so I'll while her I'll basically take while her I'll basically take third into a new variable say third into a new variable say t and check if T is less than n t and check if T is less than n continue okay and in that case I continue okay and in that case I to add two count to C because both to add two count to C because both variations will count if it is 3 4 5 so variations will count if it is 3 4 5 so 3 and four and five this variation and 3 and four and five this variation and four and three and five so two four and three and five so two variations will count so I add variations will count so I add those and then I'll those and then I'll increment T by3 so it will check for first time it will check three four and five next it will check 6 8 and 10 next it to check and and so on of 9 12 and 15 right so as soon as it crosses next will go on to 12 15 and 20 but since 20 is great than n which is 15 it will break the loop okay so once it breaks the loop I do not have do anything I just continue okay finally return slight error in this calculation return slight error in this calculation of gcd it will be while B and I'll of gcd it will be while B and I'll return a so while B because I'm reducing return a so while B because I'm reducing B at a faster rate than B at a faster rate than e but this is not C this is e but this is not C this is Count this is Count this is count count and this is and this is Count slight mistake here this will be T Count slight mistake here this will be T less than or equal to n let's run this and that worked let's it and that work too | 2024-03-25 13:14:48 | 1,925 | Leetcode 1925. Count Square Sum Triples |
|
GXGr8CUwkHw | lead code practice time so two goals the first one is to see first one is to see how to solve this problem and then we how to solve this problem and then we are going to put some code here are going to put some code here and the second one is to see and the second one is to see how they behave during every interview how they behave during every interview suppose this is some problem suppose this is some problem happening in the real interview so let's happening in the real interview so let's get started get started so the first one is the first step so the first one is the first step in the interview is always to try to in the interview is always to try to fully understand the problem fully understand the problem if there is anything uh unclear please if there is anything uh unclear please bring bring the question to the interviewer and at the question to the interviewer and at the same time think about the ash cases the same time think about the ash cases so let's take a look so copy list with so let's take a look so copy list with random pointer random pointer a linked list is given such that each a linked list is given such that each node contains an node contains an additional random pointer which could additional random pointer which could point to any node in the point to any node in the list or none all right so it has two list or none all right so it has two things things the next pointer and the random pointer the next pointer and the random pointer okay so return okay so return deep copy of the list the link list is deep copy of the list the link list is represented represented in the input or output as a list of n in the input or output as a list of n nodes so each node is represented as a nodes so each node is represented as a pair of pair of um of okay so each node is represented as a pair of value random index square while it is an integer representing no doubt value a random index is the index the index of the node where random pointer points to or none if it doesn't point to any node all right so let's see um example something like this okay so i think i kind of understand i pretty much understand what is happening here so let's see node value is between active ten thousand to ten thousand and no dot random is none or pointing to a node in the linked list so number of nodes will not exceed 1 000 okay sounds fair so let's see how to solve so how to solve this problem one thing i so how to solve this problem one thing i can think about is can think about is uh so we so the first so we have uh so we so the first so we have so we will have uh two pass so we will have uh two pass so the first pass is to so the first pass is to so so we are going to go through the so so we are going to go through the linked list linked list and do a copy of each of them and do a copy of each of them and get the linked list instead of and get the linked list instead of setting the random setting the random and at the same time we are going to and at the same time we are going to have a hash map from the have a hash map from the from the original node to the to the from the original node to the to the copy node copy node and then for the second pass we are and then for the second pass we are going to set the going to set the the random index based on the hashmap the random index based on the hashmap so that's my thinking so this one the so that's my thinking so this one the runtime is going to be all of runtime is going to be all of n so space y is it's also going to be n so space y is it's also going to be olefin olefin as well so n is the number of the nodes as well so n is the number of the nodes within the linked list within the linked list uh that's the that's this solution uh that's the that's this solution um so let's see i think it's the best um so let's see i think it's the best regarding the runtime but let's see if regarding the runtime but let's see if we can save some space we can save some space so i'll say um so we need we really at least we need to find the relationship between the original node and the copied node so i'll say if the list is modifiable we could tweak the original linked list we could tweak the original linked list so for example so for example we have this linked list and we have the we have this linked list and we have the copy links that link list copy links that link list we just set the copied we just set the copied linked list to the next node so like we linked list to the next node so like we insert a node here insert a node here like which is the copy node of seven like which is the copy node of seven and similarly we do a copy node as 13 and similarly we do a copy node as 13 like sometimes like like this so this is like sometimes like like this so this is the first step the first step and then the second step is we try to and then the second step is we try to uh we try to set the random node uh we try to set the random node for the for the new created nodes for the for the new created nodes so because so because node dot random pointing to so for node dot random pointing to so for example for this one example for this one the red red node seven for node seven the red red node seven for node seven the random point into one the random point into one so for sure that the next node the so for sure that the next node the random pointer is going to be the next random pointer is going to be the next node of this node node of this node so that so in this case we are going to so that so in this case we are going to reset the random node there reset the random node there this is the second pass and the third this is the second pass and the third pass we are going to detach pass we are going to detach the new nodes from the original link the new nodes from the original link list list and form a shiny new link list there and form a shiny new link list there so that's so for this one it's gonna so that's so for this one it's gonna need need um a one regarding the space um a one regarding the space space um yeah so but it really depends space um yeah so but it really depends you need to ask your interior if the the you need to ask your interior if the the link list is link list is the input is modifiable or not the input is modifiable or not so let's assume is not modifiable so let's assume is not modifiable because that's because that's easier to implement and let's do some coding work so the correctness of the code and the readability of the code and also the speed of the code so you can discuss with your interior whether it's modifiable or not so i would say there are two paths if the inheritor wants to give you some more difficulty of course he is going to say okay this is modifiable and go ahead to implement the space-saving solution but let's just go with the hashmap solution so for this one you have okay so let's see if if it's gonna be empty so it's so that it doesn't say that the head could be empty okay so i would say that would be the last case so if hat is equal to a non-pointer then we just return a none pointer for it otherwise we have a hash map from node to node so this is i'll say node map as a new hash map okay and um so let's say editor node it here is equal to head well uh is not equal to none we are going to say all right so um so node so node ether dot value and we ether dot value and we set uh set uh is equal to so we first initialize it um but we need to set so what if we don't set the next node so what if we don't set the next node here but instead we set the node here but instead we set the node map in the next pass so i will say map in the next pass so i will say node map.put this is the editor and the copy and next time it raises you could have again editor is not equal to none um we are going to say okay um node map dot uh now the copy is equal to node not talking to uh either all right uh this should be enter is equal to next and then we are going to say okay next is equal to node so know the map dot get so know the map dot get entered on next copy dot entered on next copy dot uh random uh random is equal to node map docket ether dot them okay so that finishes pretty much everything about copy notemap.gethead notemap.gethead this one it should have entered equal to this one it should have entered equal to eight or down next eight or down next okay so copy random okay so copy random list node if hat is equal to none they list node if hat is equal to none they return none return none so the next step after you're done with so the next step after you're done with coding the next step is about testing coding the next step is about testing so testing you go through time simple so testing you go through time simple task case to explain how this piece is task case to explain how this piece is going to work and going to work and at the same time do some sending at the same time do some sending checking the logic checking the logic and um if everything goes well then you and um if everything goes well then you you can mention that you want to set up you can mention that you want to set up some other test cases some other test cases to uh make sure it has good enough test to uh make sure it has good enough test coverage coverage so let's take a look at this one we have so let's take a look at this one we have first of all we initialize the node map first of all we initialize the node map and the unit is we do the one pass and the unit is we do the one pass through the list through the list and every time we copy the the node and every time we copy the the node so first of all we copy seven put it so first of all we copy seven put it put the original node and the copy node put the original node and the copy node into the map into the map and it is equal to the next one which is and it is equal to the next one which is 13 13 similarly we are going to copy 13 similarly we are going to copy 13 um and at the next time um and at the next time we will have we will we are doing we will have we will we are doing another pass another pass and um well it is not and um well it is not none we get a copy of the current none we get a copy of the current node he said okay next node he said okay next point next node points to one point next node points to one and based on the hashmap we have the new and based on the hashmap we have the new copy of the one and we set copy of the one and we set it to we set the it to we set the the copy of seven next pointer of the the copy of seven next pointer of the copy seven copy seven to pointing to the copy one similarly we to pointing to the copy one similarly we set the set the random pointer all right so i think it random pointer all right so i think it looks good to me let's give it a shot looks good to me let's give it a shot okay it looks good all right so okay it looks good all right so everything looks good uh like i said everything looks good uh like i said there is another solution there is another solution oh one solution but you need to do a oh one solution but you need to do a separate pass separate pass like the third pass on the linked list like the third pass on the linked list but i'm just going not i'm just leaving but i'm just going not i'm just leaving it for you to implement it for you to implement so thanks for your time watching it if so thanks for your time watching it if you find this video a bit helpful please you find this video a bit helpful please uh uh subscribe to this channel um i'll see subscribe to this channel um i'll see you next time thanks for watching | 2024-03-21 12:21:13 | 138 | Microsoft Coding Interview Question | Leetcode 138 | Copy List with Random Pointer |
|
EV8uN-oDUQM | hey hey everybody this is larry this is day eight of the march lead code daily day eight of the march lead code daily challenge 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 prom what you think about today's prom remove panoramic subsequence okay given remove panoramic subsequence okay given only a's and b's could remove only a's and b's could remove one parameter subsequence from s we turn one parameter subsequence from s we turn the minimum steps to make it the minimum steps to make it empty okay n is equal to a thousand so okay so my intuition here uh and i'm solving this live so if it's a little bit slow fast forward or whatever you need to do i feel like i always have to remind people to do it because a lot of people are just looking for just a solution and and that's fine but uh that's not what i let's see right so for this problem oh let's see right so for this problem oh wait wait subsequence not uh the subsequence makes subsequence not uh the subsequence makes it it more interesting because initially i i for for some reason i read sub string or like um or just like uh what's it called there's so much terminology that sometimes i get confused but i meant just like contiguous like next to each other um but because i saw this example where okay you could go a a b b b then it becomes a little bit more interesting maybe um and looking at that n is equal to thousand a couple of things come to my mind uh which in an interview maybe it's a little bit metal but um but i know that n squared is gonna be fast enough but but you know now it is a little bit interesting that it's only a and b and these things so it also reminds me of a more competitive programming problem where maybe the answer is just something weird and by that i mean um like looking at this i would try to fake think about a way to maybe because without you know the my initial misreading of the problem where is the substring i would think about some sort of dynamic programming maybe maybe some sort of n-cube dynamic programming something like that like a divide and conquer dynamic program or something like that i don't know right but given the n is zero the thousand and then i looked at this well that's not the this problem um so given that it is subsequence what can we do right well the the thing to notice is that and i don't know if this is an important fact but i'm you know this is a live problem so i'm just going for my thought process i think one thing that i noticed is that you know and this is maybe obvious but sometimes you have to put emphasis on it which is that um every character has to be removed once right and then the question is okay if every character has to remove one um how do we combine them in a defective um um for instance well okay now i just think about something that's really dumb right which is that okay given that it only consists of letters a and b you can actually remove everything in two steps which is this is this kind of thing is the thing that i was talking about with respect to like i think this is like one of those annoying tricky problems and what i mean by that is that you can do everything in two moves because the first move will be remove all a's and then second move we return all b's right we move for b sorry and if you do that then there's gonna be at least two moves and also it's very easy to verify that a string of all a's and a string of all b's are paradrome if not then maybe pause the video and think about that um okay so now that we know the answer is two then the question is um okay how do we you know so two is the answer no matter what or like sorry 2 is the answer in the worst case no matter what and then the question is well what what then now you can break it down to okay what would give me an end of 0 what would give me the answer of 1 and what would give me the ends of 2 right and then okay the answer is s is equal to i mean for an empty string is zero because then you know because you don't have to you know because you don't have to remove anything you're done so then the remove anything you're done so then the question is question is and then you know that everything else and then you know that everything else is returned too so then the question is is returned too so then the question is how do we check if we can remove one how do we check if we can remove one right right and then this is actually pretty simple and then this is actually pretty simple in this case because if you can remove in this case because if you can remove this in one this in one in one step and you can remove in one step and you can remove everything in one step if everything in one step if it's a palindrome so it's a palindrome so you know and you can write this in you know and you can write this in however each way i'm just gonna write in however each way i'm just gonna write in a one-liner but a one-liner but um but feel free to kind of write it in um but feel free to kind of write it in you know a one line if statement you know a one line if statement this is technically different how you this is technically different how you want to do it uh it jumped out right want to do it uh it jumped out right accounting is a little bit accounting is a little bit you know the complexity is a little bit you know the complexity is a little bit tricky depending on your language and tricky depending on your language and how you do it and whether you create how you do it and whether you create an instant of another string uh an instant of another string uh otherwise but otherwise but like you know even the most um like it's like you know even the most um like it's it's not that hard to write you know the it's not that hard to write you know the two pointer version where two pointer version where um you know you have a pointer to the to um you know you have a pointer to the to the beginning you have one at the end the beginning you have one at the end you just kind of merge into the middle you just kind of merge into the middle you're in a while loop that should be you're in a while loop that should be okay the enter is accepted cool okay the enter is accepted cool uh and of course this is gonna be linear uh and of course this is gonna be linear time because time because no matter what you have to look at the no matter what you have to look at the string and the like every count of the string and the like every count of the string and that's gonna be linear time string and that's gonna be linear time in terms of space like i said you have in terms of space like i said you have two pointers to count the pound room two pointers to count the pound room this is very basic problem this is very basic problem or you know you do what i do which is or you know you do what i do which is kind of maybe oven space depending on kind of maybe oven space depending on how the language uh the language how the language uh the language implements it implements it but you know i'm just kind of because but you know i'm just kind of because i'm focusing on the explanation i'm focusing on the explanation and hopefully the dot process uh and and hopefully the dot process uh and versus you know versus you know uh on all the details for now uh on all the details for now um remember of course like i said you um remember of course like i said you should be should be you should be able to up solve this at you should be able to up solve this at home by making it all one space home by making it all one space but yeah um i don't think this problem but yeah um i don't think this problem is tricky oh sorry i don't think i have is tricky oh sorry i don't think i have anything anything i mean this farm is tricky but i don't i mean this farm is tricky but i don't think i have anything tricky to explain think i have anything tricky to explain after i know the solution like after i know the solution like before like it's one of those trick before like it's one of those trick problems where problems where you know if you know the trick then you know if you know the trick then actually it's duh actually it's duh uh if you didn't know the trick then you uh if you didn't know the trick then you know and hopefully know and hopefully um you saw how i did it i got done you um you saw how i did it i got done you know went for different processes know went for different processes and maybe even a misreading um but yeah and maybe even a misreading um but yeah after you see all that after you see all that you know after hopefully you know when you know after hopefully you know when you see my explanation or like my you see my explanation or like my live explanation because i thought about live explanation because i thought about this live uh you know this live uh you know now they're looking back i feel like now they're looking back i feel like i've solved this problem before but i've solved this problem before but but i still didn't recognize this off but i still didn't recognize this off the bad because this is such a one-off the bad because this is such a one-off right like right like if you memorize this problem um then if you memorize this problem um then you know like it's not a waste it's not you know like it's not a waste it's not a good use of my memory to memorize a good use of my memory to memorize these problems these problems so even though it feels familiar i don't so even though it feels familiar i don't remember the solution remember the solution but that said um hopefully the way that but that said um hopefully the way that i thought about it gave you some insight i thought about it gave you some insight on how to solve this on how to solve this for yourself um cool that's all i have for yourself um cool that's all i have it's a it's a fun silly problem but it's a it's a fun silly problem but you know it's cute um probably not gonna you know it's cute um probably not gonna see this in an interview or at least see this in an interview or at least well maybe not by itself maybe you could well maybe not by itself maybe you could see like two three problems in like see like two three problems in like a session and then do it or force it to a session and then do it or force it to do it because it's such a do it because it's such a you know like like it's such a weird you know like like it's such a weird interview question because interview question because it's like if i were to ask you this it's like if i were to ask you this problem it's like either you know it or problem it's like either you know it or you don't and you don't and admit and i don't know how much it admit and i don't know how much it teaches me about you as a candidate so teaches me about you as a candidate so that's why that's why i wouldn't give this problem but who i wouldn't give this problem but who knows anymore everyone asks a lot of knows anymore everyone asks a lot of questions a lot of interview questions questions a lot of interview questions that i disagree with so that i disagree with so anyway that's all i have um stay safe anyway that's all i have um stay safe stay cool stay cool uh you know stay healthy and to good uh you know stay healthy and to good mental health i'll see you tomorrow bye | 2024-03-20 12:23:52 | 1,332 | 1332. Remove Palindromic Subsequences - Day 8/31 Leetcode March Challenge |
|
bd7MQ81SoNI | okay so uh lead code practice time um this uh this is the last question for um this uh this is the last question for today uh there are two goals for today uh there are two goals for this uh video the first one is to see this uh video the first one is to see uh how do you solve this problem and uh how do you solve this problem and then we are going to put some code in then we are going to put some code in and the second one is to see how to and the second one is to see how to behave in a real interview given the behave in a real interview given the question question so let's get started remember the first so let's get started remember the first thing is to always thing is to always always try to understand the problem if always try to understand the problem if there is anything unclear to you there is anything unclear to you please ask the question to the please ask the question to the interviewer interviewer and also think about some edge cases and also think about some edge cases which we need to which we need to take special care of in the next step so take special care of in the next step so let's restore the problem so it's called let's restore the problem so it's called design data structure design data structure that follows the constraints of a least that follows the constraints of a least recently recently used cache has which is lr cache used cache has which is lr cache so implement the error lru cash class so implement the error lru cash class liu cash liu cash so errol cash is if you um so errol cash is if you um have some capacity and the least have some capacity and the least recently used item is going to be recently used item is going to be removed removed uh so that's essentially what an iou uh so that's essentially what an iou cache is cache is so let's say it has a constructor which so let's say it has a constructor which initialize the capacity initialize the capacity of the uh cache so it's for sure to be of the uh cache so it's for sure to be positive positive which is both in bold font so which is both in bold font so it has a good api and it has a good api and if the key doesn't exist then it return if the key doesn't exist then it return -1 and it has a put api -1 and it has a put api to update the key and value so if the to update the key and value so if the key value exists key value exists let me try to update it otherwise let me try to update it otherwise you add a new keyword appearing to the you add a new keyword appearing to the cache cache so if the number of the keys exists so if the number of the keys exists exceeded exceeded exceeds the capacity from the operation exceeds the capacity from the operation that we evict that we evict the least recently is key so follow up the least recently is key so follow up so can you so can you do get and put in a one-time complexity do get and put in a one-time complexity so of course we can so of course we can yeah so there isn't too much to clarify yeah so there isn't too much to clarify i think i think pretty clear and also i don't think of pretty clear and also i don't think of any ash case any ash case at this moment because we have some at this moment because we have some pretty strong assumptions saying that pretty strong assumptions saying that the capacity is going to be positive for the capacity is going to be positive for sure sure um and yeah i know so um and yeah i know so uh if the key doesn't exist then we uh if the key doesn't exist then we return -1 okay so that those are very return -1 okay so that those are very good good assumptions uh we have so we don't have assumptions uh we have so we don't have any ash cases at this moment any ash cases at this moment yeah so uh let's think about the yeah so uh let's think about the solution so the solution solution so the solution yeah so the solution is to have the yeah so the solution is to have the hashmap hashmap to store so so first of all we will to store so so first of all we will define a doubly linked list define a doubly linked list so the double linked list so the double linked list the the the tail of the linked list the the the tail of the linked list is the least recently used key value is the least recently used key value and for the hashmap we are going to and for the hashmap we are going to store the key to the corresponding node store the key to the corresponding node so when we so for the implementation of so when we so for the implementation of the get the get api you try to get the api you try to get the corresponding node based on the key from corresponding node based on the key from the hash map the hash map and then update the curs update the and then update the curs update the doubly linked list doubly linked list for the put same thing we are going to for the put same thing we are going to put the put the key and value into the hashmap and also key and value into the hashmap and also update the double linked list update the double linked list so both are going to be 01 regarding the so both are going to be 01 regarding the time complexity for the get and put time complexity for the get and put operation so having said that operation so having said that let's do some coding let's do some coding so uh for coding part so uh for coding part uh there first of all we need to define uh there first of all we need to define some uh member members so let's say this is the capacity and we also need to have the hashmap which is the integer to node this is let's just call it map um so we are going to define a class and it has several different and it has several different members the first one is a key of course members the first one is a key of course and the second one and the second one is the value and is the value and it also has the previous it also has the previous the reference to the previous node and the reference to the previous node and it also has the reference to the next it also has the reference to the next note note and then we have the public and then we have the public sorry public note sorry public note we have the constructor here let's say we have the constructor here let's say key and the value this dot key is your key and the value this dot key is your key key this dot value this dot value is equal to value is equal to value all right so that's it all right so that's it for the node definition and for the node definition and we are also going to have the head of we are also going to have the head of the the uh link list uh link list here so in the constructor we are going here so in the constructor we are going to to initialize the hashmap initialize the hashmap uh we are going to have the capacity uh we are going to have the capacity the capacity is equal to the capacity is equal to ct okay and node is equal to ct okay and node is equal to uh the new uh uh sorry it's going uh the new uh uh sorry it's going sorry the hat should be a sorry the hat should be a none pointer so for the get none pointer so for the get and the set for the get key and the set for the get key i said first of all check if the hash i said first of all check if the hash map map contains the corresponding thing so if contains the corresponding thing so if mat dot contact mat dot contact not contains a key then simply we are not contains a key then simply we are just just going to return -1 going to return -1 otherwise it means we have the otherwise it means we have the corresponding node in the corresponding node in the in the in the in the hashmap so in the in the in the hashmap so that's the time uh we are going to say that's the time uh we are going to say okay okay node.note is equal to um node.note is equal to um map.gas the key map.gas the key and uh we what we should do and uh we what we should do is uh we should is uh we should first of all detach the node first of all detach the node from the from the from the linked list from the from the from the linked list then we are going to reattach it to the then we are going to reattach it to the head of the linked list head of the linked list then we are going to return then we are going to return the uh we are going to return all the the uh we are going to return all the value value okay so that is good and for the put um same thing so if a map dot contains the key so if it already contains the key um then it means uh we so if it contains a key we are going to so if it contains a key we are going to say say okay uh no no no it is not equal to map okay uh no no no it is not equal to map gets the key all right gets the key all right so now that value is equal to updated to so now that value is equal to updated to the value and then we are going to uh attach the node and then we just return it and then we just return it otherwise it means that we have already otherwise it means that we have already uh so otherwise it means that uh uh so otherwise it means that uh we we don't already have the we we don't already have the corresponding key and value corresponding key and value uh in the uh uh in the uh in the in the hashmap so in the in the hashmap so you're going to have the new node so new you're going to have the new node so new node is good new known node is good new known as the key and value so we are going to put it into the hashmap that put as a key and the uh what is that this should be the node okay and we should also attach so the thing so the thing currently is we also need to check if currently is we also need to check if the size of the map the size of the map is larger than capacity if my dot size is larger than capacity if my dot size is larger than the capacity then that's the time we are going to do something to remove one node so we are going to detach the uh prev the which is the tail node the least recently used node and we are going to a so okay so maybe um so okay so maybe um let's say node remove node is equal to let's say node remove node is equal to head dot pre so we are going to head dot pre so we are going to do that and then dots remove do that and then dots remove the remove node key the remove node key yes so that's it yes so that's it uh so we detach and then uh so we detach and then attach so first of all we attach the attach so first of all we attach the node to the head and then we detach the last one i think it should be okay so the next thing for us to do is to implement some helper so okay the so okay the detergent attached so private boy the detergent attached so private boy the detach and the detach and the private void attach private void attach um yep so this um yep so this is the node and node this is a node is the node and node this is a node node okay yeah so node okay yeah so if i attach it then it means we need to if i attach it then it means we need to put it put it as a head node so if as a head node so if um head is equal to um head is equal to some none pointer then you're going to some none pointer then you're going to say head say head node.next is equal to uh node.next is equal to uh node and node so it's like node and node so it's like self-reference self-reference is equal note it's like a self single is equal note it's like a self single note circle note circle so we are going to say all right had is so we are going to say all right had is equal to note now equal to note now and we just return otherwise it means and we just return otherwise it means it's not the head is not equal to none it's not the head is not equal to none so you're going to say head dot next so you're going to say head dot next equal to head and note equal to head and note dot brave is equal to had.pray and then no had that spread that next is equal node and the head that's brief is equal node as well so we are going to set head as equal note all right so this attach and then the next thing is about detach how to detach the node from so how they detach so the thing so how they detach so the thing is if um so uh is it possible that we detach something uh i don't think it's possible if the head is called none then it detects something so if uh node dot node dot next is equal to node next is equal to node so if there is only one node within the so if there is only one node within the within within the within the double within within the within the double linked list linked list that means um we just had set had as that means um we just had set had as equal to the num pointer equal to the num pointer otherwise and then we just need to otherwise and then we just need to return otherwise return otherwise we will have node we will have node dot spray down next is dot spray down next is equal to node.next and note equal to node.next and note that next the parade that next the parade is equal to node.3 is equal to node.3 so that's that that's how to detach the so that's that that's how to detach the note from the length note from the length last uh last uh yeah so that's it yeah so that's it and also we need to say and also we need to say [Music] [Music] hey um node is hey um node is equal to head there you have know that equal to head there you have know that next hat is equal to next hat is equal to node.next otherwise it's going to cause node.next otherwise it's going to cause some problem some problem um yeah so i think that should be it so remember the last thing is about testing so um usually we will go through um some test cases manually uh to do sanity check and at the same time explain how this piece of code is gonna work uh but uh since uh we don't have enough time for this uh i would just uh just uh using my pure eye to to to explore the correctness of the let's see so first of all we are going let's see so first of all we are going to initialize the hashmap to initialize the hashmap so this is a cap capacity and then so this is a cap capacity and then highlights so when we try to detach it highlights so when we try to detach it uh if it is just a single note circle uh if it is just a single note circle then we are just going to set head is then we are just going to set head is equal to none then return it equal to none then return it otherwise if it is equal to a hat otherwise if it is equal to a hat the height is equal to node.next the height is equal to node.next yep and uh yep and uh now we are going to how did we are going now we are going to how did we are going to set know the free to set know the free down next is going to know next now down down next is going to know next now down next up pretty basically not afraid okay next up pretty basically not afraid okay so that's how they detach a node from so that's how they detach a node from the linked list the linked list and uh see how to attach it into to the and uh see how to attach it into to the head head so if head is none they get a self so if head is none they get a self redirecting redirecting node and the set has a secret node the node and the set has a secret node the return return so otherwise uh we are going to have no so otherwise uh we are going to have no down axis had no the previous down axis had no the previous had approved no dot prive dot next is had approved no dot prive dot next is equal node equal node and the prey had and the prey had dodged had a previous equal dodged had a previous equal to note okay this looks to note okay this looks fair um so we have the get and the fair um so we have the get and the foot so we have so when we get foot so we have so when we get first of all we see if it contains if first of all we see if it contains if not contain return not contain return minus one otherwise we get the minus one otherwise we get the node from it detach it node from it detach it and attach to the head then we return and attach to the head then we return node dots node dots value sounds fair value sounds fair so for the put we will see if it so for the put we will see if it contains contains if it contains let me just get the if it contains let me just get the corresponding thing corresponding thing updated and then detach and attach and updated and then detach and attach and then return then return otherwise we are going to have a new otherwise we are going to have a new node node and we are going to attach it and then and we are going to attach it and then we are going to put it we are going to put it if the size is larger than the capacity if the size is larger than the capacity uh uh then we have to find the tail node and then we have to find the tail node and detach it and then remove from the map detach it and then remove from the map all right all sounds fair let's give it all right all sounds fair let's give it a shot a shot okay it's accepted it's accepted okay it's accepted it's accepted yeah so you can see this is my second yeah so you can see this is my second version version of my implementation yeah so for my of my implementation yeah so for my first version i actually made a stupid first version i actually made a stupid mistake mistake and i spent quite some time to debug and i spent quite some time to debug where to code it where to code it where the where the the the bug is where the where the the the bug is so i'll tell you where the my previous so i'll tell you where the my previous block was so block was so it was here uh so it was here uh so i didn't set the node uh i didn't set the node uh i in the detach function if node is i in the detach function if node is either had either had i didn't set reset the head so if i i didn't set reset the head so if i don't don't reset the head then it is going to cause some serious problem because uh the attack the attach means we are trying to attach the node to be the previous head and then um yeah and it causes a series of the issues but glad i caught that bug and then i redo this video so that's it for this question coding question uh if you have any question about this coding puzzle please give me leave some comments if you find this video a bit helpful please give me a like and i'll see you next | 2024-03-21 12:53:43 | 146 | Microsoft Coding Interview Question | Leetcode 146 | LRU Cache |
|
oN0yDH-_5dk | welcome to midnight coding everyone today we'll solve lead code question 684 today we'll solve lead code question 684 redundant connection this is a graph redundant connection this is a graph problem and we'll be using union find problem and we'll be using union find algorithm to solve this problem algorithm to solve this problem but before we continue please like this but before we continue please like this video and subscribe to the channel as it video and subscribe to the channel as it will provide you with all the luck you will provide you with all the luck you need on your upcoming job interview so need on your upcoming job interview so if you are planning on getting into any if you are planning on getting into any of the fan companies or if you have an of the fan companies or if you have an upcoming interview if you like this upcoming interview if you like this video i promise you will get the offer video i promise you will get the offer and also it encourages me to keep making and also it encourages me to keep making educational videos like this this is a educational videos like this this is a medium difficulty problem but before we medium difficulty problem but before we continue with our explanation and coding continue with our explanation and coding it up i want to go over the concept and it up i want to go over the concept and explain to you guys how exactly union explain to you guys how exactly union find is helpful in this situation and find is helpful in this situation and how we can optimize union find so let's how we can optimize union find so let's jump into the explanation jump into the explanation now let's think about how union find or now let's think about how union find or disjoint set with rank works in the disjoint set with rank works in the beginning all the notes are going to beginning all the notes are going to have rank of one and when we connect two have rank of one and when we connect two notes it doesn't really matter which one notes it doesn't really matter which one is gonna become the parent note or the is gonna become the parent note or the root note so let's just say that i'm root note so let's just say that i'm going to make this one the parent note going to make this one the parent note so this one is the parent note and since so this one is the parent note and since we have made that one the parent note we have made that one the parent note let's update the right so the rank of let's update the right so the rank of this one is going to be two and this one this one is going to be two and this one is it's child note and this is the is it's child note and this is the parent note now so now parent note now so now when we connect this note over here with when we connect this note over here with this note over here now we ask what's this note over here now we ask what's the parent of this note so we can go up the parent of this note so we can go up and we can see that the parent node of and we can see that the parent node of one this one over here is two this red one this one over here is two this red one and we're going to check the rank so one and we're going to check the rank so the rank of this is two and the rank of the rank of this is two and the rank of this one is one and we're gonna do the this one is one and we're gonna do the same thing with um this node over here same thing with um this node over here two and we're gonna try to find its two and we're gonna try to find its parent node and how do we do that well parent node and how do we do that well we know that this note is the parent of we know that this note is the parent of itself because of this connection so we itself because of this connection so we can just imagine that all the notes can just imagine that all the notes starting out they're going to be their starting out they're going to be their own parents so now after we have done own parents so now after we have done all that we know that the parent of this all that we know that the parent of this node is this 2 as well and we can just node is this 2 as well and we can just keep the rank as is so let's do the same keep the rank as is so let's do the same thing with the second thing with the second half of this graph so let's connect half of this graph so let's connect these two and let's make its rank 2 and these two and let's make its rank 2 and let's connect these two and now what if let's connect these two and now what if you wanted to connect this one and this you wanted to connect this one and this one so if you wanted to make a one so if you wanted to make a connection between these two first of connection between these two first of all we're gonna find its parent so we're all we're gonna find its parent so we're gonna go up go up and we found its gonna go up go up and we found its parent its parent is two and then we're parent its parent is two and then we're going to go up again and this node's going to go up again and this node's parent has a rank of two as well so as i parent has a rank of two as well so as i said again if they're equals it doesn't said again if they're equals it doesn't really matter uh we can just connect really matter uh we can just connect these two like that and then we can make these two like that and then we can make the parent of this set to be this node the parent of this set to be this node and then we will just update its rank as and then we will just update its rank as well so to do these operations we need well so to do these operations we need two functions we need a function called two functions we need a function called find and we know the function called find and we know the function called union hence called union find basically union hence called union find basically what happens is that you have two nodes what happens is that you have two nodes so this union function takes two so this union function takes two arguments so it takes note one and note arguments so it takes note one and note two and this find function just takes two and this find function just takes one argument which is known find goes to one argument which is known find goes to this node makes itself up to the parent this node makes itself up to the parent node and union just tries to connect two node and union just tries to connect two nodes together and here's what's so nice nodes together and here's what's so nice about union find our disjoint set is about union find our disjoint set is that for example if there was three that for example if there was three nodes we're gonna call union on these nodes we're gonna call union on these two nodes and we're gonna try to find two nodes and we're gonna try to find its parent right let's just say for this its parent right let's just say for this example they were their own parents example they were their own parents that's fine and we're gonna do the same that's fine and we're gonna do the same thing for this two note and the parent thing for this two note and the parent is going to be this one over here and is going to be this one over here and now if we try to connect these two nodes now if we try to connect these two nodes we're going to call our find function we're going to call our find function over here on this note and on this node over here on this note and on this node as well but their parent is the same as well but their parent is the same node that means there's a cycle in this node that means there's a cycle in this graph so once we find the cycle we can graph so once we find the cycle we can we can just return true and we can just we can just return true and we can just return the index or the value of these return the index or the value of these two two nodes so that's basically how we're nodes so that's basically how we're going to use union find to solve this going to use union find to solve this problem now let's think about what path problem now let's think about what path compression is okay so let's just say compression is okay so let's just say that we're looking at this note right that we're looking at this note right here we called our union function on two here we called our union function on two nodes and let's just say this node over nodes and let's just say this node over here happens to be this node over here here happens to be this node over here so its value is x so the parent of x is so its value is x so the parent of x is y but that's actually not true because y but that's actually not true because the parent of x is actually this one the parent of x is actually this one over here let's call it node c so we're over here let's call it node c so we're gonna say if x is parent equal to parent gonna say if x is parent equal to parent of x because remember this root note is of x because remember this root note is going to point to itself making it's the going to point to itself making it's the root note so when we go from x to y y root note so when we go from x to y y does not equal to its parent so we're does not equal to its parent so we're gonna make this is the current parent gonna make this is the current parent and the parent of this also does not and the parent of this also does not equal to this note over here so we're equal to this note over here so we're gonna make our way up and up until we gonna make our way up and up until we find the parent or root note but in this find the parent or root note but in this example you can see that we're going one example you can see that we're going one by one and we don't have to do that we by one and we don't have to do that we can do what's called path compression can do what's called path compression basically what we're gonna say is that basically what we're gonna say is that parent of x this one over here is parent of x this one over here is currently this one but we're gonna say currently this one but we're gonna say parent of x is equal to parent of parent parent of x is equal to parent of parent of x parent of x right now is this not of x parent of x right now is this not over here so this notes parent meaning over here so this notes parent meaning this one over here so we're making our this one over here so we're making our progression faster by doing path progression faster by doing path compression so here's a picture i found compression so here's a picture i found from geeks4geeks and visually it looks from geeks4geeks and visually it looks way better than what i just drew so i'm way better than what i just drew so i'm just going to use this picture so as you just going to use this picture so as you can see the initial note or or the root can see the initial note or or the root note is 9 over here and these are all of note is 9 over here and these are all of its children nodes basically what path its children nodes basically what path compression does is that it turns this compression does is that it turns this structure over here and makes it like structure over here and makes it like this so next time we have to access this this so next time we have to access this three over here so if this three wanted three over here so if this three wanted to go up this can just go up instead of to go up this can just go up instead of going from here to here to here into going from here to here to here into here so instead of doing that it just it here so instead of doing that it just it just makes it a really short path to just makes it a really short path to follow so that's just basically what follow so that's just basically what path compression is it's a really nice path compression is it's a really nice optimization technique and it's going to optimization technique and it's going to lower our time complexity now let's jump lower our time complexity now let's jump into the coding all right before we into the coding all right before we actually jump into the coding i want to actually jump into the coding i want to talk about how we are actually going to talk about how we are actually going to initialize the parent and the rank initialize the parent and the rank variables that we're going to create so variables that we're going to create so in the beginning we want to make sure in the beginning we want to make sure that a node points to itself so this that a node points to itself so this node's root will be itself so we need node's root will be itself so we need that information to begin with and how that information to begin with and how can we do that right so all the can we do that right so all the information we've given is the edges for information we've given is the edges for example this node has an h2 here and example this node has an h2 here and this node has an h to here so what we're this node has an h to here so what we're basically given is x basically given is x y and x y and x c and the length of our input is 2 but c and the length of our input is 2 but as you can see there are three nodes and as you can see there are three nodes and when we initialize basically what we're when we initialize basically what we're going to say is that we're going to take going to say is that we're going to take the length of our edges the input the length of our edges the input variable we get and then we're just variable we get and then we're just going to add one node to account for all going to add one node to account for all the other nodes because if we don't the other nodes because if we don't we'll be missing out one node so after we'll be missing out one node so after that when we get this we're basically that when we get this we're basically gonna say so this node it points to gonna say so this node it points to itself this node points to itself and itself this node points to itself and this node points to itself and we can do this node points to itself and we can do the same thing for rank so the rank of the same thing for rank so the rank of this note is going to be one and one this note is going to be one and one here as well and one here again so here as well and one here again so that's how we're going to initialize our that's how we're going to initialize our parent and rank variables so in python parent and rank variables so in python we're just gonna use a dictionary and in we're just gonna use a dictionary and in go we're just going to use an array to go we're just going to use an array to represent this relationship and the next represent this relationship and the next thing i want to talk about is the time thing i want to talk about is the time complexity so just to find function complexity so just to find function itself it would be o of n however since itself it would be o of n however since we're using path compression we can say we're using path compression we can say that the time complexity is o log of n that the time complexity is o log of n so union on the other hand since we're so union on the other hand since we're using rank over here let's just say that using rank over here let's just say that in in theory the operation should take in in theory the operation should take log of n time because we are using path log of n time because we are using path compression to use find but the time compression to use find but the time complexity of disjoint set using path complexity of disjoint set using path compression and rank together the two compression and rank together the two optimization techniques it actually optimization techniques it actually comes down to o of amortized n and comes down to o of amortized n and that's the worst time complexity so with that's the worst time complexity so with that being said now let's go into the that being said now let's go into the coding so here's the solution to the coding so here's the solution to the problem in go so as compared to our problem in go so as compared to our python solution our go solution is going python solution our go solution is going to be a little bit more lengthy and to be a little bit more lengthy and that's just one advantage python has that's just one advantage python has over all other languages because it's over all other languages because it's just so easy to write even so in go it's just so easy to write even so in go it's not going to be difficult anyways what not going to be difficult anyways what we're going to do right now is that we're going to do right now is that we're going to create a struct called we're going to create a struct called union find or disjoint set so let's call union find or disjoint set so let's call it type disjoint set it type disjoint set and it's gonna be estra and our struct and it's gonna be estra and our struct is going to consist of three things is going to consist of three things parent and rank and the number of parent and rank and the number of components so we need the parent because components so we need the parent because we obviously need to know which disjoint we obviously need to know which disjoint set goes into which disjoint set and we set goes into which disjoint set and we need a rank because we are utilizing need a rank because we are utilizing this technique called path compression this technique called path compression as we discussed in our drawing as we discussed in our drawing explanation and we need n to know how explanation and we need n to know how many components there are within our many components there are within our graph so now that's done now we are graph so now that's done now we are going to define our functions find and going to define our functions find and union so function find is going to union so function find is going to receive a note and that's going to be of receive a note and that's going to be of integer and it's going to return an integer and it's going to return an integer as well so here is how we're integer as well so here is how we're going to do our path compression while going to do our path compression while uh in go it's four and one thing we uh in go it's four and one thing we forgot to do is that we're gonna have to forgot to do is that we're gonna have to uh define this u variable over here uh define this u variable over here because uh we are going to be uh using because uh we are going to be uh using this our disjoint set struct so uh we'll this our disjoint set struct so uh we'll be using this u variable and it's gonna be using this u variable and it's gonna be this joint set so while u dot parent be this joint set so while u dot parent of n does not equal to n itself meaning of n does not equal to n itself meaning that if it's not the parent of itself that if it's not the parent of itself then we're gonna do a path compression then we're gonna do a path compression which is now that u dot parent n is which is now that u dot parent n is going to be u dot parent n going to be u dot parent n you dot parent off you don't parent uh you dot parent off you don't parent uh of n so that's basically what the path of n so that's basically what the path compression is what's happening is that compression is what's happening is that so n is probably connected to other so n is probably connected to other nodes and then we're gonna say is that nodes and then we're gonna say is that the parent of n is the parent of the the parent of n is the parent of the parent of n so we're basically parent of n so we're basically shortening the path so next time we shortening the path so next time we iterate we have shorter distance so now iterate we have shorter distance so now we're just gonna say this n is going to we're just gonna say this n is going to equal to u dot parent of n and if if we equal to u dot parent of n and if if we found the root of this node n then we found the root of this node n then we can just return the parent of n and now can just return the parent of n and now we need to do the union function we need to do the union function so for union uh we are receiving two so for union uh we are receiving two inputs we're receiving uh one note and inputs we're receiving uh one note and one note and and two known and it's one note and and two known and it's going to return a boolean value because going to return a boolean value because we know that as soon as we find a cycle we know that as soon as we find a cycle in this graph that's the answer we want in this graph that's the answer we want to return what we're going to say is to return what we're going to say is that that n1 root and n2 root is going to equal to n1 root and n2 root is going to equal to u dot find n1 and you don't find n2 for u dot find n1 and you don't find n2 for that matter and then what we're gonna that matter and then what we're gonna say is that if n1 root equals n2 root say is that if n1 root equals n2 root then we know that there's a cycle in then we know that there's a cycle in this graph so it's going to return false this graph so it's going to return false um the reason why we return false is um the reason why we return false is this so in our main function find this so in our main function find redundant connection what we're going to redundant connection what we're going to say is that we're first of all we're say is that we're first of all we're going to going to initialize our disjoint set so our initialize our disjoint set so our destroying set is going to be this joint destroying set is going to be this joint set uh and let's give it in the length set uh and let's give it in the length of edges plus one and then what we're of edges plus one and then what we're gonna say is that for i gonna say is that for i for i is zero and i is less than uh for i is zero and i is less than uh less than the length edges and i plus less than the length edges and i plus plus what we're gonna say is that if plus what we're gonna say is that if edges at i and if the zero disjoint set edges at i and if the zero disjoint set dot dot union with so we're gonna union edges i union with so we're gonna union edges i zero and i1 if this is false then we're zero and i1 if this is false then we're just gonna return an array of these two just gonna return an array of these two elements and based on the description elements and based on the description we're guaranteed that we're gonna get an we're guaranteed that we're gonna get an answer at least an answer but if we just answer at least an answer but if we just leave it like that go it's not gonna leave it like that go it's not gonna like it so we're just gonna have to like it so we're just gonna have to return an empty array like this although return an empty array like this although it's not gonna get executed so that's it's not gonna get executed so that's why we are saying if n1 root and n2 root why we are saying if n1 root and n2 root of equals this is false so what happens of equals this is false so what happens if this is not false so now uh now we're if this is not false so now uh now we're gonna use our rank to determine which gonna use our rank to determine which disjoint set this uh another disjoint disjoint set this uh another disjoint set goes so we're gonna say if u dot set goes so we're gonna say if u dot rank of n1 root if this is greater than rank of n1 root if this is greater than n2 roots rand then the rank then the n2 roots rand then the rank then the parent of n2 root is going to be n1 root parent of n2 root is going to be n1 root so if this is the case then u the parent so if this is the case then u the parent of n2 root it's going to equal to of n2 root it's going to equal to in one root else if if it's the other in one root else if if it's the other way around then we're just going to way around then we're just going to switch it up and then we're going to say switch it up and then we're going to say that the parent of n1 root is into root that the parent of n1 root is into root and we have another condition which is and we have another condition which is else that's if these two are equals else that's if these two are equals they're equals like it doesn't really they're equals like it doesn't really matter which one uh it's gonna have a matter which one uh it's gonna have a higher rank i'm just gonna say that that higher rank i'm just gonna say that that n1 is going to have higher rank and then n1 is going to have higher rank and then we can update the rank of n1 root plus we can update the rank of n1 root plus equals one so next time it comes uh n1 equals one so next time it comes uh n1 root is going to have higher ranking root is going to have higher ranking than an and two root okay so that's than an and two root okay so that's basically it now we just need to basically it now we just need to construct our disjoint set so over here construct our disjoint set so over here i'm going to i'm going to define a variable called uh construct define a variable called uh construct disjoint set and it's going to receive disjoint set and it's going to receive the number of components and then it's the number of components and then it's going to return disjoint set going to return disjoint set so parent and rank they are going to be so parent and rank they are going to be uh an array of integers uh with the uh an array of integers uh with the length of n that we give it to uh so length of n that we give it to uh so that this that n is the length of edges that this that n is the length of edges plus one we went over y length of edges plus one we went over y length of edges plus one in our drawing explanation so plus one in our drawing explanation so you can go back and check y and rank is you can go back and check y and rank is also going to be the same so we're gonna also going to be the same so we're gonna do for i so i is gonna be zero do for i so i is gonna be zero and while i is less than n and while i is less than n and then and then i plus plus we're going to say i plus plus we're going to say parent at this index is going to equal parent at this index is going to equal itself and rank at this index is going itself and rank at this index is going to equal 2 1 because to equal 2 1 because all the nodes is going to have initial all the nodes is going to have initial rank of one rank of one and at the end we can just return at and at the end we can just return at this joint set of parent is going to this joint set of parent is going to equal to parent rank is going to be equal to parent rank is going to be rank and n is going to be rank and n is going to be n so that's basically it for defining uh n so that's basically it for defining uh and using this join set to solve this and using this join set to solve this problem now let's run it to see if it problem now let's run it to see if it works uh sorry but that we don't need uh works uh sorry but that we don't need uh commas in here when we're defining commas in here when we're defining struct now let's see if it works oh we struct now let's see if it works oh we need to close our union function over need to close our union function over here now let's run it again oh and then here now let's run it again oh and then um because since we're returning false um because since we're returning false here and it looks it's expecting us to here and it looks it's expecting us to return a boolean we're going to return return a boolean we're going to return true over here all right now it runs now true over here all right now it runs now let's submit it let's submit it and yes it works so that's basically the and yes it works so that's basically the whole intuition of using this joint set whole intuition of using this joint set to solve this problem so if you've made to solve this problem so if you've made this far into the video thank you so this far into the video thank you so much for watching and if you liked it much for watching and if you liked it please like the video and subscribe for please like the video and subscribe for eternal luck and i hope you guys learned eternal luck and i hope you guys learned something new today and if you guys have something new today and if you guys have any questions any lego questions that any questions any lego questions that you want me to cover please leave a you want me to cover please leave a message in the comment section and i'll message in the comment section and i'll try to get it done as soon as i can so try to get it done as soon as i can so i'll see you guys in the next one | 2024-03-20 16:08:27 | 684 | LeetCode 684 - Redundant Connection - Disjoint Set - Explained in Go |
|
fa8NViEXNrQ | hello fans today I'm gonna talk about new decoded trail for a two car number new decoded trail for a two car number oh nice Subway's the problem that came oh nice Subway's the problem that came an array of integers none and and you an array of integers none and and you need your K a subway he's caught on ice need your K a subway he's caught on ice if they are K or the numbers on it if they are K or the numbers on it between a number of last several ways between a number of last several ways no Kevin Jews Emperor why is that there no Kevin Jews Emperor why is that there are five numbers K you were three I was are five numbers K you were three I was returned to which he that has some ways returned to which he that has some ways to service that has all the other to service that has all the other numbers equals three so there are a lot numbers equals three so there are a lot nicer ways for the second example we nicer ways for the second example we have we can find any nice sub array have we can find any nice sub array because they are all human and for this because they are all human and for this this sort example there are sitting nice this sort example there are sitting nice sub arrays so we can sing about first the idea is that we can use the Bluetooth was two loops find all the subways here hmm and then during that then during the second loop we were kind of harmony or numbers that has cleaner birds this algorithm takes Oh and few times of course we can organise you - Oh n square times uses which is a second method based on the sir I do like the pre some idea if you have for me now is prism actually a week we can call it a pig hunt and for you food for subway I to tell us what no number all the you go to the I okay if we pass one in for the number J is odd if it's not or if it's it was not all there will be the same it was not all there will be the same control and I J in Phenom sure it's even control and I J in Phenom sure it's even and this is no takers om and so a time and this is no takers om and so a time is actually this problem is way also we is actually this problem is way also we had caused time limit in the sacred had caused time limit in the sacred because and you could file times 10 because and you could file times 10 power 4 and so where where we take 25 power 4 and so where where we take 25 times 10 power 8 this week all the time times 10 power 8 this week all the time and image a new city generally if it's and image a new city generally if it's about hemp house 8 or 10 power 7 this is about hemp house 8 or 10 power 7 this is public they will have no time limit public they will have no time limit exceeded problem here exceeded problem here so the first sort of problem that is we so the first sort of problem that is we can use ideal that is based on two can use ideal that is based on two pointers so the idea is that for example pointers so the idea is that for example here we have they have it already about a 2 to 1 1 1 to 4 is here and the K equals 2 and we can carry that to your the trapunto whines air the other is out and there are counter and kind or counter so far and we have the subway Hunt's subway nice subway not serious number over for first away my son for first away my son yo you put 0 and equal to zero as well yo you put 0 and equal to zero as well and we will see that you will have a and we will see that you will have a subway for example run here and here if subway for example run here and here if this is a sample of a there is nice then this is a sample of a there is nice then we will find that it has a tail you go we will find that it has a tail you go to right and then we will I need to to right and then we will I need to shift this Punto expect only beat so we shift this Punto expect only beat so we were shipping out to AMA and then can were shipping out to AMA and then can you to check whether there is the you to check whether there is the audience your 2 to the order is not true audience your 2 to the order is not true so we worship over this okay so we worship over this okay adios we are two so against we so far adios we are two so against we so far right and when there were here she right and when there were here she shifted a oh oh here shifted a oh oh here only Hawai element that is necessary only Hawai element that is necessary ok you go to so we will increase the increase our here so you kind of there are two numbers over here mm-hmm it's numbers because it when I'm was has order you were two as well so we are there may be achieved again with one hmm and can you know so well answer it would like plasma and pare away and we go here to here shifter memories shifted by 0.04 while here pattern actually with the lambo countries one butter we have all answers from what from the periods are out here so we need to pass a while again so in this this is a trigger part of this that we need to detect to Canada you call the Pew is reliable and certain eyes have a Vietnam people a Sarah is 1 here so applause well here any time if we see any time if the current number is all the way we are then that's basically together the then that's basically together the numbers here so first of I equal 0 and numbers here so first of I equal 0 and yeah are you gonna do yeah you could yeah are you gonna do yeah you could zero here and the Cantor you go to other zero here and the Cantor you go to other country you could do and not country you country you could do and not country you could do and a second here cos 0 and I could do and a second here cos 0 and I do 100 0 is 0 and I see and sovereign do 100 0 is 0 and I see and sovereign number is 1 and we have answers here number is 1 and we have answers here answer sulphides 0 5 0 and here is y 0 answer sulphides 0 5 0 and here is y 0 and y equal to and we care a counter or and y equal to and we care a counter or equal to 1 and not some is your 0 and equal to 1 and not some is your 0 and kindest your 0 for the force here because the Cantor number is 1 we will continue to move the right apprentice my point was should be sweet hmm 300 equal to and then the sauce not sub-arrays with Joe mmm scientists a row as long as this is co-author we will assign the line subway service number zero hopefully this is a kind not a service of kiona not subway for the kind innovation and here and here is the studio it's you didn't say we need to live how was the shiver left back because the kinda boy is our number is a 2 over here but our number 2 is just which is equal to k k so where is she oh yeah equal to Y over here and because the last number you secret oh wow this because it's our language to then I wish here is the last number shift air you could have one key and get a nice number yeah his analysis in this tool and so on I was just too so we shifted or okay yeah okay okay yes we know the kind of this only this one element and the mass number is equal to 3 here because the overall number is already change it will be 1 because the only you will manage the previous to shift 1 1 so you watch so we are allocated a while loop and pass the nice table number is 3 so answer it should be sweet and then which paneer the shifter cable ship only 4 and which we found that I found this number you know you two again yeah wait this the the nice type of it is sofa is zero and here so range to where we are used while oppa so maybe she left again for so this is kind the body while number over here so and can't count Auto counters become wow and nice number has increased the one because previously should be increased oh and here also here we should four plus one again and when you put a tool should be the shifted for file and although hunter also still while now some nice oblong with one here we have to add one is fine here's this chick apartheid a nice acronym we should be there should be no since 1 or 0 should be cable same as this person's previous table because for although for all the the period is we can the answers again the period is we can the answers again you were here I was four okay and they you were here I was four okay and they will help with this also answer and will help with this also answer and since again and all this will be sub since again and all this will be sub away okay so it's nice suburban avoid away okay so it's nice suburban avoid should be you could be increased should be you could be increased should it be capable the same so every should it be capable the same so every time we pass one to the answers so time we pass one to the answers so basically this is a code logical here basically this is a code logical here photo J and should be left Pentos and I should really uh very pentose million changes here so I mean integrated way is all numbers we all increase the work on and initialize it with you a number was we wait wait cable the previous and last cyber numbers and then when or now is equal okay we will use a while loop to analyze Sapna was plasma and she for the the left pointers to write him one step more and decrease the ordinal or controversial kind of embodies it's all numbers and their way every time we personalize some numbers there we are killed answers so basically this idea of yeah this is one okay this code what's yeah this is one okay this code what's because I have all day I write so because I have all day I write so talented candidates all go huh talented candidates all go huh you know something you all again oh they shouldn't be though ow yeah we made it thank you for watching | 2024-03-19 17:14:34 | 1,248 | Leetcode--1248 count number of nice subarrays (Two pointers) |
|
qpCqntouzYM | hello everyone this is sham saari and I welcome you again in the new video of welcome you again in the new video of our YouTube channel so this is a lead our YouTube channel so this is a lead code problem which was asked on 21st of code problem which was asked on 21st of February and the problem is medium so February and the problem is medium so pit wise and of numbers range so they pit wise and of numbers range so they have given two integers left and right have given two integers left and right that that represent range left right that that represent range left right left to right and we need to return the left to right and we need to return the bitwise add of all numbers in this range bitwise add of all numbers in this range inclusive including left and right so inclusive including left and right so left equal to 5 and right equals to 7 so left equal to 5 and right equals to 7 so the bitwise or bitwise end the bitwise or bitwise end of this range will be four uh then of this range will be four uh then bitwise and of from left to from left bitwise and of from left to from left equals to Z to right r equal to Z equals to Z to right r equal to Z bitwise and will be zero so left equals bitwise and will be zero so left equals to 1 and right equals to to 1 and right equals to this so the bitwise end of this this so the bitwise end of this operation will be zero so how to solve operation will be zero so how to solve this type of problem let's discuss the this type of problem let's discuss the approach so first of all we will approach so first of all we will initialize a variable count to count the initialize a variable count to count the number of right shifts needed to make number of right shifts needed to make left and right equal so that's the left and right equal so that's the basically that's the approach so if we will initialize a variable count and count the number of right shifts needed to make the left and right equal and after that while left is not equal to right the right shift both left and right by one bit so here we in this inside the file look while left is not equal to right then we will do what we will do right shift both left and right by one bit and increment the count after each right shift operation and after the loop left shift left y count bits and return return the result and after the loop here the left shift left by count bits and that will be the result overall result that's the approach here to solve this type of problem so let's C this solution before that if you are new to the channel hit the like button and subscribe for more content so first of all we will do we will create account variable and initialize it to zero and right so we will do what we will left right so we will do what we will left shift uh we will WR shift uh we will WR right shift left to one and right right shift left to one and right shift right to one and increment the shift right to one and increment the count and count and if and we will return if if and we will return if left of Le shift of left of Le shift of count and what is the value of that we count and what is the value of that we will return will return here uh we will left shift the left by here uh we will left shift the left by count times so that that will be the count times so that that will be the answer that's the only solution let's answer that's the only solution let's look at the overall solution yeah the test cases successfully let's submit the code yeah all the hidden test cases done successfully so here here the overall time complexity will be biger off log of minimum of left or right so what is the minimum of left of right left or right value and log of that will be the time complexity here so and the space complexity will be big of one as we are not using any container so that's it if you enjoyed this video or found it helpful don't forget to hit the like button and subscribe for more content and also stay tuned for upcoming lad code problem of the day videos and exciting monack web development projects happy coding and let's make this year a | 2024-03-22 09:39:57 | 201 | ✅Day 52 | LeetCode 201. Bitwise AND of Numbers Range #dailychallenge #leetcode #solution #problem |
|
_ZWW6FPV2pE | hello everyone so in this video we are going to solve a question complete code going to solve a question complete code it is jump game 6 this is 1696 question it is jump game 6 this is 1696 question read code and this comes under medium read code and this comes under medium category all right so let's start with category all right so let's start with the problem statement you are given and the problem statement you are given and zero indexed integer l in nums and in zero indexed integer l in nums and in integer k you are initially standing at integer k you are initially standing at index zero right we are standing at index zero right we are standing at index zero initially and in one move you index zero initially and in one move you can jump at most k step right so we can can jump at most k step right so we can jump any number of steps jump any number of steps ranging from one to k right so we are ranging from one to k right so we are basically given at most k step basically given at most k step all right so all right so like without going outside the like without going outside the boundaries of there so boundaries of there so like this is the range of the k jump and like this is the range of the k jump and you want to reach to the last index of you want to reach to the last index of the array and your score is the sum of the array and your score is the sum of all the numbers day for each j you visit all the numbers day for each j you visit in the array and at the end you need to in the array and at the end you need to return the maximum score you can get return the maximum score you can get right and then we need to return the right and then we need to return the maximum score we can get let's see maximum score we can get let's see through an example so this is our first through an example so this is our first example let's just pop it from here example let's just pop it from here and let's move toward and let's move toward this tech body so this tech body so let's see let's see this is our example this is our example right this is another example so in this right this is another example so in this example what we can do is example what we can do is we can jump for few steps right we can jump for few steps right we have k equal to 2 here we have k equal to 2 here and we have k equal to 2 so for this k and we have k equal to 2 so for this k equal to 2 what we can do is we can make equal to 2 what we can do is we can make at most two jumps right we can make at at most two jumps right we can make at most two jumps so we can make one jump most two jumps so we can make one jump or two jumps these are two possibilities or two jumps these are two possibilities we have right so let's see we can either we have right so let's see we can either jump one step here jump one step here or two steps here right we have two or two steps here right we have two possibilities here possibilities here so let's see so let's see all the possibilities so basically we all the possibilities so basically we will be making a tree to will be making a tree to see all the possibilities here right so see all the possibilities here right so let's make a tree here let's make a tree here so so there are two possibilities for this there are two possibilities for this index right either it can go to -1 or index right either it can go to -1 or minus 2 minus 2 so if we go to minus 1 the updated sum so if we go to minus 1 the updated sum would be would be 1 plus minus 1 right so this will become 1 plus minus 1 right so this will become 0 0 and the whole array will remain same 0 and the whole array will remain same 0 minus 2 minus 2 4 4 minus minus 7 7 and 3 right and similarly for minus 2 and 3 right and similarly for minus 2 this 1 plus minus 2 is equal to this 1 plus minus 2 is equal to minus 1 and the whole minus 1 and the whole array will remain same so four array will remain same so four minus seven minus seven and three and three right now let's see the possibilities right now let's see the possibilities for for these these right right the possibilities for these are again the possibilities for these are again two two right again two possibilities it can right again two possibilities it can either jump to this or this to this either jump to this or this to this height so if we jump to minus 2 and if height so if we jump to minus 2 and if we jump to minus we jump to minus 4 so let's see if we jump to minus 2 we 4 so let's see if we jump to minus 2 we will get 0 plus minus 2 is equal to say will get 0 plus minus 2 is equal to say minus 2 minus 2 4 will remain same this is same right 4 will remain same this is same right and if we jump to four and if we jump to four so the updated array would be four so the updated array would be four minus seven and three minus seven and three right and in this again we have two right and in this again we have two consolidated minus one and four consolidated minus one and four right right not minus one and four it should be not minus one and four it should be four and minus seven four and minus seven right so four and minus seven right so four and minus seven now let's see the combination so in this now let's see the combination so in this we have we have um this will become um this will become three three minus seven and three right and in this minus seven and three right and in this it becomes minus one plus minus seven it it becomes minus one plus minus seven it is equal to minus eight is equal to minus eight and and three will remain as it is right three will remain as it is right now let's see now let's see for for the cases the cases right so right so this will become this will become the here we have two possibilities right the here we have two possibilities right you can go to here or here you can go to here or here right so we have four and minus seven right so we have four and minus seven right so if we go to 4 we will get 4 right so if we go to 4 we will get 4 minus 2 is equal to 2 minus 2 is equal to 2 minus 7 and 3 right and if we go to minus 7 and 3 right and if we go to minus 7 we will get minus 7 we will get minus 9 minus 9 right minus 9 right minus 9 and three will remain as it is right and three will remain as it is right similarly for this we have two similarly for this we have two possibilities possibilities there is there is minus seven and three minus seven and three so for minus seven we will get so for minus seven we will get minus three and 3 right and minus three and 3 right and this 4 plus 3 is equal to 7 right this this 4 plus 3 is equal to 7 right this is 7 and for this 3 minus 3 and 3 we is 7 and for this 3 minus 3 and 3 we will have will have total answer is equal to 0 total answer is equal to 0 right and for this 9 minus 9 and three right and for this 9 minus 9 and three we have equal to we have equal to minus six and here we have minus six and here we have two possibilities so this will become two possibilities so this will become uh minus seven and three right so uh minus seven and three right so the answer will come out to be um the answer will come out to be um minus 7 and 2 so minus 7 and 2 so this is equal to minus 5 and 3 and this is equal to minus 5 and 3 and this is 5 right this is 5 right and this is and this is minus minus 2 right so we have till now got minus 2 2 right so we have till now got minus 2 5 5 6 6 0 and 7 right now let's see for this 0 and 7 right now let's see for this remaining one right so for this remaining one right so for this remaining vl we have eight and three so remaining vl we have eight and three so this eight and three will become this eight and three will become five right this will be a minus five and five right this will be a minus five and for this for this this will again have two possibilities this will again have two possibilities right that is minus seven and three right that is minus seven and three so for minus seven so for minus seven we will get minus four and three let's end this for three we get six and this four and three we get minus one so now we have checked for all the possibilities right we have checked for all the possibilities and the answer we got is this one right these are all the possibilities so you can easily see the maximum out of these answer is 7 right so we are returning 7 in this case so this is the first example right and this is a recursive tree just formed after all the possible combinations right so the total number of combinations we get is equal to k to the power n right and we just need to you know iterate recursively k to the power n times so if we try to memorize in the dp so it will just reduce to k 2 k into 10 right but this solution is also not accepted on delete code right so let's see optimized approach to solve this question which will reduce the time complexity to beco of n right currently the time complexity is because e to the power and then we reduce 2k to the power 9 in the dp memorization and now let's see the approach of dq to further reduce this time complexity to beco of n right so let's see so let me just copy the same example here right let's here right let's take this here take this here all right now let's take all right now let's take let me just write the indexes of this let me just write the indexes of this this is 0 this is 1 this is 2 this is 3 this is 0 this is 1 this is 2 this is 3 this is 4 and this is 5 right and what this is 4 and this is 5 right and what we will do we will make a dq here right we will do we will make a dq here right so let's make a dq so let's make a dq so we are making a dq here so we are making a dq here and let's initially store a and let's initially store a zero index here zero index here right let's initially store a right let's initially store a 0 index here 0 index here and and we have k equal to 2 right we have k we have k equal to 2 right we have k equal to 2 equal to 2 in this example so let's see in this example so let's see how can we approach this question right how can we approach this question right so we have already taken 0 so we have already taken 0 and we are basically storing the indexes and we are basically storing the indexes in this dq right we are storing the in this dq right we are storing the indexes in this dq indexes in this dq right now let's see we initially stored right now let's see we initially stored 0 0 and let's see all the combinations for and let's see all the combinations for the remaining array right the remaining array right so so we'll start with this index that is we'll start with this index that is minus 1 right so let's find out the sum minus 1 right so let's find out the sum for this so 1 plus minus 1 is equal to 0 for this so 1 plus minus 1 is equal to 0 right 1 plus minus 1 is equal to 0 right 1 plus minus 1 is equal to 0 so what we will do we will just push so what we will do we will just push this button index into this dq because this button index into this dq because we just iterated through this right now we just iterated through this right now right and let's see right and let's see whether whether the the left elements right which we just left elements right which we just iterated iterated just now or we just already created the just now or we just already created the values whether these are smaller than values whether these are smaller than zero or not if this is smaller than 0 zero or not if this is smaller than 0 then we don't have any use of this then we don't have any use of this because we need to find out the maximum because we need to find out the maximum one and we need to find out the maximum one and we need to find out the maximum so we don't need the lesser value but in so we don't need the lesser value but in this case 1 is greater than zero so this case 1 is greater than zero so let's keep this value because it let's keep this value because it must be needed afterwards right so let's must be needed afterwards right so let's see see for the next case right so we just for the next case right so we just taken this minus one now let's take taken this minus one now let's take minus two here right so minus two here right so let's take minus two so let's take minus two so let's update minus two with let's update minus two with the maximum out of this right the the maximum out of this right the maximum out of this is zero and one so maximum out of this is zero and one so out of this maximum one is one so let's out of this maximum one is one so let's update minus one plus one is equal to update minus one plus one is equal to minus 1 right minus 2 plus 1 is equal to minus 1 right minus 2 plus 1 is equal to minus 1 minus 1 and let's see and let's see whether the whether the left elements are less or not no they left elements are less or not no they are not lesser these are are not lesser these are greater than minus 1 so let's keep it as greater than minus 1 so let's keep it as it is and let's it is and let's um um push 2 into the push 2 into the dq right now we are at 3 dq right now we are at 3 so now we are when we are at 3 we so now we are when we are at 3 we basically are checking the k indexes basically are checking the k indexes because because let's you can also assume this as a let's you can also assume this as a sliding window approach because we are sliding window approach because we are maintaining a window of k size right so maintaining a window of k size right so whenever we will come to three so we whenever we will come to three so we will just check the two elements or we will just check the two elements or we can say the k elements can say the k elements so this one is extra right this element so this one is extra right this element is extra so we will just pop out this is extra so we will just pop out this from here right we will just pop out from here right we will just pop out zero from here zero from here and let's see and let's see for these two values right for these two values right and you can also observe one more thing and you can also observe one more thing that this one the front element of the that this one the front element of the dq is always the greater one right dq is always the greater one right this is the index so the value of this this is the index so the value of this index is zero so this is always the index is zero so this is always the greater out of all the values of the dq greater out of all the values of the dq right so let's see right so let's see for for another case that is four so another case that is four so let's add four let's add four with the greater one that is zero with the greater one that is zero so let's add zero here so let's add zero here right and what we can do is we can right and what we can do is we can just push this 3 into this dq just push this 3 into this dq right let's push this 3 into this eq and right let's push this 3 into this eq and let's check let's check this should be this should be this is 0 plus 4 is equal to 4 right this is 0 plus 4 is equal to 4 right this is 0 plus 4 is equal to 4 right so this is 0 plus 4 is equal to 4 right so let's see let's see whether the elements on the left side whether the elements on the left side is is greater than or less than right so in greater than or less than right so in this case the elements are lesser than 4 this case the elements are lesser than 4 right so right so we don't need it anymore let's just pop we don't need it anymore let's just pop it out from here it out from here we are just popped out these elements we are just popped out these elements from the dq from the dq let's just pop out these elements from let's just pop out these elements from dq dq and we have three on the front now and we have three on the front now so you can see that this is a maximum so you can see that this is a maximum one which is kept at front right one which is kept at front right now let's move further so now let's move further so now we have minus seven so when we have now we have minus seven so when we have minus seven let's add 4 into this minus minus seven let's add 4 into this minus 7 so 4 7 so 4 plus minus 7 plus minus 7 that is equal to minus 3 that is equal to minus 3 right and right and let's also see whether the left one has let's also see whether the left one has greater than or greater than or smaller than or not so they are not a smaller than or not so they are not a smaller let's keep it as it is let's smaller let's keep it as it is let's move forward move forward and let's push this four here and let's push this four here right now let's see for this one the right now let's see for this one the fifth index right for the fifth index we fifth index right for the fifth index we have three have three let's add the maximum out of them so 4 let's add the maximum out of them so 4 is the maximum right so let's add 4 plus is the maximum right so let's add 4 plus 3 is equal to 7 right 3 is equal to 7 right 4 plus 3 is equal to 4 plus 3 is equal to 7 7 so let's check the previous values so let's check the previous values there is smaller than 7 let's just there is smaller than 7 let's just remove it remove it and also remove from the queue and also remove from the queue and let's push and let's push this fifth index this fifth index right right so whichever index we are just so whichever index we are just processing we are just pushing it into processing we are just pushing it into our key our key so we have just completed the iteration so we have just completed the iteration right we've just completed an iteration right we've just completed an iteration and at the end we have and at the end we have one element into our dq that is five so one element into our dq that is five so let's just return the fifth index value let's just return the fifth index value so the value of fifth index is seven so so the value of fifth index is seven so our answer is 7 our answer is 7 right right so this is our answer and we have just so this is our answer and we have just iterated the whole array iterated the whole array once so the time complexity right the once so the time complexity right the time complexity in this case is big o of time complexity in this case is big o of n and space complexity is n and space complexity is becau of becau of n because at most we are just storing n because at most we are just storing n elements into this d n elements into this d right so i hope the approach is creative right so i hope the approach is creative if you still have enough in this if you still have enough in this approach feel free to comment down let's approach feel free to comment down let's move to the coding part move to the coding part all right so all right so let's make a dq here so dq let's make a dq here so dq of integers of integers let's name it dq and initially let's let's name it dq and initially let's push push zero into this dq right and zero into this dq right and let's run a for loop from let's run a for loop from first index to the last index or num first index to the last index or num start size start size and i plus plus right now and i plus plus right now let's check let's check let's see let's see what we were checking first what we were checking first we are checking we are checking the size of this window it is k window the size of this window it is k window right we are just checking whether the k right we are just checking whether the k elements are there or not so how can we elements are there or not so how can we check this we have the value of i right check this we have the value of i right and we have the value of and we have the value of k k right and also right and also we have the value of we have the value of this dq this dq right or we can say we have right or we can say we have this index this index so we are just basically checking from so we are just basically checking from the front let's see so let's see we have the front let's see so let's see we have we are checking that this dq dot front right this dq dot front whether this dq dot front eq dot front is less than this less than it is i minus k it is i minus k if dq dot front is i less than i minus k if dq dot front is i less than i minus k we will just pop it out from here right we will just pop it out from here right so if so if dq dot front the q dot front is less than i minus k right is less than then what we can do is we can just pop out from here right so um dq dot right so right so this should work fine let's turn it into this should work fine let's turn it into a a while loop so if there might be multiple while loop so if there might be multiple cases so this while loop will handle cases so this while loop will handle right now let's update our nums of i right now let's update our nums of i right we are we were just updating this right we are we were just updating this nums of i nums of i right we were just updating this nums of right we were just updating this nums of i i with with the sum right you were just updating the sum right you were just updating this this number i with the number i with the sum which was greater so the greater one sum which was greater so the greater one was always at the front one right so was always at the front one right so let's update with let's update with the front value right so numbers of i the front value right so numbers of i plus is equal to plus is equal to dq dq dot front dot front and and since this is storing index so we are since this is storing index so we are just keeping this into our nums just keeping this into our nums all right so this is fine right now all right so this is fine right now also check also check whether whether this this like the previous left elements are like the previous left elements are lesser or not right so if let's also run lesser or not right so if let's also run a while loop again a while loop again so the while loop will run till the ego so the while loop will run till the ego dot dot um dq dot um dq dot let's write empty let's write empty right let's write empty here while dq right let's write empty here while dq dot empty dot empty until unless not empty and also check until unless not empty and also check whether this dq dot back whether this dq dot back right this dq dot back and right this dq dot back and they should be indexed so numbs of they should be indexed so numbs of the q dot the q dot back back is less than equal to is less than equal to nums of highlight we are basically nums of highlight we are basically checking whether the previous elements checking whether the previous elements are lesser known if they are lesser than are lesser known if they are lesser than we don't need it anymore let's just we don't need it anymore let's just remove it from here so remove it from here so dp dp this should be dq right pq dot this should be dq right pq dot um um pop pop back back and and this while loop will just remove all the this while loop will just remove all the lesser element lesser element right and let's add our current index right and let's add our current index into the dq so dq dot into the dq so dq dot push back right and let's return the answer from here so return numbers of islam right we are just returning the last index of this nems array because this is storing the maximum value right so let's just yes working fine so let's just sum this yeah it's working fine so let's calculate the time and space complexity so the time complexity is big o of we write it here time complexity is because n because we are just traversing through all the n elements like we have already seen it here we just severed through all the n elements only once right only once that is the time complexity is big o of n and the space complexity is we go off and because we have stored at most n elements into this dq right so i hope the approach and solution is clear to you if you still have any doubt in this question so feel free to comment down please like this video and subscribe to our channel i will see you in the next you | 2024-03-20 14:28:40 | 1,696 | Jump Game VI | Deque 🔥| LeetCode Solution 1696 |
|
Iqu7lVWsyow | hi everyone welcome back to this channel I hope you guys are doing well today we I hope you guys are doing well today we are going to solve one of the famous are going to solve one of the famous lead chord problems spiral Matrix in lead chord problems spiral Matrix in this problem we have one mn2 and Matrix this problem we have one mn2 and Matrix and we need to retrieve all the elements and we need to retrieve all the elements in spiral order for example for this in spiral order for example for this Matrix we need to travel like this from Matrix we need to travel like this from this cell to this and again 2 to 3 and this cell to this and again 2 to 3 and then three to six and this way all the then three to six and this way all the way to 5. this problem can be solved in multiple ways but we are going to solve it using one of the graph traversal technique DFS or depth first search generally when we perform DFS on normal grade we are allowed to move either in four direction or eight direction for example suppose we have a cell we can go to right side we can go to down we can go to left side and we can go to ok I'll just name it but here we need to Traverse in One Direction till we reach the boundary for example we start from here and we go only in the right direction and from this cell only in the right direction but from this cell since we cannot go to the right direction obviously it will go out of grid so here we need to change the direction to downwards now interpret this with this four directional moves for example initially we only moved this direction and when we no longer able to move in the right direction we change the direction to down okay from here again will be going down now from here 9 again we cannot go further down since it will go out of boundary so we'll change the direction to left so here we went in down Direction till we can then we had to change the direction to left side okay so we have to Circle those Direction in other words we'll be going right direction till we can then we'll be changing the direction to down and then down to left and then left to upside and again upside to right okay so we'll be going like this and from here to here now from here we can go upset okay but we already visited that cell we cannot go in the up Direction so we must have to go to the right direction now we need a way to find out whether we can move in the same direction or we need to change the direction okay and we can do this either by maintaining a visited array or we'll change the cell value to some other value too so that this cell is visited now let's jump over to the code I'll be writing my solution in C plus plus but you can easily write in your own preferred programming languages okay so that should not be an issue first of all I'll write the so we'll be going right direction first so in right direction or x coordinate or I coordinate will not be changing and in the downward Direction ith value will increase by 1 and then left and then up similarly will be defined for y it will be so our Direction right down left up okay some prefer to write in pairs but that's okay also I'll declare two variables for dimension of our Matrix now let's so in this we would be needing our cell so in this we would be needing our cell position our current cell position that position our current cell position that is I and J in the direction and the is I and J in the direction and the direction means we'll take direction as direction means we'll take direction as an integer an integer and if this value is 0 meaning we are and if this value is 0 meaning we are moving in the right side if this Dr moving in the right side if this Dr value is 1 then we are moving in the value is 1 then we are moving in the downward Direction and so on and then downward Direction and so on and then obviously we will be needing our actual obviously we will be needing our actual Matrix and one more Vector we need to store The let's call it answer now when should we stop reversing when we visited all the Matrix elements and how can we identify that we can easily identify the Matrix contains M into M elements so after visiting all the elements the size of our answer Vector will be exactly M into n that will be our base condition size of our answer is m in 10 just return from here okay so that puts back Matrix I so that puts back Matrix I into J into J now I have taken the value of cell I now I have taken the value of cell I comma J we need to mark this cell as comma J we need to mark this cell as visited so that we do not visit it again visited so that we do not visit it again for that we already discussed about for that we already discussed about either you can maintain a visited array either you can maintain a visited array or we can change the cell value to or we can change the cell value to something else something else if we seen the problem if we seen the problem or Matrix cell value is ranging from or Matrix cell value is ranging from minus 100 to 100 okay minus 100 to 100 okay so we can mark it with something big so we can mark it with something big like 10 to the power 9 now we need to check if we can move into the next cell in the same direction or we need to change the direction so we'll change direction okay so we'll be giving the position of the dir don't worry I will implement this don't worry I will implement this function in a second when we will be function in a second when we will be changing the direction when this the changing the direction when this the next cell is invalid meaning either we next cell is invalid meaning either we are going out of bounds or the cell is are going out of bounds or the cell is already visited in those cases we'll be already visited in those cases we'll be changing the direction changing the direction so our new direction will be why we did it in this way because suppose we are moving in the upward and now we need to change the direction and so we'll be going in the right direction but here the index will be 3. if we just add one more into the direction it will go out of bounds and that does not make any sense so we need to modulo this with the length of this direction Vector so that it will give us next correct direction which is right in this case okay and then we'll make the call for next cell and that will be DFS and coordinate of our next cell will be I plus d i comma d comma dir or Direction and then Matrix vector and then answer okay now let's implement this change direction this will be our Boolean function so let's see the cases where our cell so let's see the cases where our cell will be invalid negative index will be invalid negative index or it I is greater than equal to m or J is less than 0 n and one final is Matrix a cell is already visited so I comma J equal to equal to this one we set this value to Market that the cell is visited so in these cases we need to change the direction okay let's finally Define our spiral order function so we need to determine the order of similarly in the cell similarly in the cell number of columns okay to store our cell values to store our cell values let's call it answer again let's call it answer again and and let's make a call to DFS function so let's make a call to DFS function so we'll start with the zero comma 0 and we'll start with the zero comma 0 and our initial direction will also be 0 and our initial direction will also be 0 and the norm the norm Matrix and then our answer array Matrix and then our answer array and then finally written our answer compiler error oh obviously so we'll just so we'll just Matrix now everything looks fine let's submit it our code did well in the time complexity since we are visiting every cell once so time complexity will be number of cell that is M into m as always thank you for watching this video please do like this video And | 2024-03-20 10:24:24 | 54 | Spiral Matrix -- LeetCode - 54 -- DFS |
|
JwWsTqMjcyw | so in this video we are going to solve wired card matching problem so suppose wired card matching problem so suppose if you have been given one string and if you have been given one string and you also have the pattern so you have to you also have the pattern so you have to say according to this pattern this say according to this pattern this string is matching or not string is matching or not so if you see here suppose a string is so if you see here suppose a string is SS SS and pattern is a and pattern is a so it will not match right so if you see so it will not match right so if you see here this is the a a and here is a on a here this is the a a and here is a on a so this a b match with this a but this so this a b match with this a but this complete is not matching so I can say complete is not matching so I can say this is the false right this is the false right another case if you see here but suppose another case if you see here but suppose if this is the history if this is the history and if this is your pattern a a also so and if this is your pattern a a also so you can say that you string a pattern you can say that you string a pattern matching so you can say that true take matching so you can say that true take another example it is very easy right another example it is very easy right this is string compression the thing this is string compression the thing here is the pattern but in the pattern here is the pattern but in the pattern we have the two very unique character we have the two very unique character one is the aesthetic and one is the one is the aesthetic and one is the question mark question mark question mark obviously present the any question mark obviously present the any character but only one character and character but only one character and that should not be empty that should not be empty so in this case if you see if your so in this case if you see if your string is a b and pattern is question string is a b and pattern is question mark and B it is true because here mark and B it is true because here question mark can represent as a and question mark can represent as a and then of course this B is B matching then of course this B is B matching right so in this case if this is the right so in this case if this is the this one so if this is the string and this is the pattern so of course b b match with b and a question mark represent any character right so it can be present a character also it will match your answer has the more unique compared to the has the more unique compared to the question mark some unique features so question mark some unique features so this asterisk can represent empty string this asterisk can represent empty string also that I've become to show you it can also that I've become to show you it can represent either only one character or represent either only one character or multiple character so means suppose if multiple character so means suppose if your string is in the case you can see your string is in the case you can see this one if your string is empty and this one if your string is empty and pattern is the Aztec you can see this is pattern is the Aztec you can see this is the true the true right and even suppose if you is this right and even suppose if you is this string is this one and pattern is just string is this one and pattern is just star if we match because star could be star if we match because star could be anything even it could be have the one anything even it could be have the one character character and or you can could have the any and or you can could have the any character character and due to this star this algorithm is and due to this star this algorithm is going to little bit tough compared to going to little bit tough compared to the other algorithms let me just fast the other algorithms let me just fast forward let me see the the few examples forward let me see the the few examples then you can jump into the solution so then you can jump into the solution so in this case CB is the string and in this case CB is the string and pattern is the star of course it will be pattern is the star of course it will be the two because star can represent the the two because star can represent the CB CB in this case in this case and we are going to take this example in and we are going to take this example in the our Solutions so if suppose steering the our Solutions so if suppose steering is a b c p q G is a b c p q G and your pattern is a question mark C and your pattern is a question mark C astric G so check whether this is the astric G so check whether this is the this we match or not so of course A B B this we match or not so of course A B B match with a match with a B we match with the question mark B we match with the question mark question mark can be present any question mark can be present any character character C of course is matching with the c and C of course is matching with the c and Easter Easter and this g g percent this G and this g g percent this G Then star can be present the p and Q and Then star can be present the p and Q and you can say this is the two you can say this is the two so it's matching another case so it's matching another case if the steering is same and this time if the steering is same and this time pattern is just a b c star not the G of pattern is just a b c star not the G of course a is matching B is matching with course a is matching B is matching with the question mark C is matching with the the question mark C is matching with the c and here e star we represent the all c and here e star we represent the all three character and U string is correct three character and U string is correct and another pattern nothing in the and another pattern nothing in the pattern only you have the star yes it pattern only you have the star yes it will match any character but now I am will match any character but now I am asking you if steering is this pattern asking you if steering is this pattern is this and if instead of the G suppose is this and if instead of the G suppose here is a p there here is a p there which returns that to no because this T which returns that to no because this T is not matching with the G here this is not matching with the G here this star will be present only the PQ but star will be present only the PQ but this ending character is not matching this ending character is not matching and wizard would be the force right so and wizard would be the force right so if this is the G here U it is 2 even if this is the G here U it is 2 even without G is also to only star is also without G is also to only star is also true true right again suppose if your string is right again suppose if your string is the empty string and pattern is question the empty string and pattern is question mark it is false because question mark mark it is false because question mark represent represent any one character but one character must any one character but one character must be there but in the empty there is no be there but in the empty there is no anything right so question mark will be anything right so question mark will be the false but if you have the this is the false but if you have the this is the string and this is the pattern it's the string and this is the pattern it's two because question mark represent two because question mark represent empty character also right but how it is empty character also right but how it is difficult right why you cannot do the difficult right why you cannot do the one one comparison and say I can do that one one comparison and say I can do that I am going to say why it is the complex I am going to say why it is the complex so if you see here so if you see here your string size could be anything and your string size could be anything and pattern size could be anything right so pattern size could be anything right so your string size could be of the 20 your string size could be of the 20 character but your pattern size could be character but your pattern size could be the any character less than equal 20 the any character less than equal 20 right or even it could be the pipe only right or even it could be the pipe only and that it could be two because St can and that it could be two because St can be present the multiple character at a be present the multiple character at a time right that's why it is going to the time right that's why it is going to the 80 bit complex here and another 80 bit complex here and another complexity what I am saying here suppose complexity what I am saying here suppose this is the history and suppose this is this is the history and suppose this is a pattern a pattern try to understand here now I am saying try to understand here now I am saying you whether this is correct or not so you whether this is correct or not so now you see if a is matching with the a now you see if a is matching with the a and B represent with the question mark and B represent with the question mark and now here C and now here C so when you confusion the C to C so when you confusion the C to C we cannot say to we cannot say to here here let me repeat my sentence again let me repeat my sentence again if you this first character matching if you this first character matching with the first character pattern I say with the first character pattern I say this is two this is two first character right first character right another character is matching IBC this another character is matching IBC this is two two second character is two two second character I don't know about the next character I don't know about the next character right now come the third character now she is C matching I can see two but now think even though c c is matching can I say to even though c c is matching can I say to you no because previous one is the first you no because previous one is the first even though C is matching it will not even though C is matching it will not make the two it will become the false so current index matching is depend upon the previous one so when you compare the this index if this is the clue if this is the two then you check the previous one if deviation was the two it will be true if this is the first previous one this is the false so this completion is based upon the two things one thing is that suppose this here was the C here was the suppose this here was the C here was the F it was not matching then I can F it was not matching then I can straight forward I can say this is the straight forward I can say this is the force but if it is match this index force but if it is match this index character character then you have to take the previous value then you have to take the previous value not the current we have you previous not the current we have you previous value that could be the two and that value that could be the two and that could be the force could be the force in this case suppose if it is was the f in this case suppose if it is was the f so a a was matching I can see to b f is so a a was matching I can see to b f is not matching I can say for c c is not matching I can say for c c is matching matching cc is matching what is the previous cc is matching what is the previous value false so this will be the false value false so this will be the false if suppose this is the question mark if suppose this is the question mark then this become the true then this become the true then cc is matching previous value 2 so then cc is matching previous value 2 so this is the two this is the two so to make this kind of the solutions we so to make this kind of the solutions we have to take the a very easiest way to have to take the a very easiest way to take the 2D Dimension so what I will do take the 2D Dimension so what I will do here here I will put the pattern here I will put the pattern here in this case pattern is a and here we take the string what is the String here a b c d f okay but important thing is that we have to leave one low also and the one column also so this values will be come from I will explain you so because why I shoot the wire should not start index 0 because we have to always depend upon so if you start your calculation on the so if you start your calculation on the index 0 then we don't have the minus 1 index 0 then we don't have the minus 1 index so you have to start all the index so you have to start all the calculation from the index one so you calculation from the index one so you will have the index 0 for this kind of will have the index 0 for this kind of the calculation so that I will detail uh the calculation so that I will detail uh no let me wrap the board and take the no let me wrap the board and take the example so suppose if you have the example so suppose if you have the string s and the pattern T and you can string s and the pattern T and you can see I have just given the indexing right see I have just given the indexing right so to solving the problem I will come so to solving the problem I will come across through the 2D dimension for the across through the 2D dimension for the Boolean so I will give the name of this Boolean so I will give the name of this 2DS the match and of course at the size 2DS the match and of course at the size of the this 2D would be one size greater of the this 2D would be one size greater than string so it will the low Y is the than string so it will the low Y is the string event so if you can say this is string event so if you can say this is my string my string so this is the string we go by and so this is the string we go by and column wise is the pattern so column wise is the pattern so I have given the pattern one one extra I I have given the pattern one one extra I have taken the event because as I have taken the event because as I discussed that I need go to the previous discussed that I need go to the previous one to fetch the value I so that's why I one to fetch the value I so that's why I have taken the extra one here so if you have taken the extra one here so if you see that my pattern would be start from see that my pattern would be start from index one and I kept one empty stick on index one and I kept one empty stick on the both on the pattern also and on the the both on the pattern also and on the string also I will detail you why I have string also I will detail you why I have kept that so this is my indexing for the kept that so this is my indexing for the pattern this is indexing from either pattern this is indexing from either string okay string okay so the beauty of this 2D so if you see so the beauty of this 2D so if you see that if you see here the empty empty that if you see here the empty empty would be match if it is match I will be would be match if it is match I will be presented to you so when I start up I presented to you so when I start up I algorithm by default I will make the two algorithm by default I will make the two for the uh this one and now if you see for the uh this one and now if you see this empties matching with the a it will this empties matching with the a it will not match the a so I can put the force not match the a so I can put the force here and also something I want to say here and also something I want to say you the beauty of this one if you say you the beauty of this one if you say the two two so what is the value of the two two so what is the value of match 2 2 it will become these two and match 2 2 it will become these two and these two I'm talking about this one these two I'm talking about this one so this value whether this is the 2 here so this value whether this is the 2 here Force here this box represent the Force here this box represent the pattern this one a and question mark and pattern this one a and question mark and this represent the string a b so if you this represent the string a b so if you see here the match 2 2 means see here the match 2 2 means still would be the a b t here what is still would be the a b t here what is the string a b here and what is the the string a b here and what is the pattern Q2 a question mark So this pattern Q2 a question mark So this represent the pattern matching or not represent the pattern matching or not matching for this particular value so if matching for this particular value so if you case if you see this is matching I you case if you see this is matching I will give the two that I will come will give the two that I will come across that just I want to show what is across that just I want to show what is the importance of this grid the importance of this grid when I save 4 or 3 that means till index when I save 4 or 3 that means till index of the 4 for the steering and T index of the 4 for the steering and T index for the pattern 3 so 4 up to p for the pattern 3 so 4 up to p and this is the box I am talking about and this is the box I am talking about right and here so so string would be a b right and here so so string would be a b c p and the pattern is still three a c p and the pattern is still three a question mark and C so this value question mark and C so this value whatever the value would be here that whatever the value would be here that will be represent the pattern matching will be represent the pattern matching field here field here I'm not talking about the full string so I'm not talking about the full string so if you suppose taking this one if you suppose taking this one this box so this box represent where this box so this box represent where your pattern matching for this string your pattern matching for this string and for this pattern and for this pattern this very present so I am going to play this very present so I am going to play one by one and see that and this value one by one and see that and this value this box this box will be present you this box this box will be present you complete string and the complete pattern complete string and the complete pattern is matching or not and this is your is matching or not and this is your final value if this is returning the final value if this is returning the true means your pattern is batching if true means your pattern is batching if this box returning the first your this box returning the first your pattern is not matching okay so now c pattern is not matching okay so now c one by one here so how we do that one by one here so how we do that so actually we will follow the three so actually we will follow the three logic here that logic is that first logic if or suppose if collector or suppose if collector does not match then we will use the force then no need to do anything I will represent the first means suppose if this one and this one is matching if this one this one is not matching I will say false first condition second condition if if it is match then we will see if it is match then we will see if character match then we take the if character match then we take the previous value previous diagonal value previous value previous diagonal value so it will be here previous value means suppose here if C and C is matching right in this case if C in C is matching so I will take the previous value what is the previous value before c this is value and before c this is the value right so if you are talking about this value this one this C and this C right we are talking about this one so if C and C is matching I will see the what is the previous value what is the previous value means before c this one and before c this B so this is the previous value I will take the value from here right that's why I say the previous value no so if this is the star is coming then take one example when then you can understand so suppose if I am taking the ABCD a b c p and pattern if you take the pattern a question mark C and asteric so in this case there are two possibilities what I will do first take the string adjectives and pattern consider the pattern acidic is not there because S2 could be the empty and see whether this is true or not first I will check this one to enforce second case you consider that this star is the P so you can remove the peep from the history so this case ABC and here and see whatever the value you both take the all and take the final value so in this case if you see here suppose this is the a b c p a b c p and the a question mark CQ a question mark CQ I am talking about this one right then take the first case I remove the then take the first case I remove the asterisk so if you're talking about this asterisk so if you're talking about this box you remove the asterisk means you box you remove the asterisk means you move the asterisk so you are talking move the asterisk so you are talking about then this one you are talking about then this one you are talking about the a question mark C a question about the a question mark C a question mark C and the string acbp means here so mark C and the string acbp means here so you are talking about this one this box and for another case you remove this p and you are talking about this box so I will check this box this box and make the all condition that is for the aesthetic okay let me see the example foreign and we represent the pattern is equal to and string row Y is the I so I make the and string row Y is the I so I make the two for you one for the I start from the two for you one for the I start from the S string so your wise and then the four S string so your wise and then the four J is a pattern wise that's why this is J is a pattern wise that's why this is the S7 and this is the prevent the S7 and this is the prevent and of course let me do the first then and of course let me do the first then because I have started the form one and because I have started the form one and one so we first compute the Zero part one so we first compute the Zero part then this code will be start right by then this code will be start right by default on the Zero Geo will put the two default on the Zero Geo will put the two because obvious this empty MTV Match so because obvious this empty MTV Match so I put the two now this empty and this a I put the two now this empty and this a is not matching so anyhow if you guess is not matching so anyhow if you guess this one this one means your string this one this one means your string string and pattern is the a so it is not string and pattern is the a so it is not matching your pattern is the MTA matching your pattern is the MTA it is not matching so I will give the it is not matching so I will give the first the same case it is a false false first the same case it is a false false here also false here so because in here here also false here so because in here what is that your string is e and the what is that your string is e and the pattern is empty a question mark C pattern is empty a question mark C obvious it is not matching I will put obvious it is not matching I will put the first In Here Also first and the the first In Here Also first and the same case if your pattern is empty it same case if your pattern is empty it will not match any one here so I will will not match any one here so I will return the force return the force so before starting the code we have to so before starting the code we have to fill this zeroth zeroth column and the 0 fill this zeroth zeroth column and the 0 because my uh would be start from the 1 because my uh would be start from the 1 1 why could we start from here right 1 why could we start from here right now I'm saying that if now I'm saying that if P pattern J minus 1 why I did the J P pattern J minus 1 why I did the J minus 1 because it is J star from the minus 1 because it is J star from the one and pattern if you see here so J one and pattern if you see here so J minus 1 is 0 so I have to start from minus 1 is 0 so I have to start from zero the and this is start from the one zero the and this is start from the one that's why I always given the minus one that's why I always given the minus one minus one right so if you see if this is minus one right so if you see if this is the if this one p and this is as if it the if this one p and this is as if it is matching I am talking about this box is matching I am talking about this box right so because i1 J1 i1 and this is right so because i1 J1 i1 and this is the one so I'm talking about this box the one so I'm talking about this box right if this is matching or pattern is right if this is matching or pattern is a question mark then you put the value a question mark then you put the value of the I minus 1 and J minus 1 so if if of the I minus 1 and J minus 1 so if if you here if a a is matching then I minus you here if a a is matching then I minus 1 J minus 1 what is I right now 1 and 1 J minus 1 what is I right now 1 and what is the J one so I minus 1 0 J minus what is the J one so I minus 1 0 J minus 1 0 so what is the value of J what is 1 0 so what is the value of J what is the value of Max jio is the two so it the value of Max jio is the two so it will come from here and so I can make will come from here and so I can make the 2 here the 2 here and we have already discussed that if it and we have already discussed that if it is matching if we take the previous is matching if we take the previous value now value now it will go up and this time I is equal it will go up and this time I is equal to 1 J is equal to 2 right I Square 2 1 to 1 J is equal to 2 right I Square 2 1 J is equal to 2. so now in this case J is equal to 2. so now in this case pattern is 1 and this is the zero right pattern is 1 and this is the zero right so now and right or not yes so now if this is the now this is the and we are here talking about this box so my pattern is my pet in for this box my pattern is the A and question mark and string is the a right so you have to check right now so it is matching or not because J is equal to 2 and this is the zero this is the one so in the case if no right time G is equal to 2 so this is a 2 minus 1 1 so I'm talking about this one and I is still one so one minus G one zero so this one this one I'm talking about this box and I'm talking about this box so it is asking that if both are matching or the G minus 1 is the question mark yes G minus 1 question mark if this is the case then you take the previous value so we will take the previous value here so it will become the false this is not matching at all so make the this is not matching at all so make the first but this time we make the Force first but this time we make the Force form it was not matching and the force form it was not matching and the force was already there so when you create the was already there so when you create the 2D Dimension or the value is equal to 2D Dimension or the value is equal to false so it will contain the force so false so it will contain the force so now to move forward that now this is the now to move forward that now this is the A and this is the streak right now the A and this is the streak right now the S3 case is there so in the St case what S3 case is there so in the St case what I have to see we have to see this value I have to see we have to see this value or this value if one of the two I will or this value if one of the two I will put the two but both are the first so I put the two but both are the first so I am going to make it the force so this is am going to make it the force so this is the force the force and of course A and G is not matching I and of course A and G is not matching I will make the false now come here b or a will make the false now come here b or a is not matching give the first B and is not matching give the first B and question mark So this condition so you question mark So this condition so you have to take the have to take the previous one previous one is equal to 2 previous one previous one is equal to 2 so make the two B and C is not matching so make the two B and C is not matching give the false b and s t again I will give the false b and s t again I will take this value and this value both all take this value and this value both all false so it will become the force B and false so it will become the force B and G is not matching give the force c c a G is not matching give the force c c a is not matching no problem give the is not matching no problem give the false see question mark this condition false see question mark this condition so then you have to take the C question so then you have to take the C question mark you have to take the previous value mark you have to take the previous value right figure is equal to false so let's right figure is equal to false so let's go to the false go to the false and then cc is matching if it is and then cc is matching if it is matching then take the previous value so matching then take the previous value so for this this is the previous value so for this this is the previous value so this 2 I will take the two c and this 2 I will take the two c and question mark So in this case C and St question mark So in this case C and St so take the both or here is the force so take the both or here is the force here is equal to 2 then take the two here is equal to 2 then take the two e e sorry C and the g is not matching put sorry C and the g is not matching put the first p and the a not matching give the first p and the a not matching give the first p and question mark this the first p and question mark this condition to take the previous value condition to take the previous value false p and c not matching give the false p and c not matching give the force p and the stick so again previous force p and the stick so again previous previous this one and this one is equal previous this one and this one is equal to 2 you can see if once U we get the 2 to 2 you can see if once U we get the 2 for Star it will be the continuous star for Star it will be the continuous star continuous two continuous two so now p and the g not matching put the so now p and the g not matching put the Force Q and A not matching give the Force Q and A not matching give the Force Q question mark this condition Force Q question mark this condition take the previous value false q and the take the previous value false q and the C not matching give the false q and the C not matching give the false q and the star take both of the all this is the star take both of the all this is the two because one of the value in this two because one of the value in this value this value one is for 2 so put the value this value one is for 2 so put the two Q and G is not matching give the two Q and G is not matching give the force G and a not matching give the force G and a not matching give the false G question mark this condition false G question mark this condition take the previous value G and the C not take the previous value G and the C not matching give the false G and star this matching give the false G and star this one and this one to G and G is matching one and this one to G and G is matching and get the two so the moment you get and get the two so the moment you get the two this is your final result it the two this is your final result it means that this pattern this string at means that this pattern this string at this pattern is matching this pattern is matching right so that's why this was the now we right so that's why this was the now we see in the code how it works but one see in the code how it works but one more time I want to explain that if you more time I want to explain that if you come any particular point if you suppose come any particular point if you suppose take this example too that means take this example too that means from here that means this is string come from here that means this is string come here and this pattern must be matching here and this pattern must be matching you can see this is the ABC and here the you can see this is the ABC and here the a question mark C right both are the a question mark C right both are the correct so this represent the column correct so this represent the column into those value right let me so but we into those value right let me so but we have the one corner case if suppose you have the one corner case if suppose you have the S3 only right only the asterisk have the S3 only right only the asterisk in the pattern so if you make this one in the pattern so if you make this one so this will be the your pattern on it so this will be the your pattern on it this is the empty St and here if you see this is the empty St and here if you see this is your uh this is your empty this is your uh this is your empty string here and you have the a and a string here and you have the a and a right so in that case right so in that case this by default is to you then this by default is to you then if if before asterisk if anything is true you before asterisk if anything is true you have to make the two to satisfy this have to make the two to satisfy this condition of the this kind of the corner condition of the this kind of the corner case otherwise it will give the false so case otherwise it will give the false so when you make this match DP in that we when you make this match DP in that we have to first view this have to first view this rho and this column keeping this rho and this column keeping this condition in the mind that I will show condition in the mind that I will show in the code in the code so first what you have to do we have to so first what you have to do we have to create one two dimension I will give the match name and anything you can give version and as we discussed that rent would be the one character mode of the string and one character mode of the atom so in event plus one and here better plus one okay and by default we will first make the this index 0 and 0 and you have to give up the first and you have to give up the first row keeping the conditions that I will row keeping the conditions that I will explain you so in the case suppose your explain you so in the case suppose your s is equal to a a and s is equal to a a and pattern is only a stick so just just pattern is only a stick so just just feel free for this condition we have to feel free for this condition we have to make the row figure so obvious if we make the row figure so obvious if we start from the start from the one because I I have already taken the one because I I have already taken the jio so I will start from the one and it jio so I will start from the one and it will go equal to the pattern event right will go equal to the pattern event right we are going for the zero wise right so we are going for the zero wise right so only the first view so it will go and only the first view so it will go and then I plus plus and here if we check then I plus plus and here if we check means in the match we have three only means in the match we have three only the first row means this is the first the first row means this is the first two right and the Comm is equal to I so two right and the Comm is equal to I so I will check if I will check if if previous we have you I minus 1 is equal to true pattern is at the I minus 1. right pattern is at the I minus 1. right you're getting my point right the If the you're getting my point right the If the previous character and why I am getting previous character and why I am getting the character I minus 1 because my index the character I minus 1 because my index is starts from the one so if that is the is starts from the one so if that is the static so that's it so if this is the static so that's it so if this is the two keep the two if this is the first two keep the two if this is the first keep the whole fall first right so now keep the whole fall first right so now we're done now if you go the first entry we're done now if you go the first entry for the for the First Column right so I will start from First Column right so I will start from the what am I talking about so I because you have already given the uh zero index so this we are giving the First Column so compute the S right so it is the s dot length of course equal because we are taking the from the one and then I plus plus and here I will keep the complete I and jio because I'm talking about the First Column I will return the force because only the first is the two otherwise you're fitting the force now our logic will start and the logic we start from the one right and first is the row y so I will take the S3 Dash Dot and now take another one is the column and now take another one is the column wise right so G is equal to 1 and of wise right so G is equal to 1 and of course and then J plus plus and then J plus plus if the first condition if your s character at the I minus 1 because string is the I J minus 1 if both are matching right if J minus 1 if both are matching right if both are matching then uh whatever do if both are matching then uh whatever do if both are matching both are matching here and or your P dot character is equal to star in both case we have to take the question mark So in both case we have to take the previous value so what is the previous value match I and J equal to equal to match I minus J minus a right then what you have to do then what you have to do match I and J equal to is from the up match I and J equal to is from the up and underapped from the website in and underapped from the website in upside if it is any one to IB take the upside if it is any one to IB take the two so first case I will make the minus two so first case I will make the minus I minus 1 keep the J intact or I minus 1 keep the J intact or next time keep the eye intact and the J next time keep the eye intact and the J minus one if any condition that I may minus one if any condition that I may take it and this is the false is here take it and this is the false is here and this method and here will be Vita on and this method and here will be Vita on the above the last Index right the above the last Index right so match so match s dot length s dot length this is the last this from where from this is the last this from where from the right bottom right so p the right bottom right so p length this is length this is the code let me just run and check the code let me just run and check whether it's working or not it's working fine right so now it's working fine and take some different examples to one in my case what we have taken that a b c p q G and it was the a question mark B and see that style G this is also working so it is giving the this is also working so it is giving the first because we because we have to give first because we because we have to give the a b is matching if you give the the a b is matching if you give the C and then it should work too right okay these two what I have given the first case because this is the corner case suppose suppose you have the 2A here and if you have given the s t right so now if you can see it is working fine it is giving the two but you if you remove this part is true now suppose if you are not keeping giving this part and try to run it will give the false that's why the first we we taken the corner case for the first one right so this is the first feature that's why you need to put this condition just for this corner cases so now everything is working let me submit this code and see how it works submit the code this would work because I have already tested here so this is accepted right so thank you very much please don't forget to subscribe and like the channel thank | 2024-03-20 09:26:23 | 44 | Wildcard Matching | Explanation on WhiteBoard | Leetcode # 44 |
|
8iUFLUIeK9k | hi guys welcome to algorithms made easy in this video we'll go through the in this video we'll go through the question keys and rooms question keys and rooms there are n rooms and you start in room there are n rooms and you start in room 0. 0. each room has a distinct number 0 to n each room has a distinct number 0 to n minus 1 and each room may have some keys minus 1 and each room may have some keys to access the next room to access the next room formally each room i has a list of keys formally each room i has a list of keys letters letters given in an array form rooms of i and given in an array form rooms of i and each key each key is an integer in 0 to n minus 1 is an integer in 0 to n minus 1 where n equal to rooms dot length or the where n equal to rooms dot length or the length of this particular array that is length of this particular array that is given to us or the list that is given to given to us or the list that is given to us us a key room of i j is equal to v opens a key room of i j is equal to v opens the room the room that is numbered v initially all the that is numbered v initially all the rooms start rooms start locked except for room 0. you can walk locked except for room 0. you can walk back and forth between rooms freely and back and forth between rooms freely and you need to return to if and only if you you need to return to if and only if you can enter can enter every room so in the example one we can every room so in the example one we can say that in room 0 we have the key to say that in room 0 we have the key to room 1 room 1 in room 1 we have the key to room 2 room in room 1 we have the key to room 2 room 2 we have key to room 3 2 we have key to room 3 so we can go through each and every room so we can go through each and every room which is which is 0 to 3 and so the output is true in this 0 to 3 and so the output is true in this case case while for example 2 you can see that while for example 2 you can see that from the room 0 you can either go to from the room 0 you can either go to room 1 room 1 and 3 and in room 1 you have the key to and 3 and in room 1 you have the key to either room either room 3 0 or 1 and in room 3 you have the key 3 0 or 1 and in room 3 you have the key to to room 0 but there is no way you can get room 0 but there is no way you can get the the key for room 2 because that key is key for room 2 because that key is already placed in the room 2 already placed in the room 2 and so we cannot enter that room and so and so we cannot enter that room and so we return false we return false so that's all about the problem so that's all about the problem statement now let's go ahead and look statement now let's go ahead and look how we can solve this question how we can solve this question let's take this example where we have let's take this example where we have these three rooms these three rooms that we need to visit so now first you that we need to visit so now first you will go and enter room one will go and enter room one now room one has the key for room two now room one has the key for room two so what you do is you need to mark this so what you do is you need to mark this room as visited and you will go to the room as visited and you will go to the room 2. room 2. while you go to the room 2 say you have while you go to the room 2 say you have these two keys these two keys one is to the room one and second is to one is to the room one and second is to room three so since you have visited room three so since you have visited this room one or you this room one or you already have the key to room one you already have the key to room one you would not would not need that key again you can just take need that key again you can just take the key to this the key to this third room and go ahead in the third third room and go ahead in the third room room say you have the key to room one so now say you have the key to room one so now do you need this key no because you do you need this key no because you already have the key already have the key to room one and so you just mark this as to room one and so you just mark this as visited visited and now all the rooms or all the list and now all the rooms or all the list that was given to us is traversed that was given to us is traversed and we would now need to check whether and we would now need to check whether all the rooms have been visited or not all the rooms have been visited or not so with the ticks that are shown here we so with the ticks that are shown here we can say that all the rooms that can say that all the rooms that were there are already visited and so we were there are already visited and so we can return true in this case can return true in this case for example if any of this stick was not for example if any of this stick was not there there then we could have returned false so then we could have returned false so what do we need to do in this particular what do we need to do in this particular case case we would need a boolean array to mark we would need a boolean array to mark whether a room is visited or not so that whether a room is visited or not so that would be of length rooms dot length or would be of length rooms dot length or n secondly we would need to recursively n secondly we would need to recursively call call a function that would collect all the a function that would collect all the keys that are being there keys that are being there in a room and would be going in a room and would be going into the next room according to the into the next room according to the condition condition of whether the room is visited or not of whether the room is visited or not visited visited with these two things we can actually with these two things we can actually solve this question solve this question so let's go ahead and write some code so let's go ahead and write some code for it for it so the first thing that we are going to so the first thing that we are going to need is a boolean array so let me take a need is a boolean array so let me take a class level variable so that we can class level variable so that we can access it everywhere access it everywhere and the length of this visited array and the length of this visited array would be would be the length of the rooms that is given to the length of the rooms that is given to us us and now since we were already having a and now since we were already having a key for room 0 key for room 0 we can mark that as visited we can mark that as visited after this we'll just call dfs on our after this we'll just call dfs on our rules rules and starting with the zeroth index once and starting with the zeroth index once this dfs function is complete we'll this dfs function is complete we'll check check whether any of the room is still whether any of the room is still unvisited or not unvisited or not so we'll check for each value in the so we'll check for each value in the boolean array boolean array and if this is not and if this is not true we return false true we return false otherwise we can just return true otherwise we can just return true now we need to just write the dfs now we need to just write the dfs function so that would be function so that would be so this is rooms and this is index we so this is rooms and this is index we are starting with index 0. are starting with index 0. so now as we know that at a particular so now as we know that at a particular index we would be having a list of index we would be having a list of integers we would need to iterate over integers we would need to iterate over each one of them each one of them so let's write a for each loop if this particular iath room is already visited that is if visited of this i is already true we do not need to do anything but if this is not visited in that case and apart from that we need to call dfs and apart from that we need to call dfs on rooms and on this iath room on rooms and on this iath room so that's it let's just try to run this so that's it let's just try to run this code code and see whether it works and let's and see whether it works and let's quickly resolve all the errors and it's quickly resolve all the errors and it's giving giving a perfect result let's try to submit a perfect result let's try to submit this this and it got submitted so the time and it got submitted so the time complexity complexity over here would be the number of rooms over here would be the number of rooms that we are going to visit that we are going to visit since we are not visiting each and every since we are not visiting each and every room that was previously visited room that was previously visited we will just say that the effective time we will just say that the effective time complexity would be complexity would be equal to number of rooms but in worst equal to number of rooms but in worst case we can say that it case we can say that it could go up to o of rooms plus the could go up to o of rooms plus the number of keys that we have number of keys that we have so this is the dfs way of doing this so this is the dfs way of doing this question you can also do it iteratively question you can also do it iteratively by using a bfs method wherein you will by using a bfs method wherein you will be using a queue be using a queue the logic behind it remains the same the logic behind it remains the same that you need to that you need to mark the room as visited whenever you mark the room as visited whenever you are taking that key are taking that key and at the end you need to just iterate and at the end you need to just iterate over this visited array to check whether over this visited array to check whether any of the rooms is still not visited so any of the rooms is still not visited so that's it for today guys i hope you like that's it for today guys i hope you like the video and i'll see you in another the video and i'll see you in another one one till then keep learning keep coding till then keep learning keep coding [Music] | 2024-03-22 16:00:42 | 841 | Keys and Rooms | Live Coding with Explanation | Leetcode - 841 |
|
H1-Ka5Ob2kc | now let's go over the code question number 1725 number 1725 number of rectangles that can form the number of rectangles that can form the largest largest square now the question says you're square now the question says you're given an array given an array rectangle is at index i represents the i rectangle is at index i represents the i rectangle at length and width so this is rectangle at length and width so this is length and this is good you can cut the length and this is good you can cut the eighth eighth rectangle to form a square with a size rectangle to form a square with a size length length of k if both k is less than or equal to of k if both k is less than or equal to length or k is less than or equal to the length or k is less than or equal to the width so for example if you have a width so for example if you have a rectangle rectangle 4 6 you can cut it to get a square 4 6 you can cut it to get a square with a side length of at most four with a side length of at most four and if you don't know what square is and if you don't know what square is squares should have all squares should have all same size when you have a rectangle that same size when you have a rectangle that looks something like this let's say that looks something like this let's say that this is four this is four and this is six in order for us to get a and this is six in order for us to get a square we have to cut this by length of square we have to cut this by length of two and this will have a length of four two and this will have a length of four this would have four this would have four and four and so forth so squares should and four and so forth so squares should have all same size have all same size so from this rectangle the largest so from this rectangle the largest square that we can make square that we can make is this four by four square that next is this four by four square that next length be the side length be the side length of the largest square you can length of the largest square you can obtain from the given rectangle obtain from the given rectangle so that would be four in our case return so that would be four in our case return the number of rectangles that can make the number of rectangles that can make this square this square with side length of max len okay with side length of max len okay now let's look at our example so for now let's look at our example so for example we have example we have this as our input array and remember this as our input array and remember that each one that each one represents a rectangle so we have four represents a rectangle so we have four rectangles here now you have to figure rectangles here now you have to figure out what out what the maximum square we can make out of the maximum square we can make out of this this each and individual rectangle so for the each and individual rectangle so for the first one it's going to be 5 first one it's going to be 5 because we can't make a square that's because we can't make a square that's greater than 5 right because our length greater than 5 right because our length is is 5. and for this one it's going to be 3. 5. and for this one it's going to be 3. this is going to be five this is going to be five and this is going to be five now what and this is going to be five now what they want us to do is you want to first they want us to do is you want to first get the maximum square and then it wants get the maximum square and then it wants us to return the count of maximum us to return the count of maximum squares so what's the maximum square squares so what's the maximum square here well here well it's going to be five right because we it's going to be five right because we have five three have five three five and five and five is the biggest five and five and five is the biggest size size and how many fives do we have we have and how many fives do we have we have one one two and three so our result is going to two and three so our result is going to be three because we be three because we have three size five rectangles have three size five rectangles now let's look at our example two so now let's look at our example two so what's the maximum square that we can what's the maximum square that we can get for each get for each rectangle it's going to be two here it's rectangle it's going to be two here it's going to be three here it's going to be going to be three here it's going to be three here three here there's going to be 3 here and what's there's going to be 3 here and what's the maximum square out of this whole the maximum square out of this whole rectangles that's going to be 3 right rectangles that's going to be 3 right because 2 is smaller than 3 because 2 is smaller than 3 and how many 3s do we have we have 1 2 and how many 3s do we have we have 1 2 and 3. so our result and 3. so our result again is going to be same as before 3. again is going to be same as before 3. now using this logic we can try to solve now using this logic we can try to solve this problem in two ways this problem in two ways first thing i can think of is you can first thing i can think of is you can try to store try to store the max square into an object the max square into an object and then get the count for each and and then get the count for each and lastly lastly return the count of biggest return the count of biggest square and the second will be more square and the second will be more optimal because optimal because for this solution you won't have to make for this solution you won't have to make it object to store the it object to store the count of the squares well instead of count of the squares well instead of counting counting the number of max scores that we get the number of max scores that we get what we can do is we can just track what we can do is we can just track which one is which one is the largest and if it is the largest and the largest and if it is the largest and then second then second keep a count of the keep a count of the largest square so using these two logics largest square so using these two logics try to implement your solution try to implement your solution first of all would be to create an first of all would be to create an object to store object to store the count of each square that we get the count of each square that we get and next what we can do is well you and next what we can do is well you don't really have to make an object don't really have to make an object so just check which square is the so just check which square is the largest and then largest and then keep the count of the largest square keep the count of the largest square only only so this will be giving us a space so this will be giving us a space complexity of oven complexity of oven because you might have to create an because you might have to create an object that's equal to the size of the object that's equal to the size of the input but for this one input but for this one we just have to keep this one variable we just have to keep this one variable that's where it's going to keep the that's where it's going to keep the count count of the largest if you guys find this of the largest if you guys find this helpful make sure you guys like helpful make sure you guys like and subscribe thanks and subscribe thanks now let's go over our first solution and now let's go over our first solution and our first solution is going to have a our first solution is going to have a time and space complexity time and space complexity of o-o-ven later we are going to of o-o-ven later we are going to actually actually optimize our space complexity but let's optimize our space complexity but let's first code this solution because i think first code this solution because i think it's it's easier to understand and time complexity easier to understand and time complexity will be oh will be oh then because we will have to iterate then because we will have to iterate through all the elements through all the elements in our given array so first thing i'm in our given array so first thing i'm going to do is i'm going going to do is i'm going to create a variable named output and to create a variable named output and this this is going to be an object and here what is going to be an object and here what we're going to do is we're going to we're going to do is we're going to store store our keys which is going to represent the our keys which is going to represent the squares squares and values which is going to represent and values which is going to represent the count of the squares and later the count of the squares and later we are going to get the maximum key and we are going to get the maximum key and then then return the count of that largest return the count of that largest score that we have so i cream i'll put score that we have so i cream i'll put the store on my result the store on my result and i'm going to create a for loop and and i'm going to create a for loop and let's just create a for let's just create a for overloop and for each rectangle and overloop and for each rectangle and rectangles rectangles array what i'm first going to do is i'm array what i'm first going to do is i'm going to find the going to find the square so let's just call this men or square so let's just call this men or you can just call it square let's call you can just call it square let's call it square and i'm going to set this it square and i'm going to set this equal to math equal to math dot min square operator rectangle dot min square operator rectangle and what this does is if you were to and what this does is if you were to just console log square you can see that just console log square you can see that it's giving us the square for each it's giving us the square for each rectangle that we have so largest square rectangle that we have so largest square that we can make out of the first one that we can make out of the first one is five second one is three five and is five second one is three five and five five and that's exactly what we have so we and that's exactly what we have so we now have our now have our squares but what we need to handle is squares but what we need to handle is you want to put these squares you want to put these squares into our output object and count into our output object and count how many of the squares we have so first how many of the squares we have so first let's check so if let's check so if the output does not have the square the output does not have the square what i'm going to do is i'm going to what i'm going to do is i'm going to give a value of give a value of zero if it's the other case so we zero if it's the other case so we initialize it with initialize it with a value of zero and then we increment a value of zero and then we increment the output by one it's not output it's the output by one it's not output it's output at square okay now let's just output at square okay now let's just console log our output console log our output and we have a count of our and we have a count of our object or squares let's just call some object or squares let's just call some log here so you can see that we have log here so you can see that we have one square because we have a value of one square because we have a value of one that has a one that has a size of three and three squares that has size of three and three squares that has a size of five a size of five and if you were to just cause a lot of and if you were to just cause a lot of squares again here you can see that we squares again here you can see that we have three fives have three fives and one three so it's looking good so and one three so it's looking good so far far now what we need to do is we need to be now what we need to do is we need to be able to get the maximum square able to get the maximum square and our output so i'll call it max and our output so i'll call it max and we are going to use math.max and we are going to use math.max to get the maximum value and we're going to get the maximum value and we're going to use the spread operator to use the spread operator and dot keys to get all the keys in the and dot keys to get all the keys in the object object and pass in our output object and let's and pass in our output object and let's just console log just console log our max square and it should give us a our max square and it should give us a five five right because we have only threes and right because we have only threes and fives fives we got our maximum square but now we we got our maximum square but now we need to need to return the count of the return the count of the largest square which in our case is largest square which in our case is going to be three going to be three so how do we do that well how do we so how do we do that well how do we access access a key or a value in an object well a key or a value in an object well we do that by first we're going to we do that by first we're going to return because that's going to be our return because that's going to be our result result output at key max and output at key max and that should give us three which we got that should give us three which we got because again because again we have five threes which is the largest we have five threes which is the largest square and let's just uncomment our square and let's just uncomment our second second input we have three here three here input we have three here three here three here three here and a two here so maximum or the largest and a two here so maximum or the largest square is three and how many square is three and how many threes do we have we have three of those threes do we have we have three of those so that's why we get so that's why we get three so this is our first solution three so this is our first solution again i think this is again i think this is really easy to understand but let's try really easy to understand but let's try to later optimize our code so that we to later optimize our code so that we can see can see some space now let's go over our second some space now let's go over our second solution where we optimize our space solution where we optimize our space complexity complexity if you remember from before we had a if you remember from before we had a space complexity space complexity of all of n and the reason was because of all of n and the reason was because we had an we had an object to store our key value pairs object to store our key value pairs where key represented the square where key represented the square and value represented the count of and value represented the count of that square but here what we're going to that square but here what we're going to do is we're just going to keep two do is we're just going to keep two variables where one tracks variables where one tracks the largest square and another one the largest square and another one tracks the tracks the count of that largest square so having count of that largest square so having two variables we are able to save two variables we are able to save some space so given that now let's start some space so given that now let's start coding coding so first i'm going to create two so first i'm going to create two variables one is called the max and this variables one is called the max and this is going to be the is going to be the largest square that i'm going to have largest square that i'm going to have and and another one is going to count and this another one is going to count and this is going to keep track of is going to keep track of how many largest square that i'm going how many largest square that i'm going to have to have let's use a 4 overloop and it's going to let's use a 4 overloop and it's going to look similar look similar let's switch things up a little we want let's switch things up a little we want to have to have length and we are going to have width length and we are going to have width for the second one so what we're here for the second one so what we're here doing is we're just destructuring our doing is we're just destructuring our array array and if you don't know how that works and if you don't know how that works i'll show it to you really soon so i'll show it to you really soon so rectangles rectangles okay now if i were to just console log okay now if i were to just console log length and length and console.log width you can see that console.log width you can see that length represents the first value so 5 length represents the first value so 5 3 5 16 and so on and so forth and with 3 5 16 and so on and so forth and with represents 8 9 12 and 5. so this is a represents 8 9 12 and 5. so this is a way to way to name the first element in the array this name the first element in the array this is the name of the second element in the is the name of the second element in the array or you could just don array or you could just don rectangles for this motion if you like rectangles for this motion if you like it doesn't really matter it doesn't really matter so now what i'm going to do is i'm going so now what i'm going to do is i'm going to find my square to find my square and this is going to look similar to our and this is going to look similar to our previous one previous one it should be min because it can't be the it should be min because it can't be the bigger than bigger than the smallest size that we have so we are the smallest size that we have so we are going to pass going to pass in length and width and if you want you in length and width and if you want you could just do the same thing as before could just do the same thing as before where you pass rectangle here where you pass rectangle here and then just use sprout operator and and then just use sprout operator and pass in our rectangle and if you were to pass in our rectangle and if you were to just constantly log r square you can see just constantly log r square you can see that that we have our squares right so so for the we have our squares right so so for the first one it's going to be 5 first one it's going to be 5 3 five and five now what we need to do 3 five and five now what we need to do is we need to check well if my is we need to check well if my current square if my current square is current square if my current square is greater than my maximum square that greater than my maximum square that means that i need to change my maximum means that i need to change my maximum square to the current mode right square to the current mode right so we are going to set max equal to so we are going to set max equal to square so we square so we are replacing our maximum square here are replacing our maximum square here and then there's one more thing what we and then there's one more thing what we have to do is we need to increment the have to do is we need to increment the count so we're going to set count equal count so we're going to set count equal to one okay that looks good to one okay that looks good and another thing is if our square and another thing is if our square is equal to the current maximum square is equal to the current maximum square what do you have to do you have to what do you have to do you have to increase the count by one increase the count by one so let's say that we were passing a so let's say that we were passing a value of five value of five well first is square equal to max well well first is square equal to max well our max is negative our max is negative infinity for now so that evaluates to infinity for now so that evaluates to false so we skip false so we skip is square greater than five well five is is square greater than five well five is greater than maximum greater than maximum which is negative infinity so what we do which is negative infinity so what we do is we reset is we reset maximum to our current square which is maximum to our current square which is five set five set count to one and then next what's our count to one and then next what's our square our square is three square our square is three well is square greater than three no well is square greater than three no right so we just right so we just keep looping and then our square is 5 keep looping and then our square is 5 again again well is our square equal to max well it well is our square equal to max well it is because is because at first our square became 5. so we at first our square became 5. so we increment our count increment our count to 2 so this evaluates to two now and to 2 so this evaluates to two now and then then next we go to the next one and have next we go to the next one and have another five another five and square is equal to our max so we and square is equal to our max so we increase our count by one again increase our count by one again so after we're done we just want to so after we're done we just want to return our result right which is going return our result right which is going to be stored to be stored in our count variable so there you have in our count variable so there you have it uh we have our result of three it uh we have our result of three and let's check for the second one and and let's check for the second one and second one also gave us a result of second one also gave us a result of three now using the same logic that we three now using the same logic that we used before used before i want to go over this solution one more i want to go over this solution one more time but we are going to use reduce time but we are going to use reduce for this one well the code itself is for this one well the code itself is actually going to look really similar actually going to look really similar but i think it's good to practice but i think it's good to practice solving questionnaire in a little bit solving questionnaire in a little bit different way and here we can just different way and here we can just practice using reduce too practice using reduce too so same as before first thing i'm going so same as before first thing i'm going to do is i'm going to set to do is i'm going to set my max to negative infinity and then my max to negative infinity and then here i'm going to use here i'm going to use videos so rectangles videos so rectangles dot reduce and here i'm going to pass in dot reduce and here i'm going to pass in two things my accumulator two things my accumulator and my current value and i'm going to and my current value and i'm going to give an initial value give an initial value of zero and our that means that our of zero and our that means that our accumulator is going to be accumulator is going to be zero right and later i'm going to return zero right and later i'm going to return my accumulator my accumulator and this is actually going to store the and this is actually going to store the count of the largest square that we are count of the largest square that we are going to have going to have the same as before what i want to do is the same as before what i want to do is i want to get the i want to get the squared so square is equal to math.min squared so square is equal to math.min and let's just actually rename this to and let's just actually rename this to rectangle rectangle and we are going to pass in a rectangle and we are going to pass in a rectangle and let's just console log square and let's just console log square you can see that we have our largest you can see that we have our largest square square for each rectangle now let's just get for each rectangle now let's just get rid of that rid of that and same as before we need to have some and same as before we need to have some if statements to check so if if statements to check so if square is the same size as our max square is the same size as our max what do you want to do we want to what do you want to do we want to increase our count right but here we increase our count right but here we don't have a count don't have a count instead we are going to have an instead we are going to have an accumulator that's going to keep the accumulator that's going to keep the count count and we can just actually rename this to and we can just actually rename this to count if you want count if you want but i want to just leave it like this but i want to just leave it like this for now and we're going to increment our for now and we're going to increment our count or accumulator by one and next we count or accumulator by one and next we need to check need to check well there's the current square greater well there's the current square greater than our maximum than our maximum square that we stored well if it is we square that we stored well if it is we want to want to reset our maximum square the first reset our maximum square the first to the current square and then set to the current square and then set accumulator to accumulator to one and we're actually done so one and we're actually done so everything inside the reduce function everything inside the reduce function looks the same it's just that we have an looks the same it's just that we have an accumulator accumulator and instead of using a for loop we just and instead of using a for loop we just use reduce but the logic use reduce but the logic is the same and as you can see we have is the same and as you can see we have our result our result and let's just uncomment this you can and let's just uncomment this you can see that we have three for this one also see that we have three for this one also if you guys find this helpful make sure if you guys find this helpful make sure you guys like and you guys like and subscribe thanks | 2024-03-20 17:31:15 | 1,725 | leetcode - 1725 Number if Rectangles That Can Form The Largest Square |
|
AVJipe27BuI | hello everyone welcome back after a very long time long time welcome back to my channel i am amitesh welcome back to my channel i am amitesh and and today we will be discussing a very good today we will be discussing a very good question which i found while i was question which i found while i was solving solving it for uh it for uh this uh six companies 30 days challenged this uh six companies 30 days challenged by our square by our square and the problem name is the code string and the problem name is the code string it has been asked by goldman sachs it has been asked by goldman sachs and uh let us first see what the and uh let us first see what the question is so we will be given an question is so we will be given an encoded string and we have to return its encoded string and we have to return its decoded string now what's this decoded string now what's this so we'll be given uh this kind of form so we'll be given uh this kind of form which is k and an encoded string and we which is k and an encoded string and we have to print the encoded key number of have to print the encoded key number of times times which means which means where the encoded string inside the where the encoded string inside the square bracket is being repeated k times square bracket is being repeated k times right which means for example a is there right which means for example a is there and outside the bracket key is three and outside the bracket key is three we need to print a three times right we need to print a three times right i'll explain it in the examples first i'll explain it in the examples first let's understand what the question says let's understand what the question says next is next is it's given that there is no number it's given that there is no number except that uh that k the repeating except that uh that k the repeating number right number right so we can safely assume that there is so we can safely assume that there is only one digit only one digit uh there is the only digits represented uh there is the only digits represented here are k which means that here are k which means that uh uh it is for uh it is for uh repeating elements right now we can also repeating elements right now we can also assume it's given in the question that assume it's given in the question that there are no extra white space square there are no extra white space square brackets brackets etc right etc right let us now jump into the examples the let us now jump into the examples the constraints are the length of the string constraints are the length of the string can be 30 can be 30 and and yeah okay fine let's see the examples yeah okay fine let's see the examples first okay so i've already written it first okay so i've already written it what uh the question as the question what uh the question as the question says this is k says this is k this is my encoded string right this is my encoded string right it's very difficult to write here it's very difficult to write here so so i have to print it uh write it three i have to print it uh write it three times so answer would be a a times so answer would be a a e e what's the answer here how will we what's the answer here how will we seeing it seeing it so so here it's written to c like here it's written to c like 2c 2c so so firstly firstly i'll write 2 times c i'll write 2 times c right first step would be this and the right first step would be this and the second step would be second step would be c c 3 is here right so let's go and c c 3 is here right so let's go and write write acc three times so ac c acc three times so ac c a c c a c c and as you see ah and as you see ah i cannot write just i cannot write just understand it right so there these were understand it right so there these were the examples i hope you have understood the examples i hope you have understood it now let us it now let us right now dive it into right now dive it into uh how would we uh how would we how how are we solving that right let us how how are we solving that right let us see see it's a very very good uh very good it's a very very good uh very good question i would say question i would say it took me time to understand how to it took me time to understand how to approach it approach it so so uh uh let us say if let us say if 3a is given right 3a is given right now we have to decode is decode it as a now we have to decode is decode it as a a a now how i am coming up with three is now how i am coming up with three is i know there is three written here i know there is three written here how will i get it when will i get it how will i get it when will i get it and uh i i also want a and uh i i also want a and then multiply or like and then multiply or like print it three times right so for print it three times right so for printing we need three right and printing we need three right and for uh for uh the content i need a the content i need a right right how will i do it how will i do it let us see so let us see so first of all our intuition comes that we first of all our intuition comes that we need to need to uh uh search for a closing bracket first search for a closing bracket first closing bracket no closing bracket no closing bracket no closing bracket no closing bracket this is a closing magnet closing bracket this is a closing magnet right right now go back to the uh till we find uh now go back to the uh till we find uh opening bracket opening bracket and pop out all the content inside it and pop out all the content inside it which is three which is three i have popped out i have popped out oh sorry a yeah i have popped out a oh sorry a yeah i have popped out a now i go back once more and pop out now i go back once more and pop out three three and then c and then c uh and then multiply it uh and then multiply it a multiply here means like i am a multiply here means like i am repeating it three times okay don't repeating it three times okay don't misunderstand it misunderstand it right then right then let us take another example for example let us take another example for example 3 is 3 is 2c 2c right right this was my first example so this was my first example so let us see let us see now as i said i'll go for finding a now as i said i'll go for finding a closing bracket closing bracket yeah here is the closing bracket my yeah here is the closing bracket my first closing bracket is here pop out first closing bracket is here pop out all element till i find the next opening bracket which was c then pop out again the number so 2 into c will be there and then i'll push back all the c's inside the okay so this is acc i have pushed it into the stack now three again pop out all three this three till i get an opening bracket and then multiply it by three which means three times hcc right so i hope you got it like i'm using i'll be using a stat right pushing out every element for example in the first case i'll be pushing oh let me rub it uh it it's very it's not looking good just let me uh i hope you have got it because it was uh i hope you have got it because it was uh really very interesting uh to use this really very interesting uh to use this approach let us say we have a right i approach let us say we have a right i have used the stack have used the stack right right let us go through the example let us go through the example uh i'll i'll i'll be on this string uh uh i'll i'll i'll be on this string uh i'll beat this character sorry put it i'll beat this character sorry put it into the stack i'll be on this character into the stack i'll be on this character now put it into the stack now put it into the stack then i'll put a then i'll put a right i then i found this right i then i found this and when i found this i'll pop all the and when i found this i'll pop all the characters still the opening bracket characters still the opening bracket which was a which was a and and this opening bracket which is of no use this opening bracket which is of no use and again pop out the number of times and again pop out the number of times the the character needs to be repeated and then character needs to be repeated and then finally finally multiply the multiply the answer with that answer with that right and then put it back into the right and then put it back into the stack and then return the answer stack and then return the answer go so this was very simple i'll show you go so this was very simple i'll show you another example another example to assure that this process is working to assure that this process is working now let's go now let's go like 2 like 2 a a three b three b okay okay so so how we will go as i said i'll use a how we will go as i said i'll use a stack stack let's take a big stack right let's take a big stack right put two put two put an opening bracket put an a put a 3 put an opening bracket put an a put a 3 right put a opening bracket put a b now right put a opening bracket put a b now we have found a closing bracket here we have found a closing bracket here right now i have to pop till here right now i have to pop till here right so b and an opening bracket gets right so b and an opening bracket gets popped out this is of no use popped out this is of no use i'll pop out three also i'll pop out three also and then multiply it by b and then multiply it by b and then push it back into the stack and then push it back into the stack which means now our stack would look which means now our stack would look like like b b b b b three times right b three times right then a then a then an opening bracket then an opening bracket then a then a two two right right then again i found a then again i found a closing bracket closing bracket right and i pop out right and i pop out b bbba b bbba and then multiply it two times and then multiply it two times right this would give me the answer right this would give me the answer let us jump right let us jump right right into the code so stack right into the code so stack off off i'll put i'll make a stack as i said and i'll put i'll make a stack as i said and then traverse the string then traverse the string quentin is equal to 0 i less than s dot yes length and then let's start length i'll traverse the whole string yeah if i find a till i find a closing bracket i'll just push the content in this into the stack pushing it through whatever i said i am writing down in the code i pushed everything instead now what now what i found uh i found a like opening bracket right i'm sorry my bad i found a closing bracket right i have i close it so why where i'll store first of all let me keep a current uh string to store that whatever i pop off so i am storing right so while sp which is our stack top if it is not equal to a closing sorry opening bracket till that's ml what pop and put it into till that's ml what pop and put it into a a our current string our current string which would be which would be yes i'll go through the examples again for sure to tell that this process is working now what now what uh after uh like while stack not equal now stack top is equal to skip top is equal to uh this this opening bracket right i need to pop that too which is of no use as i said by popped opening bracket now i might have two cases from here i might have a number outside here right or i cannot have a number outside here or the stack can be empty also because uh let us take this case like uh let me let me show you like let us take this case so a is only here right and the stack is this a and when i found this i pop out a i pop out this this was of no use so i just pop out and the current was just a right current was a but we didn't have anything here so i like the stack can be empty right so we don't pop out anything from here so if while not stack dot empty right and [Music] and uh this digit the drop element which is st top is the st top is a digit then i'll put it in number which is uh my string dot top and then press the number right now why i did this i'll explain it again now why i did this i'll explain it again and telling and telling oh oh i have my number right let us convert it i have my number right let us convert it into an integer first so string to into an integer first so string to integer stoi is string to integer integer stoi is string to integer i have converted it into an integer and i have converted it into an integer and we have to repeat that string we have to repeat that string that number of times that number of times which was in the question k number of which was in the question k number of times right so number of times times right so number of times till the number of times is there i'll till the number of times is there i'll go through every character of that go through every character of that current string current string and then push it into the stack and then push it into the stack which would be this which would be this and then for sure what and then for sure what i did here is got my stack pushed and i did here is got my stack pushed and this process gets repeated every time this process gets repeated every time now that i have pushed everything into now that i have pushed everything into my stack now my stack contains my answer my stack now my stack contains my answer right so let us print the answer so right so let us print the answer so while stack is not empty all right i'll just answer equal to st top press answer plus answer and mistakes mistakes so i guess uh my this would contain my so i guess uh my this would contain my answer and i will return it there might be somewhere else there might be somewhere else no no there was no other no no there was no other i'll submit it anyhow i have made it i'll submit it anyhow i have made it so uh this was a very good question and so uh this was a very good question and see this day this is faster than 100 of see this day this is faster than 100 of uh c plus plus submissions how i did it uh c plus plus submissions how i did it i'll explain it again i'll explain it again right okay so i'll explain again for clearing all the confusions you have and this time i'll take a good example so let me take three a two c okay three 382c let's go okay so my code says that i'll go till uh i'll be i'll be pushing the content till i get a closing bracket okay so this is my current stack okay i'll i'll be pushing it uh the content till i get a closing bracket so three an opening bracket a two an opening bracket i'm writing here okay see now i found a closing bracket so what happens now now i found the closing bracket now pop it out until i find uh this code pops out and sources into the current till i find the opening bracket which means here is our opening right here here this one so my current now stores see true till i popped out till the closing uh now i'll pop the opening bracket also now i'll pop the opening bracket also and put the number if it's there so and put the number if it's there so let's see let's see now i popped out this one this one now i popped out this one this one and then uh checked and then uh checked the number the number so so times now times now times times variable variable now contains now contains two two right from this code right from this code you can see the times variable contains you can see the times variable contains the number which was true the number which was true right now now what i did is while times right now now what i did is while times minus minus for every character i push minus minus for every character i push that into the stack that into the stack so this was the stack so this was the stack correct three correct three this this and a and a so for times minus minus means two times so for times minus minus means two times i put c inside the stack push i put c inside the stack push finally i am done my pointer was here finally i am done my pointer was here now the pointer moves here again it now the pointer moves here again it found the closing bracket found the closing bracket again it repeats the same sequence again it repeats the same sequence till it finds an opening bracket and till it finds an opening bracket and it pops out everything from here it pops out everything from here like acc like acc pops out this pops out this right right st dot pop was here i mentioned it here st dot pop was here i mentioned it here popped out this popped out this and then for and then for the number the number i find the number that would be the i find the number that would be the number of times my answer would be number of times my answer would be repeated which is 3 repeated which is 3 so 3 into so 3 into acc which would give me acc three times acc which would give me acc three times yeah yeah yeah yeah let's leave it let's leave it yeah so yeah so i think i hope you would understand this i think i hope you would understand this uh if you like the video do give me a uh if you like the video do give me a thumbs up thumbs up because it really motivates me to make because it really motivates me to make new videos for you every time right and new videos for you every time right and explain your better concepts explain your better concepts very easily to understand thank you | 2024-03-24 12:13:11 | 394 | Leetcode 394 | Decode String | [ Solution + Code Explained ] |
|
6wbz96oTIo4 | Ko [Music] Enjoy a [Music] Enjoy a lot, beloved Krishna Radha, your long lot, beloved Krishna Radha, your long golden problem, thank you, stop, I golden problem, thank you, stop, I want it again, want it again, sitting horse, sitting through resentment, why is sitting horse, sitting through resentment, why is he angry, why are you angry, your dreams, your why are you angry, your dreams, your love, yours | 2024-03-15 18:31:12 | 1,615 | Maximal Network Rank -Leetcode 1615 Solution |
|
7DjxxYtFi5k | Hello gas welcome you new video, so this problem is a very problem is a very interesting problem and one of my interesting problem and one of my favorite question is from Giridih. Okay, so favorite question is from Giridih. Okay, so in the question it is said that we are given two in the question it is said that we are given two strings S1 and S2 of equal length. strings S1 and S2 of equal length. strings S1 and S2 of equal length. already mentioned that out of the lengths of S, Van and Tu, X and A from two letters will either be only And 2 strings are made as if this tu makes tu string equal tu h other what we have to do is we have to make S1 equal to S2 which gives as many characters as there are in S1, there should be same number of characters in h2 There There There should also be the amount of characters like here it is should also be the amount of characters like here it is XX and here it is A A so we have to make it XX and here it is A A so we have to make it X A If we have to string with both characters, then this thing has been said and we have been told that return d minimum number required to make s1n2 equal. Okay, so we have been told that we have to tell the minimum number of cells so that we can make If you can make it and if it is impossible then make a If you can make it and if it is impossible then make a If you can make it and if it is impossible then make a return mine. Let return mine. Let us understand it once. us understand it once. Look at the problem, the problem is very straight Look at the problem, the problem is very straight forward but the logic is very good in this. So if forward but the logic is very good in this. So if I talk about the approach to the problem then I talk about the approach to the problem then in this in this in this that Let's Let's S1, both should be different, S1, both should be different, so look friend, there can be four conditions here, so look friend, there can be four conditions here, okay, the first condition is that okay, the first condition is that like in S1, we talk like this like in S1, we talk like this here. It is This is possible that this A and this A can also be found and that can also be found like this, okay The The sequence of XX can also be found like this, If If there is a minimum number option then let us again take the same example in which it has been given to us that XX and AA are A, we have to make them tomorrow, then what does your basic initiation say that they can be of equal, We can see when whatever is We can see when whatever is We can see when whatever is ours becomes see see how to do it. So here we understand how to do it. So here we understand that we can perform that we can perform one character response by picking one one character response by picking one character. Okay, so here character. Okay, so here we will be looking at Ace of we will be looking at Ace of Zero. Zero. Zero. with van is ok and after shopping we got the form of A X A X then I would have got then I would have got X X Sorry A Sorry A This This increased our limit, so we understand that if increased our limit, so we understand that if we swipe like this, it will take we swipe like this, it will take us a lot of steps. How many are the total number of Let's do something and try to make both the streams from, first in the string there should be as many many give a team under his command, give a team under his command, okay, so we will perform shopping like this, we will okay, so we will perform shopping like this, we will solve zero s zero with s van, solve zero s zero with s van, but man, nothing is getting full, so but man, nothing is getting full, so before full, let us talk about this, before full, let us talk about this, so we will get the basic instructions till now. so we will get the basic instructions till now. What all did we come to know? Okay, so the basic idea is that What all did we come to know? Okay, so the basic idea is that we came to know about two things. we came to know about two things. After understanding this much, let's look at the problem. Firstly, I am in the After understanding this much, let's look at the problem. Firstly, I am in the testing size, this was given to us testing size, this was given to us in the question itself, okay, so we do in the question itself, okay, so we do not have any right to it. not have any right to it. not have any right to it. this banda but this second point, this is a very important thing to note that the amount of character from this string exactly content is ok, what am I trying to say, as you can take an example, see here, The The The exact content of a string is the amount of exact content of a string is the amount of characters. It can mean any string characters. It can mean any string when there is amount of characters in both of them, when there is amount of characters in both of them, like if there is an This is S2, okay, it is in the This is S2, okay, it is in the same way, same way, so if there should be one A in this too, so if there should be one A in this too, okay, if every news in this is 2X, okay, if every news in this is 2X, then there should be 2X in this too, that means there is then there should be 2X in this too, that means there is equal distribution of characters, equal distribution of characters, okay Dan, and in the same place, if okay Dan, and in the same place, if is no sharing of equal amount in both, like you can see in this example, is no sharing of equal amount in both, like you can see in this example, in S1, 2X came, in S2, two brothers in S1, 2X came, in S2, two brothers came, so now came, so now we know that we know that how many total how many total By doing this we will make it equal, but see when we are not able to make it equal, look, we will not be able to make it equal then, as from here till now you all must have understood one thing very clearly, that thing is that look like take this example Pay here. I can keep it and I can keep one A in S1 and can keep it and I can keep one A in S1 and I can keep one A in this, so let's I can keep one A in this, so let's see an example from where we will see an example from where we will start getting clear about the actual start getting clear about the actual shopping etc. from whom and why to do it, shopping etc. from whom and why to do it, how will the minimum be arrived at, okay? how will the minimum be arrived at, okay? how will the minimum be arrived at, okay? that I have taken a string S1, there are some characters in S1 and there are some this is my Tak Ji Han is absolutely ok, this is my A, this is my A, what was my position now, S van S, you are equal, so Ji Han is absolutely ok, now here comes the point, Is Is Is it equal? No, it is not equal, so it equal? No, it is not equal, so we have to make it equal, but to make it equal, we have we have to make it equal, but to make it equal, we have already come here, right already come here, right on the second index, on the second index, we have got an we have got an If you want to make it equal then remember I had If you want to make it equal then remember I had talked about four conditions at the top that talked about four conditions at the top that look either I get X or I look either I get X or I can get Bhai Bhai which you can get can get Bhai Bhai which you can get problem but if this happens then there is a problem but if this happens then there is a problem. If this happens then there is a problem because we problem. If this happens then there is a problem because we both have to make a call. Okay, so let's leave X and A for both have to make a call. Okay, so let's leave X and A for a while, a while, then we got the same then we got the same then we got the same keep it and again if it is AA then there is no problem in it. Again there is no problem ok brother but this has a problem and what is the solution to this problem ok then look X A you are ok if you will I I I try to do this I will open that next Which again a episode why that because again diagonal like I set this so what would I get I would get If I get a sequence of But if they get Look how they are going to look, Look how they are going to look, if we diagnose them, there will be if we diagnose them, there will be no benefit even after shopping, there will be no benefit even after shopping, there will be no change in them, so for this too, no change in them, so for this too, we will have to set them as X A, so when we will have to set them as X A, so when we swipe on X A, it will convert to we swipe on X A, it will convert to A A A in A If one operation is done, then they will become There is If So I am going to undergo minimum two operations, so friend, from here onwards everything is very clear, look, it was equal, it was equal, it was equal, there is no problem, but here there is Want a greedy approach? What should we do is that axi is Along Along with A, with A, there will not be Later this one will come, it will take two operations. Here, how much minimum pressure will I have, it will take two operations, but if I talk like this, I would have had one more I would have had one more Here, Here, two legs of two legs of we get one more sequence, what will we do with these two in one operation because X will become A, then this A will go here to because X will become A, then this A will go here to A A and this X will become I got his brother I got his brother D Power PDS This means we go from the gate to confusion Pay A Look In In this way, if I get the same day of A, why do we have to talk A, why do we have to talk because look here, if it becomes direct, then it will There will be a There will be a There will be a swipe, this will create swipe, this will create Man, take the total of four times This is the index from s2px, okay you guys must be seeing how much is my total, my One One A came here A A came here One came here One A came here A A came here One came here One came here How many times have we came here How many times have we consumed A in the same manner So X A consumed A in the same manner So X A once came here Just became one And talking about A Now, if I talk about the minimum number of operations required for this, then remove it from the game, I do then remove it from the game, I do n't see any problem in it, okay, Y-Bhai n't see any problem in it, okay, Y-Bhai is also already a shortcut, so remove it too is also already a shortcut, so remove it too because there is no problem in it. because there is no problem in it. because there is no problem in it. come to X A and A look at the axis if It will be reduced in one operation, It will be reduced in one operation, happily it will establish its setting, ok, it will equalize in one operation but the problem comes, if A is X then A Will take your butt here, is Would like to Would like to open But look here, here Because I will Because I will do two operations with this one to equalize do two operations with this one to equalize but with this one less but with this one less becomes mine. Okay, but now we have to check the same thing, becomes mine. Okay, but now we have to check the same thing, X A got his partner X A got his partner but AF did not get it. but AF did not get it. but AF did not get it. can also be A. A can also be can also be can also be necessary to have one of the two because I actually want as many F's as there are. Look, all these So I am not sure if there is another A If there is X, then A Try this thing because unless you do it yourself, maybe it will be very clear to you but A Why did I say this? I see, A wants it simultaneously, it can be X, A can be A or A can be He may have a lookalike or it may be the opposite, It It should not be, these two are the same and should not be, these two are the same and why should they not be? Let's take an example why should they not be? Let's take an example like here X A X A like here X A X A A After doing this, he used to check whether whether called yourself in the operation, after performing called yourself in the operation, after performing this shopping, now it comes to this shopping, now it comes to my poor ex, and ex has my poor ex, and ex has his day, not mine, brother, with whom he his day, not mine, brother, with whom he could have reduced one operation, he got ex, if he could have reduced one operation, he got ex, if he got ex, then it is his friend now. got ex, then it is his friend now. 0 sign, now I 0 sign, now I will check each index by applying fall loop, okay, if the will check each index by applying fall loop, okay, if the size of both is equal, then you size of both is equal, then you can go for the size of any one, and can go for the size of any one, and what to do X A what to do X A So we have to count, in this way I had Please Please remind me once again in the video, remind me once again in the video, if there is any problem then it is ok then return it, it if there is any problem then it is ok then return it, it means it can never be means it can never be equal and if it is not like this then we have to return it, don't look brother, I get its cousin I get its cousin If you do it, I will get the minimum number one operation and the third express, the fourth will do one operation and the third express, the fourth will do that operation with Axi, accordingly, that operation with Axi, accordingly, I had to do Axi/2, okay, in the same I had to do Axi/2, okay, in the same way, you will do the second one also on A's account, way, you will do the second one also on A's account, so that so that so that Along with Along with one operation, I will do the one operation, I will do the operation, but one ex will be left, about whom operation, but one ex will be left, about whom we cannot do anything, he is not we cannot do anything, he is not found, okay, in the same way, I will do found, okay, in the same way, I will do shopping with one ex, one ex upon you, shopping with one ex, one ex upon you, three upon you, one. three upon you, one. three upon you, one. but look at doing the All the All the is an account and for every AX there exists an A So, if for each ex the So, if for each ex the ex is not gifted, but the same person must be ex is not gifted, but the same person must be exiting that amount because exiting that amount because we have first put a check and returned it to the mine owner, so that we have first put a check and returned it to the mine owner, so that this does not happen, that is why he has this does not happen, that is why he has come here, so for the ex. come here, so for the ex. Only Only there is a minimum operation then minimal operation would be done and only If there are only a few If there are only a few left then I will get the answer in this way, so that's why I had to do XA model Tu in Tu, why didn't I do Tu plus directly? If I know for sure that XA will survive, it is not necessary that if If axi is left then only it will be If axi is left then only it will be If axi is left then only it will be multiplied by 2. If it is not left then it will multiplied by 2. If it is not left then it will not happen. This direct case is going under not happen. This direct case is going under and here one more thing, here and here one more thing, here you have to write not equal, let's submit it and see. Now look It may have happened that you people It may have happened that you people It may have happened that you people may not have understood this even a little, but as may not have understood this even a little, but as much dry return as I did, it is much dry return as I did, it is up, now you guys do it once yourself and up, now you guys do it once yourself and then watch the video, you guys will definitely then watch the video, you guys will definitely understand, it was a very logical question. understand, it was a very logical question. understand, it was a very logical question. hope you guys enjoyed this gravy, let's meet in the next video, | 2024-03-19 17:13:32 | 1,247 | Minimum Swaps to Make Strings Equal | Leetcode 1247 | Greedy approach | Maths | C++ |Java |
|
ZaxsE6lFQMw | hey how's it going everyone welcome to another video today we're going to be another video today we're going to be doing another leak code problem and this doing another leak code problem and this is a problem that is really fun in my is a problem that is really fun in my opinion and it's called find the opinion and it's called find the celebrity and it's a leak cook medium celebrity and it's a leak cook medium and this is actually a problem that a and this is actually a problem that a buddy of mine saw in a phone interview buddy of mine saw in a phone interview at Amazon so obviously it's a problem at Amazon so obviously it's a problem that gets asked in the real world so the that gets asked in the real world so the the definition here is really long and the definition here is really long and like makes it confusing so I'm just like makes it confusing so I'm just gonna explain the problem to you guys gonna explain the problem to you guys basically you have a list of people at a basically you have a list of people at a party or a group of people and one party or a group of people and one person in that group is a celebrity and person in that group is a celebrity and that's celebrity doesn't know anyone that's celebrity doesn't know anyone else however everyone else knows that else however everyone else knows that celebrity so you're given this function celebrity so you're given this function here called nose and it takes in two here called nose and it takes in two values and it returns a boolean so if a values and it returns a boolean so if a knows B then it returns true so the way knows B then it returns true so the way that we can use this is that if if that we can use this is that if if anyone ever knows someone we know that anyone ever knows someone we know that that person isn't the celebrity and the that person isn't the celebrity and the person that knows someone also is in the person that knows someone also is in the celebrity so basically say you have nose celebrity so basically say you have nose and you have said we actually have the and you have said we actually have the celebrity in here and we have like celebrity in here and we have like person a this return false because the person a this return false because the celebrity does not know the person so celebrity does not know the person so using this function we need to figure using this function we need to figure out who the celebrity is and also if the out who the celebrity is and also if the problem states that there might not be a problem states that there might not be a celebrity there at the party so that's celebrity there at the party so that's also something that we need to take into also something that we need to take into account so the way that to approach this account so the way that to approach this problem is let's just first start with problem is let's just first start with the first person and have that as our the first person and have that as our potential candidate so these people are potential candidate so these people are represented as integers so we'll just represented as integers so we'll just say candidate equals and then we'll you say candidate equals and then we'll you know we have to start somewhere so let's know we have to start somewhere so let's just start at zero so what we need to do just start at zero so what we need to do is we need to loop through the rest of is we need to loop through the rest of the people and we need to start at one the people and we need to start at one since we already have zero all right so with this person what we need to do is we need to check if our candidate knows them if our candidate knows them then our we know that our candidate can't be the celebrity because the celebrity doesn't know anyone so what we can do is we can say if knows candidate and I then we need to update our candidate and our potential new candidate is gonna be I since someone knows I but we don't know if I knows anyone yet so that's why we're calling it a candidate so it's going to be candidate equals I all right so once we go through that we know that we have one person left that someone knows them but we don't know if anyone knows them or not so we could do potemkin edit but that's only if we were guaranteed to have a celebrity since we don't know we need to do another pass through so what we can do here is we can do four and then we just do another for loop all right so at this point we'll have a couple cases here so we'll do if so we want to first make sure that value that we're checking is not the actual candidate and we also need to check two things now we need to check if our candidate knows someone or if anyone knows the candidate and if either those are true then our actually if the opposite is true it'll return false so let me just show you so if we have knows candidate and I so if the candidate knows someone that can't be the celebrity or if I knows the so I doesn't know the candidate then the so I doesn't know the candidate then the candidate can't be the celebrity so if candidate can't be the celebrity so if we have either of those two cases we we have either of those two cases we just return to minus one because that's just return to minus one because that's what the that's what the function says what the that's what the function says that's what the prompt says otherwise we that's what the prompt says otherwise we do return that candidate so let's go do return that candidate so let's go ahead and run that and we have an error ahead and run that and we have an error because of course we need semicolons in because of course we need semicolons in Java and so that looks good let's go Java and so that looks good let's go ahead and submit and we get success so ahead and submit and we get success so we have a run time of 97% and a memory we have a run time of 97% and a memory usage of 58% all right so let's look at usage of 58% all right so let's look at the time and space complexity of this the time and space complexity of this since we're not using any additional since we're not using any additional space the space complexity is just going space the space complexity is just going to be constant and the run time is going to be constant and the run time is going to be n because we have a loop here to be n because we have a loop here where we're going through each element where we're going through each element and we also do have this extra for loop and we also do have this extra for loop but this isn't adding to the time but this isn't adding to the time complexity because we are just doing complexity because we are just doing another pass through so the time another pass through so the time complexity will just be linear or n all complexity will just be linear or n all right that's gonna be all for this video right that's gonna be all for this video I hope you guys enjoy the problem as I hope you guys enjoy the problem as always thank you guys so much for always thank you guys so much for watching please like subscribe if you watching please like subscribe if you haven't and I will see you guys next haven't and I will see you guys next time time [Music] | 2024-03-22 12:37:16 | 277 | LeetCode Interview Problem - Find The Celebrity |
|
mgNbOlvEiwc | hello everybody today we will focus on solving lead code problem one seven two solving lead code problem one seven two five five number of direct tanks that can form the number of direct tanks that can form the largest square largest square if you read the question we are giving if you read the question we are giving off the in uh this off the in uh this arrival list and here in this array list arrival list and here in this array list we are given the items that represent we are given the items that represent them them represent the length and width of the represent the length and width of the rectangles the problem is that to find rectangles the problem is that to find the maximum square the maximum square maximum square with this units i made maximum square with this units i made some illustration here some illustration here to explain the quest the problem better to explain the quest the problem better we are given off the list of the rise we are given off the list of the rise this each item represents the length and this each item represents the length and width of the rectangle width of the rectangle we need to find the maximum square how we need to find the maximum square how can we find the maximum square can we find the maximum square by taking the minimum value inside the by taking the minimum value inside the minimum value from that items minimum value from that items it's 5 and as you can see here it's 5 and as you can see here we will get 5 to make the square from we will get 5 to make the square from this rectangle this rectangle and otherwise if we get the 8 it will and otherwise if we get the 8 it will not be possible to make the rectangle not be possible to make the rectangle with the unit with the unit of 8 and with the unit with the unit of 8 and because of that we will iterate these because of that we will iterate these lists and we will get the minimum value lists and we will get the minimum value and after that we will keep inside our and after that we will keep inside our dictionary dictionary at the end of the time at the end of the function then we need to find how many times as you can see here we go if you iterate as you can see here we go if you iterate this this i a list for it for for the first item i a list for it for for the first item the minimum is five the minimum is five week and then three five five week and then three five five we have the three times five one times we have the three times five one times three three three units or three yeah three unit three units or three yeah three unit and we will return that we maximum and we will return that we maximum square is 5 how many times 3 times square is 5 how many times 3 times first we will focus on solving this first we will focus on solving this problem with java problem with java and first of all we define and first of all we define we define a hash map we define a hash map first of all yeah we define a flash map first of all yeah we define a flash map map hush map and after that we need to iterate that rectangles list for rectangle rectangle and after that we will check if this and after that we will check if this rectangle rectangle yeah and sorry first of all we will get yeah and sorry first of all we will get the minimum value the minimum value and ins new val and ins new val is equal to math is equal to math to mean and to mean and this is awry and we can get the this is awry and we can get the items by index items by index like that rectangle 0 and one yeah and after that we need to check that whether that value inside that dictionary how can we look that we can type like that map contains map contains k mean k mean y if that's true y if that's true we need to get that value and we need to we need to get that value and we need to get get this case value it's like that hash this case value it's like that hash map point cat in other ways we will get zero in other ways we will get zero yeah and yeah and okay account and after that we need to okay account and after that we need to put that inside the put that inside the map hash map map hash map put comma comma plus one and for this loop we will get plus one and for this loop we will get the hash map the hash map with the minimum value and the number of with the minimum value and the number of the minimum minimum squares the minimum minimum squares and we need to convert the case to the and we need to convert the case to the arrival list arrival list firstly we define that list here integers map point okay and after that hash map sorry hashmap point get get or collections nocturne points yeah max hash ri yeah max hash ri i will explain that one second i will explain that one second and this point i think it's it's okay yeah and actually after for after digital forward point in this for loop we will sort k and the values we get the minimum values and after that we count how many times and at the end of the loop we have a list hash map and we convert the case to the list and from this list we get the maximum value collections of the point max and after that the the the the and then we return the maximum and the and then we return the maximum and the number number the number of the maximum squares the number of the maximum squares if we if we run this if we if we run this card we need to look that everything's card we need to look that everything's okay okay run codes sorry for square or curly brackets did we type that yeah problem it has been it has been accepted it has been it has been accepted with java 6 milliseconds and if you solve this problem with yeah it's same actually first of all we yeah it's same actually first of all we define define my dict is equal to my dict is equal to dictionary and after that we need to dictionary and after that we need to iterate that iterate that we will get the minimum value we will get the minimum value for rectangle and we will get the minimum value if and we will get the minimum value if mean rectangle not in my dict if that if not in my dictionary that that's the least minimum than the minimum value of that list we check that if it's not a dictionary then we need to obtain that rectangle tangle rectangular uh we need to uh we need to just count that yeah one just count that yeah one sorry one my dick in rectangle plus one my dictionary minimum rectangle plus one and at the end of that we will get the list with the case and the values and return max max your max think should be okay it has been accepted just look it has been accepted just look differences differences and yeah java is and yeah java is more java faster than the python more java faster than the python yeah i hope that you understand the yeah i hope that you understand the logic or the basics logic or the basics i lo i hope that you enjoy that and i lo i hope that you enjoy that and thank you very much for your watching | 2024-03-20 17:30:37 | 1,725 | 1725. Number Of Rectangles That Can Form The Largest Square|LeetCode | Python | Java | English |
|
eqNKciJIxLM | Loot Exams will see the program of multiplication of two strings. strings. It is from the list. The program of multiplication of two strings is simple in pattern. To understand this, there are some things in which we have to understand that understand this, there are some things in which we have to understand that when we do this multiplication, when we do this multiplication, we will not use these teacher functions. This is not for we will not use these teacher functions. This is not for any any any and then thought using internal function is not possible, you see how to understand this, if we print, that's why we have inputted, we make this multiplication of gas unable, so If you do then If you do then If you do then this is your erotica in austin that your hair this is your erotica in austin that your hair and yours so you cannot notify STF and yours so you cannot notify STF in this you can fold it in this you can fold it if you convert it into simple city interior like this MP3 MP3 Jai Hind Jai Hind that now if we 10 that now if we 10 that now if we 10 question on Patiyara, question on Patiyara, here you do here you do not have to use the wait function i.e. simply multiply the two strings without putting in teacher function. Now multiply the two strings without putting in teacher function. Now how to do it. how to do it. how to do it. two or four things that we have to keep in mind. First of all, the logic that we have to keep in mind is that we can multiply it by using the help of your face, we will add sisters, Is it a Is it a Is it a character, be it zero, if it is a character or a character, be it zero, if it is a character or a number, in any condition, you must have number, in any condition, you must have added it, your note will be CM and added it, your note will be CM and character, that is, I have added it, Lokayukta will be character, that is, I have added it, Lokayukta will be bathed, then bathed, then what will be 55050, then its people of the institute are what will be 55050, then its people of the institute are Asim Ninth Class. Asim Ninth Class. Player will be 57th on the side, we will solve on this logic, Player will be 57th on the side, we will solve on this logic, how do you understand this because like here 4830 is the festival of zero i.e. out of hundredth, we - if we do FT, it will come out to be G. O. What happened to me, The scene is done, if it The scene is done, if it The scene is done, if it is forty nine, it is the hello of your festive one is forty nine, it is the hello of your festive one 's caravan, then if they add 340 grams of dry ginger, 's caravan, then if they add 340 grams of dry ginger, then what is the join aayega or then what is the join aayega or understand it like this and tenant is its value of understand it like this and tenant is its value of one and from this we - make it. one and from this we - make it. What will be its value in that condition? What will be its value in that condition? You will think that we will start simple on this logic, keep one more thing in mind, now we will solve on this logic, here we will solve the keep one more thing in mind, now we will solve on this logic, here we will solve the multiplication which we do first, we will fold it on that logic only. fold it on that logic only. fold it on that logic only. repeated. What will we do with a number for the first time? We will multiply it with the file. Then we multiply it with our mind. Then what will we do? One, we will multiply 66 and if we multiply 163, then my dear If we If we If we multiply by next 9 then fire into multiply by next 9 then fire into six cyber cafe 30340 started and six cyber cafe 30340 started and limited reminder yagya is done then we limited reminder yagya is done then we store zero and 30th here in the list, store zero and 30th here in the list, first of all we understand first of all we understand what is a list, we to what is a list, we to what is a list, we to size that we will declare is the chest size that we will deposit the cash in. First look at the length of both of them. You see that the length of the first time is two to the contesting comment. Whenever you multiply this number, then the It is It is It is not possible, that is, if you multiply a tube digit not possible, that is, if you multiply a tube digit number and a two digit number, number and a two digit number, it will not go more than four digits off and it will not go more than four digits off and digit. If you fry the top three digits of symbol 3D, then it will not go more than six digits. fry the top three digits of symbol 3D, then it will not go more than six digits. Player or 382 Pat. Player or 382 Pat. Player or 382 Pat. then you will get more than 3425 benefit in more time. You will not have its link. The third part of multiplication is simple. What is this play list string? This is Fourth, to store the number, we Fourth, to store the number, we Fourth, to store the number, we declared whose link is for and everyone we have stored zero then we will do this multiplication then fire into sex ati aaya to zero aham third pocket money start and thing after that profit could have been done by Mr. Then what will we do hi * -click Had it come, the file will come and -click Had it come, the file will come and -click Had it come, the file will come and what would we say, Shankar yes, these are my what would we say, Shankar yes, these are my sarees, then what will we do, if we sarees, then what will we do, if we multiply the family tree, then multiply the family tree, then what are we doing here, what have we done with the back, what are we doing here, what have we done with the back, so what is it with the back 412 we so what is it with the back 412 we so what is it with the back 412 we reminder that has been received, let the reminder unite and start ahead that I am the same as we are, the reminder of the torn one digit ahead, this trick was 3000 stored, on the reminder, the digit ahead is broken and one pocket is ahead, so did the SIM, what are we doing here, hide If there is cotton's for that If there is cotton's for that If there is cotton's for that toe, here we move one digit forward toe toe, here we move one digit forward toe question profit is toe then what will we question profit is toe then what will we do if one * one comes then take out 141 important time do if one * one comes then take out 141 important time because reminder is nothing because reminder is nothing here used to hide that zero minister here used to hide that zero minister 's team logic 's team logic 's team logic create the program further, after that we will try to understand it better. Now the first thing we have to do is take two strings, then we call them input and declare the back list, The length of both of your The length of both of your The length of both of your stings gives some effect. I turn off the net in S Plus, the play list is declared, it is simple, you print it and see that in reality it is also 0.2, dinner is done, if what we do not give here, friend. So this black would have been your star, so we all are not robbing Vijay of the right to store Jio in our pockets. Now we come to the program, there is also one thing and you have to keep in mind that whenever we do multiplication or add, Before doing this, I would Before doing this, I would Before doing this, I would request you to request you to see the program of my addition to make number or string, see the program of my addition to make number or string, it will be easy for you to understand that we can do multiplication by converting internally, can do multiplication by converting internally, why will we do why will we do such a big program in this trick because when we use such a big program in this trick because when we use any any any then its reason is that whenever we use it, you will be using excel or according to stomach, if you see, then this compiler also has a range, The The number is stored till the Africa digit, whether it is tow or edit, beyond that, there will be no notification of that condition or what to say about it, when we will do idol multiplication in this trick, then There will be There will be There will be no single single digit no single single digit multiplication and we can store this team as long as we can so we can store it as multiplication and we can store this team as long as we can so we can store it as long as possible, so long as possible, so we we need to do this, don't we? Player, now let's come to the need to do this, don't we? Player, now let's come to the program that we were in, how we can do this program that we were in, how we can do this first of all. first of all. first of all. when we do this multiplication, we do the multiplication from the back side, this is how we notify the mind from one, we do not do mental multiplication, we will do the tips from the pilot side, then we will do one, then we will do that, we will do six, then we will do one. What will we do for this, we will start both the strings from the back side in a look, add will be 654 and it is 15.41, first education will come, then forest will come, then first thyroid will be formed in the soil, so You You You can reverse it, we will not lift the skin, can reverse it, we will not lift the skin, we simply apply it in the look itself we simply apply it in the look itself and I am in the range and I am in the range that for the name of S minus one that for the name of S minus one A R Rahman, counting is done from all the districts, A R Rahman, counting is done from all the districts, so the minute will be and will go up to - 120 pockets. so the minute will be and will go up to - 120 pockets. And we will do minus one one here Tega And we will do minus one one here Tega player, this is the first look, the first player, this is the first look, the first number is the first number, you should understand one more thing here, number is the first number, you should understand one more thing here, first what we will do is multiply 6 by the height, first what we will do is multiply 6 by the height, then then multiply by and, that is, the first look multiply by and, that is, the first look is we will multiply one digit and is we will multiply one digit and To multiply both of them, let's give another look to To multiply both of them, let's give another look to that also. We set the back side setting of that also. We set the back side setting of all this coin range length all this coin range length of S1 of S1 a minus one to - formation of a minus one to - formation of a clear. Now understand in this that wearing this will cure a clear. Now understand in this that wearing this will cure your one digit height separated and your one digit height separated and five. five. five. Naseer, one will be multiplied, then there will be a zoom loop, the next one will be made and then Vansh or Hafta will be fixed and mind will be multiplied, so we two people here, we have given both of them in the report, what should be the store and when the If it is on the side or if the house is If it is on the side or if the house is If it is on the side or if the house is snatched then six orders snatched then six orders 15051 player What will we do after this? The 15051 player What will we do after this? The importance of gas will be converted into tasty and the logic which we will importance of gas will be converted into tasty and the logic which we will explain will come in it. We will convert any of these number strings explain will come in it. We will convert any of these number strings into numbers and multiply them by into numbers and multiply them by single single digit. single single digit. What will we do for this? What will we do for this? What will we do for this? sent, let's take that equal to you and we will make that RD. What will happen with this, the ASCII value of your string will be removed. The app is hide app - we will do it for test, either add it You can do that You can do that You can do that arty arty 01 we make it for tasty we have done 01 we make it for tasty we have done a lesson and will do multiplication so a lesson and will do multiplication so that etc. Desmond now once that every here both people have come back to me that every here both people have come back to me so this we click so this we click that now so that we have converted the number into digits, what will we do after converting, let us come to this simple current position of the what will we do after converting, let us come to this simple current position of the number which we will start, number which we will start, on that we come to that on that we come to that I plus Z plus one A plus product. That at the time of this action you mostly we are here simple attend what will be the location of your six because we will work the program from the back side to the American number reverse Murai tree location got 1 and one question is my zero which If you do notification If you do notification If you do notification then you can see 518 multiplication, then you can see 518 multiplication, Hello Hi, what happened at one position and it is fixed at one position, Hello Hi, what happened at one position and it is fixed at one position, Parv 124, what will happen, have you Parv 124, what will happen, have you done plus one or daily new thing, done plus one or daily new thing, my work will be done at yellow position, the What will we do for this? If What will we do for this? If What will we do for this? If we do the store at a good position, we do the store at a good position, then what is the first time found at the third position then what is the first time found at the third position because we have stored Jio in the entire list. because we have stored Jio in the entire list. For its logic, we have For its logic, we have included platinum i plus z plus one here. included platinum i plus z plus one here. Now on to the program. Now on to the program. Now on to the program. what we will do is this I plus Z plus this model, just model, just understand that I G plus one first time, what understand that I G plus one first time, what happened is happened is 101 and plus one on the third position, we will start, 101 and plus one on the third position, we will start, do reminder, if we do reminder, if we Look at this, we have to Look at this, we have to Look at this, we have to meet at the third position, meet at the third position, he is forced to have the worst position, these 10 and these two and these come to force us on this position, we want yes yes brother, it is loot, now understand this as we have done brother, it is loot, now understand this as we have done in the East. in the East. a request of two, here is plus quality, a request of two, here is plus quality, job is plus mixed, the number job is plus mixed, the number system is three system is three plus, the pimple will break on hunger strike, there will be plus, the pimple will break on hunger strike, there will be no plus effect in this, this number, no plus effect in this, this number, my daughter, is now fixed. my daughter, is now fixed. What do we do on the next number that will sit there, What do we do on the next number that will sit there, this reminder will be set that you like the quality, this reminder will be set that you like the quality, so what do we do here, plus is equal to two, so what do we do here, plus is equal to two, now we simply print this, now we simply print this, if we have one or two playlists, we will print that now. We will see the number notification 130 if we multiply the sixteen then what is my zero is coming in the first pocket then we will look ahead to remove the zero for now we understand the whole program 240 is my output which is my multiplication which is my coming this What do we do for this, first of all, this whole logic is this, you understand the logic office and article, when we article, when we make the notification of five six for the first time for 21 months, make the notification of five six for the first time for 21 months, then what will be the five or six, my 3838 Gaya then what will be the five or six, my 3838 Gaya location, whatever. location, whatever. location, whatever. happening for the first time, you are the first time, what are we in the complete list, so what is the constitution, zero will come, which was given, product plus is equal to Z plus one is equal to two of mine, this is the first time, only zero will come or the If you do then you can easily understand If you do then you can easily understand If you do then you can easily understand what is the item Hello, here is the call of what is the item Hello, here is the call of height, one of six means one plus one two three height, one of six means one plus one two three plus what is your first plus what is your first time in the list on Vanshi position, you can understand here time in the list on Vanshi position, you can understand here what is the first time in the list C position what is the first time in the list C position what is the first time in the list C position is zero, then if we clear it then it will be zero, 360 will come, when we take out the reminder, then zero will come, okay, then at which location will we start the zero, then you see here the program that we have made - A But let's But let's But let's start zero, player, then egg, start zero, player, then egg, what is this item position, where is the first position, what is this item position, where is the first position, two that we have stored, two that we have stored, care of hands free, then we come to the next step, care of hands free, then we come to the next step, next when people will run, I will be the next when people will run, I will be the application of fiber one. application of fiber one. application of fiber one. multiplication of 541 then there will be benefit. position at I? What is my position at position at I? What is my position at 543? Understand this, 543? Understand this, I plus G plus one. What is the position of I? One is G. Zero I plus G plus one. What is the position of I? One is G. Zero is zero plus one plus one. is zero plus one plus one. is zero plus one plus one. was a minister on the end to second position question, then when we understood it as a reminder, five plus 3.2 data was given to him, what will happen to me on the skin position, we store it in one pot and on the worst position, if I deposit it with carat As soon as the next one As soon as the next one As soon as the next one comes, you will complete the program by dividing it into comes, you will complete the program by dividing it into five. You should understand this music five. You should understand this music better. Then when we start, better. Then when we start, what will happen is this 1618 out of 5126, let's what will happen is this 1618 out of 5126, let's see its location. What is the location of one, what is my location, what is the location of zero, see its location. What is the location of one, what is my location, what is the location of zero, and what is the location of six? and what is the location of six? 1051 is done and when we will pay our fees plus, what store were we set on one or grade second sitting position, what store were we set on one or grade second sitting position, then we got six seats, we got 2015 then we got six seats, we got 2015 on second position, we are starting again on on second position, we are starting again on four, which is a reminder. four, which is a reminder. four, which is a reminder. one position i.e. I plus J I was my zero it was boiled on that we start one then in the next step when we go your 2101 will come then what we did Vansh plus will be done I plus J6 plus one If it is your Jio, this is also Jio and If it is your Jio, this is also Jio and If it is your Jio, this is also Jio and plus we had stored 1 here at position 191, that plus we had stored 1 here at position 191, that is, when we will take out one oath, is, when we will take out one oath, you will come immediately to the position, we will do two customers and you will come immediately to the position, we will do two customers and like zero position, we will like zero position, we will take out a reminder of Pattu, that is this zero clear. take out a reminder of Pattu, that is this zero clear. can easily solve the complete multiplication of this string. Now the problem is can easily solve the complete multiplication of this string. Now the problem is that we are going to that we are going to put another zero in front of it. To start it, put another zero in front of it. To start it, first of all, let us work first of all, let us work Given in this list, Given in this list, Given in this list, we take it open in this trick, we take it open in this trick, now we dip a string in the air W, now we dip a string in the air W, so now we put a loop here, for IAS so now we put a loop here, for IAS in research, the in research, the length of China length of China that W plus is equal to two, we make it that W plus is equal to two, we make it tear, that is, tear, that is, tear, that is, converting this, we have added a number and given a string. After that, what do we do? We will print it that it is a 1615 pajama application that your zero If we have to remove the giver which is there at the last, If we have to remove the giver which is there at the last, If we have to remove the giver which is there at the last, then what will we do for that? then what will we do for that? Simple, let's apply another logic Simple, let's apply another logic here, use a small function here, toe is kept, it has happened that the result is 0n first pocketmoney if equal result is 0n first pocketmoney if equal to if to if function of allot porn, we will remove zero function of allot porn, we will remove zero 's fast pocket, remove the sin of zero, this is 's fast pocket, remove the sin of zero, this is Jio in the first pocket, then if there is a reminder, Jio in the first pocket, then if there is a reminder, then what will happen in that condition, the reminder then what will happen in that condition, the reminder is your net that you are on this is your net that you are on this is your net that you are on this if we are doing multiplication, then in the last here two is for, then here you are, if your hello appears in the list, then we come in that condition, it will remain there, otherwise we will remove the first profit, what will happen with this, should Now Now Now when we will do multiplication on when we will do multiplication on 1616, you will remain 214 1616, you will remain 214 80. If we apply notification custom here 12345 4 5 6 80. If we apply notification custom here 12345 4 5 6 comment, then it will come 570. Hey, it is a comment, then it will come 570. Hey, it is a simple program, there should simple program, there should not be much problem in it, first of all not be much problem in it, first of all what will we do, link soft, we will what will we do, link soft, we will take all the list. take all the list. take all the list. which will be the length of steam, two strings will be from the front and all the points in all the pockets of the list, we start from zero, so we have to open a cafe, now let's come for that, we have already listed, let's What should we do? What should we do? What should we do? Friends, we have started this team from the back side. Friends, we have started this team from the back side. You can do this by doing director's research, You can do this by doing director's research, using Pankaj or by doing direct reverse. In using Pankaj or by doing direct reverse. In any variable, you just want to say that if you any variable, you just want to say that if you reverse one to just, then reverse one to just, then what will happen to you, equal to two faces. what will happen to you, equal to two faces. what will happen to you, equal to two faces. forced and Salman can be reversed in the next video force, I have not resided here, simple says she is believing in following the function so that small, my program will be found player and we This This This trick is to convert a number into a number, trick is to convert a number into a number, after converting it's after converting it's reminder i.e. the time which I have kept as my reminder reminder i.e. the time which I have kept as my reminder and then store it as hello, it is and then store it as hello, it is simple, if my list is going to zero then simple, if my list is going to zero then define the list that we define the list that we define the list that we arm of credit of pole digit is the art powder, its return is my zero, we have used the function to remove it and after that, whatever was left of my tablet, we simply added it to a string and printed it. So friends, if you liked my video then please subscribe my channel, like the video, comment, if you are interested in any program, there is a help chart in the description below, there is a link of Facebook Instagram, you | 2024-03-20 09:24:45 | 43 | Multiply two Strings || Multiply two Strings Python || Leetcode 43 || Interview questions |
|
L9Me0OZRUv0 | today we will be solving lead code 1027 that is longest arithmetic subsequence that is longest arithmetic subsequence so in this question we are given with an so in this question we are given with an array Norms of integers and we have to array Norms of integers and we have to return the length of longest arithmetic return the length of longest arithmetic subsequence in nums subsequence in nums or given array or given array and we all know that arithmetic and we all know that arithmetic subsequence is nothing but a series of subsequence is nothing but a series of integer where the difference between integer where the difference between these integers is constant like we can these integers is constant like we can see in example one there is 3 6 9 12 and see in example one there is 3 6 9 12 and you can see that 6 minus 3 is also 3 9 you can see that 6 minus 3 is also 3 9 minus 6 is also 3 and 12 minus 9 is also minus 6 is also 3 and 12 minus 9 is also three so as the difference is constant three so as the difference is constant so we can say that this whole so we can say that this whole arrays in arithmetic subsequence and arrays in arithmetic subsequence and therefore we return the length of areas therefore we return the length of areas output so how we can solve this question output so how we can solve this question as something as something we will see we will see so we are going to utilize this example so we are going to utilize this example example number two for understanding how example number two for understanding how we can approach this particular problem we can approach this particular problem so the first Brute Force approach that I so the first Brute Force approach that I can think of is like first thing is very can think of is like first thing is very clear to us that we need a difference clear to us that we need a difference right we need a difference between two right we need a difference between two values for checking whether the rest of values for checking whether the rest of the integers are in series or not the integers are in series or not arithmetic subsequence or not so for arithmetic subsequence or not so for that we always need two integers so that we always need two integers so let's consider this is our left value let's consider this is our left value this is our right value and we will do this is our right value and we will do right minus left for calculating right minus left for calculating difference after getting this difference difference after getting this difference how we can check the existence of how we can check the existence of arithmetic sequences arithmetic sequences we can do R plus d and whatever the we can do R plus d and whatever the value is we will check the value is we will check the rest of the array if this value exists rest of the array if this value exists in this portion of the array then we can in this portion of the array then we can say that yes there is a series present say that yes there is a series present else what we can do we can increase our else what we can do we can increase our pointers or we can say we will move pointers or we can say we will move forward and check the difference between forward and check the difference between another two values that is 9 and 7 then another two values that is 9 and 7 then again we'll do the same thing we will again we'll do the same thing we will subtract 7 minus 9 and whatever the subtract 7 minus 9 and whatever the difference will be we will again add the difference will be we will again add the right value to it and then we will check right value to it and then we will check from 2 to 10. so this whole approach from 2 to 10. so this whole approach will take how much time as for left and will take how much time as for left and right right values we need to nested Loops so it values we need to nested Loops so it will take big of n square and then after will take big of n square and then after getting the difference and getting the getting the difference and getting the sum of right value and difference we sum of right value and difference we will check for the existence of the will check for the existence of the arithmetic sequence and arithmetic sequence and in worst case it will take because of n in worst case it will take because of n times so the overall time complexity times so the overall time complexity will be bigger of NQ and we all know will be bigger of NQ and we all know that this is most likely to exceed time that this is most likely to exceed time limit therefore we can't limit therefore we can't proceed with this approach so how we can proceed with this approach so how we can optimize this so now what we will be optimize this so now what we will be doing rather than taking left value and doing rather than taking left value and right value we can take left and right right value we can take left and right as a range as a range so now so now this is our range and what we have to do this is our range and what we have to do is we will check for all the arithmetic is we will check for all the arithmetic sequence in this range sequence in this range and this is how we will be calculating and this is how we will be calculating for all the ranges like for firstly 9 for all the ranges like for firstly 9 and 4 will be arranged then 9 to 7 will and 4 will be arranged then 9 to 7 will be another range then 9 to 2 and then 9 be another range then 9 to 2 and then 9 to 10. in this manner we divided this to 10. in this manner we divided this whole problem into smaller sub problems whole problem into smaller sub problems right and we all know that this approach right and we all know that this approach is known as dynamic programming so we is known as dynamic programming so we will be solving this whole problem using will be solving this whole problem using dynamic programming approach now we know dynamic programming approach now we know that that in dynamic programming we also use in dynamic programming we also use minimization so in this problem where we minimization so in this problem where we can use it we can see it very clearly can use it we can see it very clearly that the traversal that we are having in that the traversal that we are having in this range is going to be repeated in this range is going to be repeated in the next stage or next further the next stage or next further traversals right we can see this portion traversals right we can see this portion is going to be repeated and then this is going to be repeated and then this portion is also going to be repeated so portion is also going to be repeated so how we can cut off the computational how we can cut off the computational time we can or the traversal time we can time we can or the traversal time we can save the result of this traversal so save the result of this traversal so that we can utilize it when we are going that we can utilize it when we are going to Traverse this next range right and to Traverse this next range right and then again we will be storing the result then again we will be storing the result of this traversal so that we can utilize of this traversal so that we can utilize in next traversal and this is how we in next traversal and this is how we will be using the memorization trick too will be using the memorization trick too now let's see how we are going to store now let's see how we are going to store our data and what we are going to store our data and what we are going to store so firstly what we have to store we need so firstly what we have to store we need to check and secondly what will be the to check and secondly what will be the data structure that we will be using data structure that we will be using right so first thing that we can see is right so first thing that we can see is there are elements in Array there are elements in Array and these elements are going to have and these elements are going to have differences differences in the sense we differences differences in the sense we will be calculating differences like for will be calculating differences like for 9 and 4 then for 9 and 7 then for 9 and 9 and 4 then for 9 and 7 then for 9 and 2 then for 9 and 10 so we can see one 2 then for 9 and 10 so we can see one element of array is going to have element of array is going to have multiple differences and with all these multiple differences and with all these differences we know that the ranges keep differences we know that the ranges keep on changing so the length of arithmetic on changing so the length of arithmetic subsequence will also be changing right subsequence will also be changing right right different right different so how we can store this so how we can store this we know that 9 minus 7 is also 2. we know that 9 minus 7 is also 2. and 4 minus 2 is also 2. so only on the and 4 minus 2 is also 2. so only on the basis of difference we can't store the basis of difference we can't store the value right so how we are going to store value right so how we are going to store the value so that we can refer it again the value so that we can refer it again and it should always be unique in some and it should always be unique in some sense so that we can sense so that we can check check in our next step is suppose we are at in our next step is suppose we are at this step this step this is our left pointer and this is our this is our left pointer and this is our right pointer so how we will be storing right pointer so how we will be storing it we will be storing it as right it we will be storing it as right pointer then the difference and the pointer then the difference and the longest subsequence in that particular longest subsequence in that particular range and this is how we will be storing range and this is how we will be storing the values in our data structure the values in our data structure so that when we are going to increase so that when we are going to increase our right pointer suppose it will go to our right pointer suppose it will go to here and we have stored this value so here and we have stored this value so when right is here our left pointer will when right is here our left pointer will be at this place be at this place so every time when we are traversing so every time when we are traversing when we are storing data it will be in when we are storing data it will be in this format and when we will be checking this format and when we will be checking for the existence of that data in our for the existence of that data in our data structure what what we will be data structure what what we will be checking we will be checking left and checking we will be checking left and the difference because in the next step our range is going to be incremented right so we won't be getting the same value but we know that our left pointer is at that value can be at that place right so we will be checking for left pointer and difference if these things doesn't make sense right now not an issue because we will be going through the whole array once using this approaching we will try to visualize the whole approach so at that point of time things will become clear so okay let's start and see how we can solve this example using this approach so at first my right pointer is going to be here and my left pointer is also going to be at this place now one condition that we will always checking is a left pointer should always be less than right pointer then only we are going to check and check that particular image okay existence of subsequence because we know that we need two values to get a difference and then check the existence of arithmetic sequence so when both the pointers are at same position we won't be able to do that so our left pointer should always be less than right pointer now I will be increasing our right pointer and it will go to 4. so now what I am going to do I am going to do write minus lip that is 4 minus 9 difference is minus 5 now I know that we need to check what the existence of left value and the difference in our DP so how we will be storing our DP as we discussed to make the value unique we will be storing right pointer and the difference as a key and the length of the subsequence as the value so right now as I DP or hash map is empty so we will be simply inserting this value how we will be inserting when we are going to insert we will keep write value that is 4 and minus 5 is equivalent to 2 okay so right now these are two elements right then we will increment our left pointer it will become equivalent to right pointer so we step out this nested Loop and we will increment our right pointer so it will go to 7. now what we will do our left pointer will always start from 0 because we have to cover that range as we discussed previously so now our right pointer is at 7 and left pointer is at 9 so what we are going to do is 7 minus 9. the difference is -2 now what we will be checking we will be checking left pointer and the difference that is 7 and 9 and 2 9 and 2 is there in our array in our hash mark no then what we will do we will simply insert write value difference and the length of consecutive sequence now we will again increment our left pointer our left pointer will come here and now what we will check 9 minus 4 this is 3 we know that 9 4 minus 4 and 3 is not present in our hash map so we will be inserting the right value that is 7 and difference that is 3. and the length now we will again increment a left pointer it will become equivalent to a right and we will step out of the nested Loop and again we will increment the right pointer it will go to 2 now we will again check right minus left that is to minus 9 it will be minus 7 then we will check the left value that is 9 and the difference minus 7 is not there in our DP hash map so we will simply insert right value that is 2 and difference as a key and this is the length then again we will increment our left pointer it will come to this place and we will do 2 minus 4 it will be minus 2 now we will check 2 and minus 2 is not there in our hash map so we will insert what 2 and 4 and minus 2 is not there in our hash mark 4 is that left pointer that's my bad and 2 I minus 2 will be inserted with consecutive uh with the subsequence length now again our left pointer is going to be incremented it will be at 7 so what we will check 2 minus 7 so this is minus 5 now again left value that is 7 and minus 5 is not there in our hash map so what we will insert we will insert 2 and -5 equivalent to 2. now again we will increment the right pointer because when we are going to increment a left point it will become equal to right and then you will step out and increment the right pointer it will come to 10 now we will do write minus left that is 10 minus 9 it will be 1 and we know that 9 and 1 is not a key in our hash map so what we will do we will again insert the right and the difference and the length then again increment left pointer this is 10 minus 4 this is 6 we know that 4 and 6 is not there in our hash map so what we will do 10 and 6 equivalent to 2 then we will go to 10 minus 7 that is 3 we know that 7 and 3 is there in our hash map so what we will do we will increment it by a point okay because this was already existing so in this subsequence ring length is going to be increased by 1. now we will again increment the left pointer so it will go to 10 minus 2 this is 8 we know that 2 and 8 is not there so we will insert it that is 10 n 8 equivalent to 2 and now we are done with our old traversal so we can see now our hash map is having all the subsequences and all the lengths are also done so now what we will do we will Traverse this hash map and we will return the maximum length that is this one three so our answer will be free so how much time this whole approach took for returning the answer is because n Square because for left and right ranges we are having nested Loop so the time complexity will be big of n square and a space complexity will also be equivalent to bigger than a square as the size of the array will be equivalent to this one Big O of n Square so now let's try to code this whole approach you will be surprised to see that this approach took this much time for explanation but the code is going to take only five lines so firstly let's let's initialize our hash map then foreign pointer you must be thinking why I am taking right and left from 0 but the thing is this will take care of all the edge cases so that we don't have to you know Define conditions for different edge cases separately this Loop will so these two so these two are going to be are are going to be are Loops at which we will be getting our Loops at which we will be getting our range now in that range firstly what we range now in that range firstly what we will do is will do is we are inserting right we are inserting right and and the values difference right the values difference right so numbers right minus nums left this so numbers right minus nums left this will be the distance and we will check will be the distance and we will check if this already exists what we were if this already exists what we were checking we were checking checking we were checking if left and this whole thing again that is nums right and nums left is existing in r hashmap then take the value and if it's not existing then return 1 because we will add 1 and it will become 2 if the value is not there else it will become 3 or it the value will be incremented by y so this whole condition will take care of our lookup and incrementing part if the value is there then it is going to return the value else we will be getting 1 and we will increment it by 1 so we will get 2 because at the end the length 2 is always going to be there because we will have two values for calculating the difference right and at the end what we have to do we have to return the max of DP Dot values and we are done this was the mold code now let's see if I had done something now it works fine I guess yeah the whole now it works fine I guess yeah the whole solution is submitted and you can solution is submitted and you can see it is quite efficient see it is quite efficient so this was the whole problem although so this was the whole problem although my explanation my explanation might be you know a simplified version might be you know a simplified version of this whole problem but this problem of this whole problem but this problem was not a medium question this problem was not a medium question this problem was a quite hard problem but now we know was a quite hard problem but now we know how to solve it so hope you find this how to solve it so hope you find this video useful and if this video helped video useful and if this video helped you to understand this whole problem you to understand this whole problem then you can like this video subscribe then you can like this video subscribe my channel and soon I will be coming my channel and soon I will be coming with some more questions and if you have with some more questions and if you have few questions that you want me to solve few questions that you want me to solve then you can share them in comment then you can share them in comment section I will definitely try to solve section I will definitely try to solve all those questions and response it for all those questions and response it for this video and I will see you soon with this video and I will see you soon with another question thanks for | 2024-03-25 15:14:30 | 1,027 | Longest Arithmetic Subsequence | LeetCode 1027 | DP | Python Solution |
|
lP2yP8Iy88c | Hello Hi Everyone Welcome To My Channel It's All The Problems Realized And Problems Realized And Civilized GST Socializing Converted Civilized GST Socializing Converted Alphabets Object Into A Sequence Of Which Alphabets Object Into A Sequence Of Which Sadhak Can Be Stored In File Or Memory Sadhak Can Be Stored In File Or Memory And Transmitted Across Network Connection And Transmitted Across Network Connection Link To Be Constructed In The Same And Link To Be Constructed In The Same And Other Computer Other Computer Other Computer Civilized and Mrs Free Word This Problem Is Constructed To-Do List Co Problem One Is Like C Tronic York Phase Problem Problem Gas 108 Constructive Work From Already Problem Solve This Problem Solving Problem Problem Problem Problem Life Enjoy's Problem Solve Place Understand How Will solve this problem is solved Vestige Vestige Vestige 251 and 320 Phase one will do for realization of civilization which will subscribe to subscribe The Amazing Space One Space 354 Sikheta Singh First of Space One Space 354 Sikheta Singh First of all evil spirited person who lives in all evil spirited person who lives in Delhi Ministers And Converted Into A Delhi Ministers And Converted Into A String String Of 2G Live Well And 30 Subscribe Placid In The First Of All The Best All The Food Factory Not Subscribe Like Subscribe And Not From Next Qualities In This Earth End Subscribe Vikas Liquid Form Ko Subscribe Sure Newspaper Today I Will Give We Do Newspaper Today I Will Give We Do Newspaper Today I Will Give We Do Subscribe My Channel I Will Also Help You Subscribe My Channel I Will Also Help You Explain Subscribe Explain Subscribe Channel Thank You Need To Do Anything Just MP Channel Thank You Need To Do Anything Just MP District Wise Subscribe Do District Wise Subscribe Do A Spring Builder Sona Novel Call Rediff A Spring Builder Sona Novel Call Rediff This And This Let Se And Let Me David Feldman This And This Let Se And Let Me David Feldman f-35 virud ndps vpn india and will f-35 virud ndps vpn india and will return hp.com string return hp.com string that singh and prem s well so that will return to its own way and definition of birthday wishes for a deficit and entry no birthday wishes for a deficit and entry no deep rooted in the string Hair withdrawal Hair withdrawal Hair withdrawal benefits also optional in this will return otherwise will happen when you benefits also optional in this will return otherwise will happen when you for the value for the value of root develop subscribe The Amazing subscribe must dot write 210 only our serialization party done using this festival has been created to string using reproduction and after Data Is Data Is Data Is Page No Entry Channel Subscribe String Page No Entry Channel Subscribe String From All No Data Speed Limit Absolutely From All No Data Speed Limit Absolutely Return Return From Truck Tasty Return Return From Truck Tasty That From Also Preorder Traversal Bill 5 This And That From Also Preorder Traversal Bill 5 This And Standard 10 And Did Last Standard 10 And Did Last Indexes Don't Length Minus One So Let's No Indexes Don't Length Minus One So Let's No Improvement Medical Staff Busty Sudhir What Improvement Medical Staff Busty Sudhir What Is The Is The Is The School subscribe The Channel That Advice Will First Aid Vinod Episode Version Lenovo Dates That Involves Dia Fruit of the Tree and Safari So Let's Root is youtu.be Hotspot Subscribe Now For Do Subscribe Index Subscribe Now For Do Subscribe Index Loon This And Subscribe Node Node Which Will Be Loon This And Subscribe Node Node Which Will Be Liberated Soul String Will Be Used For Liberated Soul String Will Be Used For GPS Of Index This Investment Considered In The GPS Of Index This Investment Considered In The Entire And Entire And A Dot Pass Intes Office Start Which Is The A Dot Pass Intes Office Start Which Is The Root Directory In This Will Reduce Root Directory In This Will Reduce Root Directory In This Will Reduce absolutely delayed course to subscribe our Channel and start from not starting boil subscribe must subscribe fruit subscribe pimp node in the river tricks three but 101 in interesting detail 012 Like This Is The Like This Is The Like This Is The Visualizer Tool In The Best Quotes And Will Be Visualizer Tool In The Best Quotes And Will Be Sonal And 5th Sonal And 5th That 2050 Govinda Right Side Soldiers Will Be This That 2050 Govinda Right Side Soldiers Will Be This Is The Bell Next9 So Let's Compile Is The Bell Next9 So Let's Compile NCOS Workings For All The Best Places NCOS Workings For All The Best Places Is Or Actress Work In Flats Submitted 137 Accept 137 Accept 137 Accept civilization is to phone number note Same time complexity of Video then subscribe to the Page if you liked The Video then | 2024-03-18 10:33:38 | 449 | Serialize and Deserialize BST | Leetcode 449 | Recursive DFS | Facebook Amazon Microsoft |
|
0A40XJH_VvE | Hello hello viewers welcome back to tech news hindi video bhi seedha 100 china news hindi video bhi seedha 100 china short position problem wishes from list to short position problem wishes from list to date end of june challenge so let's not date end of june challenge so let's not look at the problem statement the problem look at the problem statement the problem remaining life middle aged person ten writers others remaining life middle aged person ten writers others the video then subscribe to the the video then subscribe to the the video then subscribe to the then subscribe to the Subscribe Tree Not Present So If Elements Of Maintained In Ascending Order And Difficulties Inserted Into Death Six Will Go In Between This 517 Index 512 Index 76306 Goals Between 517 Index Of Beloved Country Land Which Will Push 7.23 100 Index 7 Vikram Thakur Okay so you will just have written in the newly selected element which of this is 100000 laptops subscribe The Veervikram One 100000 laptops subscribe The Veervikram One to 100 to 100 quick events will be shifted by quick events will be shifted by one position so you will just to one position so you will just to one position so you will just to position which element will become doctor 0.5 inches from left side right side you will return lost subscribe and subscribe the Channel and subscribe and subscribe the Channel and subscribe the Channel to do the time subscribe the Channel to do the time complexity of main complexity of main research if you already know its research if you already know its latest latest latest Initially Sufi Applied Sciences You Will Find The Attacks Of A To You Can Simply But What Is The Element Is Not Present In The subscribe and subscribe the 12th Part subscribe and subscribe the 12th Part Plus Minus Point To That Is This Will be late Will be late Will be late suman sur log iljaam bhi point to the same suman sur log iljaam bhi point to the same element aisa hi now you can find the value element aisa hi now you can find the value and welcome to the same point someone will also and welcome to the same point someone will also point 1000 compete with shyokand se 1000 point 1000 compete with shyokand se 1000 festivals -1.2 this point note this loop festivals -1.2 this point note this loop CO2 values of 100 parties CO2 values of 100 parties CO2 values of 100 parties 60 element element after this and exception and when you all the three leather industry element which is the largest fresh water issue index point to my people okay so this point case no if you go out of votes than what you Can You Simply First Form Check Is The President Of Australia And Greater Ahirwal You Can Just Check Which Element Of This Point To Point Tours Plus Points 258 Your Value To Make To Make To Make Plus One Log In No Way Want To 7 Minutes Will Also Plus One Log In No Way Want To 7 Minutes Will Also Be Appointed Seven Day Special To Zulu Value Will Get Updated And This [Music] [Music] Return Just The subscribe research station par use up the phone is subscribe research station par use up the phone is this code words like request you just implement android soeing in this code words like request you just implement android soeing in this paste on this paste on with your target and you can simply with your target and you can simply subscribe and finally target which are you doing this subscribe and finally target which are you doing this you will just subscribe the channel like you will just subscribe the channel like share and subscribe | 2024-03-20 08:49:47 | 35 | Search Insert Position | Leetcode #35 |
|
oSAGmYBc-A8 | um hello so today we are going to do this problem which is part of lead code this problem which is part of lead code January daily challenge January daily challenge so we get an array of strings words that so we get an array of strings words that don't have duplicates this is important don't have duplicates this is important and we want to return all the and we want to return all the concatenated words in the list of words concatenated words in the list of words now what do they mean by concatenated now what do they mean by concatenated words they mean that words they mean that um if it's comprised um if it's comprised of entirely of at least two shorter of entirely of at least two shorter words from this words list okay so it's words from this words list okay so it's a so basically a concatenated word is a a so basically a concatenated word is a word from this list word from this list that can be obtained by concatenating at that can be obtained by concatenating at least two other words right you can least two other words right you can calculate more than two but a two plus calculate more than two but a two plus okay and of course like if you can okay and of course like if you can continue just one that would be the continue just one that would be the initial string itself so that's what initial string itself so that's what makes what it means here so if we take a makes what it means here so if we take a look at this first example you can see look at this first example you can see for example for example um this we have here cats dog and cats um this we have here cats dog and cats and that's just a combination of cats in and that's just a combination of cats in dog so it's it's two plus right it's two dog so it's it's two plus right it's two and then it's a concatenation of them and then it's a concatenation of them entirely like there isn't if there was a entirely like there isn't if there was a x at the in the end this word would not x at the in the end this word would not be a concatenated world because it's not be a concatenated world because it's not entirely comprised of concatenated entirely comprised of concatenated strings from this list okay strings from this list okay so if we take a look here so if we take a look here um so there is this one which is um so there is this one which is comprised of cats dog and cats right comprised of cats dog and cats right then there is this one that has dog then there is this one that has dog Cat's dog so still two here and then Cat's dog so still two here and then this one has rat cat dog cat so it has this one has rat cat dog cat so it has this one this one has this one and then has dog right so has this one and then has dog right so it has even three it has even three um so you get the idea um so you get the idea um now in terms of time in terms of um now in terms of time in terms of terms of constraint here we have the terms of constraint here we have the list of words can be really big 10 to list of words can be really big 10 to the power of four the list of individual the power of four the list of individual the length of the individual words is a the length of the individual words is a little bits on the smaller side so it's little bits on the smaller side so it's 30. 30. um um and so the words are unique this whole and so the words are unique this whole piece is also important so let's see how piece is also important so let's see how we can solve it um okay so how do we solve this so this is an example of the first example we have we have cat cats and then the rest and so how do we how can we think about this in a in a way that we can that we can arrive at the solution so one way to think about it is let's pick for example one of the words let's pick the bigger what do we want to do we want to be able what do we want to do we want to be able to get from a letter the first letter to to get from a letter the first letter to the end using only other words from the the end using only other words from the list list right that's exactly what we want okay right that's exactly what we want okay and so how do we how can we so this is and so how do we how can we so this is that means we want if we try to think of that means we want if we try to think of it in terms of a graph that just means it in terms of a graph that just means we want a path we want a path from index 0 from index 0 to index n minus one to index n minus one and what are the the edges so if you and what are the the edges so if you want a path and you want to use a graph want a path and you want to use a graph then you we need to think about what are then you we need to think about what are the edges well what are the components the edges well what are the components of this word here just letters right of this word here just letters right and their indices right and here you can and their indices right and here you can see if we want a thermostat of a graph see if we want a thermostat of a graph the graph a path is usually from a the graph a path is usually from a source node source node right to a certain destination right to a certain destination so this all if tells us maybe we should so this all if tells us maybe we should try to make the letters be try to make the letters be um be the nodes because we go from one um be the nodes because we go from one letter to the other and that's the path letter to the other and that's the path we want so okay so that means maybe we want so okay so that means maybe let's have a graph for each world so let's have a graph for each world so basically this is for a specific word basically this is for a specific word that we want to check if it's a that we want to check if it's a concatenated word so for each word what concatenated word so for each word what we can do we can do is just um create a is just um create a suppose we have a graph from uh out of suppose we have a graph from uh out of that word that word and the nodes are basically the letters and the nodes are basically the letters of course will represent them with their of course will represent them with their indices indices and then what would be the edges now and then what would be the edges now that that's the question well let's that that's the question well let's think about what would be the solution think about what would be the solution you can't go from you can divide this you can't go from you can divide this into just CA and then TS why is that into just CA and then TS why is that because there is no CA and TS in word because there is no CA and TS in word right and so what the the edges have to right and so what the the edges have to be just from be just from the valid transitions what are the valid the valid transitions what are the valid transitions the about transitions is if transitions the about transitions is if it's a word in this list of words right it's a word in this list of words right so for example from a c to a t that's a so for example from a c to a t that's a valid Edge right valid Edge right and so what we can say here for example and so what we can say here for example this is a valid Edge right let me this is a valid Edge right let me actually write it in a different color actually write it in a different color so what we can say for this one here is so what we can say for this one here is that c to T this is a valid Edge that c to T this is a valid Edge C2 TS is a valid edge here here is a valid one and here's its cat is a valid one in this world so we can create edges like this because why is that because the path that we want to take that we want to end up with has to be just something like cat here it's not cat possible but here the the right the correct path would be to get to the end is going to be cats two dog right to um cats right and by its path I mean you go from C to S you go from D to DJ and then you go from C to S right and so that's exactly the idea here is that let's just create make this be a graph and we can just how can we find a if there is a path from one node to the other in a graph while we can just use and this is the smart idea is that and this is the smart idea is that well there is no Edge between C and A well there is no Edge between C and A because there is no word CA in this because there is no word CA in this world world in the list of words that we are taking in the list of words that we are taking a look at okay a look at okay and so with that idea we can just solve and so with that idea we can just solve our problem right we would have an our problem right we would have an implicit graph that basically if implicit graph that basically if that says basically if that says basically if um let me write this down so if w i j is um let me write this down so if w i j is in the words in the words and maybe we can convert it to a set so and maybe we can convert it to a set so that it's easy to check that it's easy to check then that means basically there is a then that means basically there is a path there is an edge path there is an edge um um from I to J from I to J okay so that's the main idea here that okay so that's the main idea here that we are going to apply now there is one we are going to apply now there is one caveat though caveat though um so from this C what about from this C um so from this C what about from this C here here to the last s right for this world to the last s right for this world does if there if there is a path should does if there if there is a path should we say this is a concatenated word well we say this is a concatenated word well no because the problem says at least two no because the problem says at least two right and it needs to be different right and it needs to be different towards not the word itself right and so towards not the word itself right and so but this is a word in the list of words but this is a word in the list of words so it is a valid Edge according to our so it is a valid Edge according to our graph definition so how do we avoid that graph definition so how do we avoid that well we can just do the check when we well we can just do the check when we are doing the traversal to find the path are doing the traversal to find the path we can just make sure that I either I is we can just make sure that I either I is different than zero different than zero or J is different than the or J is different than the um um then n just so that we don't then n just so that we don't we don't count this Edge right so for we don't count this Edge right so for each word we don't want to count the each word we don't want to count the edge that constitute the world itself edge that constitute the world itself right so that's the only distinction but right so that's the only distinction but otherwise the rest should be the same otherwise the rest should be the same um okay so let's take a look maybe at um okay so let's take a look maybe at the second examples and applied there so the second examples and applied there so the second example is cat the second example is cat dog and then cat dog right so what we dog and then cat dog right so what we will do is will do is we'll run through the example so first we'll run through the example so first cat Okay and we'll just say cat Okay and we'll just say um go through the do a DFS for I so I um go through the do a DFS for I so I will start here and we'll check for All will start here and we'll check for All J's right that are that are from I here J's right that are that are from I here so I'll say is C so I'll say is C so is the basically is the w i j here is so is the basically is the w i j here is this a valid this a valid um Edge is I to j a valid Edge well it's um Edge is I to j a valid Edge well it's not because there is no C in the list of not because there is no C in the list of words right this is not in the list of words right this is not in the list of words words so it's not a valid Edge and so we move so it's not a valid Edge and so we move our chain here our chain here is CA which is w a j a valid Edge no is CA which is w a j a valid Edge no it's not right so we move j again this T of value is um I to t a valid C to T here which is I to j a valid world yes it is right but the problem is that I is equal to 0 and J is equal to um the end of the string and so this is not what not the image we should take because it's the word itself and so this one would fail this check here the chin okay and so we would we would not count this will not add it to our results so our result is still empty and then we do we move I so we move I uh we want to try all substrings uh do we move I know we we wanna we wanna get the entire path so we don't move I so we try the next World which is dog and so now I is here J is here same thing D is not a valid Edge we move j is d o a valid Edge it's not in the string so it's not valid we move j is Doug a valid Edge yes but it felt this condition because this is the word itself so we don't use it and now what it becomes interesting is now we look at CAD dog okay so I Starts Here J Starts Here we move because C A is not a valid Edge cat is a valid Edge so this is why it becomes interesting so cat is a valid Edge and it's it's not it doesn't uh it passes this condition so it's different than I is different than z i is equal to zero right but J is smaller than n so this one is a is valid for this condition and so that means we need to add to our result uh we need to say we need to go next right so so this means basically this is a valid portion and so we advance our eye here just DFS right we found the first uh we found the first Edge and now we we want to continue our path to find a path to the end so I becomes here J is here we move j here now we have d o not in the list move j here Doug is in the list and I is different than zero and so this is a valid Edge right and then when we reach the end and minus one here or or we can say n because we will increment when we reach the end that means we are done right and we are done and there was a path and so we'll say um that this is a valid concatenated word and we'll add it to the list I hope that made sense um I think it will be even more clear with the implementation but essentially we are creating a graph where for each word we will go through each word in the list and to check if it's a concatenated world we will have an implicit graph where the nodes are the letters and the edges are the um are are constructed using the words in the list so there is an edge if from I to J if W from I to J is in the list of words right and you want to find a path using DFS from 0 to the end of the the string word um such that there are words in between right it's not just zero to n minus one we want towards in between because that's what the problem says it's at least two um words at least constructed from at least two words right so that's what we want um so that's the idea and so graph nodes are the the letters edges are the based on the words in the list and we do the fs pre-shred so let's implement it and um okay so the supplement the solution um okay so the supplement the solution we just um saw in the overview so what we just um saw in the overview so what we need to do here is we need to do here is um um so first we need to do um our word set right and so this is um and then we need to go through each um and then we need to go through each world right world right so this is just to to be easy to easily so this is just to to be easy to easily be able to check if a substring right be able to check if a substring right from I to J is part of the list of words from I to J is part of the list of words because that's exactly what determines because that's exactly what determines if there is an edge or not okay so here if there is an edge or not okay so here we'll just go through the list of words we'll just go through the list of words um and um and the second step is to the second step is to um of course do DFS as we said for that um of course do DFS as we said for that word and we'll start at zero because word and we'll start at zero because remember our nodes are the the letters remember our nodes are the the letters indices and this is the starting node indices and this is the starting node and we want to check if there is a path and we want to check if there is a path to a n minus one so this checks if there to a n minus one so this checks if there is a path is a path uh from 0 to n minus one uh in the graph uh from 0 to n minus one uh in the graph of words of words set right set right and so that's exactly what we need here and so that's exactly what we need here is to define a DFS function that is w is to define a DFS function that is w what it is fixed and then I is just the what it is fixed and then I is just the um the node that is that will Traverse um the node that is that will Traverse okay and of course for DFS we need a okay and of course for DFS we need a visited set and we start out with just visited set and we start out with just zero because that's what pass here and zero because that's what pass here and then when do we end we end when we reach then when do we end we end when we reach the end of this string right and so the end of this string right and so let's define the end of the string it's let's define the end of the string it's just the length of the of what just the length of the of what and if we get here that means we are and if we get here that means we are good and so we want to add this word good and so we want to add this word because this means basically we found a because this means basically we found a path right so this means we found a path path right so this means we found a path uh from 0 to n minus 1. uh from 0 to n minus 1. um using or or n the N right using words um using or or n the N right using words from what it's set from what it's set okay okay um of course um it's not the world itself um it's not the word itself that's something we'll pay attention to we'll take care of it down the road so here this means we want to add it to the list of results right because it's a it's a valid one basically if we find the path so here we'll just need to define the so here we'll just need to define the list that we want to return that gets list that we want to return that gets filled by DFS and so here we just filled by DFS and so here we just written that list and now let's define written that list and now let's define the chord of our DFS here so what we the chord of our DFS here so what we need to do is we need to check if there need to do is we need to check if there is a if there is a path from I to J if is a if there is a path from I to J if there is an edge like this then that there is an edge like this then that means let's consider this one means let's consider this one a portion of the path and then let's a portion of the path and then let's check if there is a path from J to uh n check if there is a path from J to uh n right because right because we found a path from a to J and so to we found a path from a to J and so to find if there is a path from I to n we find if there is a path from I to n we just need to find if there is a path just need to find if there is a path from J to n and this can be by the way from J to n and this can be by the way multiple steps right it doesn't have to multiple steps right it doesn't have to be like direct Edge right we can have be like direct Edge right we can have multiple other steps in between multiple other steps in between um so here we just want to try all of um so here we just want to try all of them right so try all so we want to try them right so try all so we want to try all the all the let's say we have CAD dog right what we let's say we have CAD dog right what we did is we tried this C to see if it's a did is we tried this C to see if it's a valid Edge from zero to zero and then we valid Edge from zero to zero and then we tried C A to see if it's a valid Edge tried C A to see if it's a valid Edge and then we tried cat right so each time and then we tried cat right so each time we try a different J and check if there we try a different J and check if there is an edge if there is an edge then we is an edge if there is an edge then we continue from J and so here that means continue from J and so here that means we will go we'll do exactly that it we will go we'll do exactly that it and we will say so we need to go to I and we will say so we need to go to I because we want to check the letter because we want to check the letter itself itself um and I'm doing n plus 1 here just um and I'm doing n plus 1 here just because of python to get the entire because of python to get the entire let's say we are here we want to get the let's say we are here we want to get the entire string entire string um so how do we check if it's an edge um so how do we check if it's an edge well we just check if it's part of the well we just check if it's part of the words set here so if this is this means words set here so if this is this means this is a word but we need to safeguard this is a word but we need to safeguard against just taking the entire world so against just taking the entire world so how do we do that we just check how do we do that we just check um that either I is bigger than zero um that either I is bigger than zero which means it's it's something like which means it's it's something like this so it's not the entire world or J this so it's not the entire world or J is not the end which means it's maybe is not the end which means it's maybe something like this something like this or something like something like this to or something like something like this to the beginning or something like this to the beginning or something like this to the beginning right so we check J the beginning right so we check J different than the end okay but we also want to make sure it's not visited we don't want to visit the same nodes twice that's just general DFS logic right and so to do that we want to check here and J not visited okay so if all of these are correct then we want to add it to the list of visited of course but we want to also call DFS and proceed and check if there is a path from J to n okay if there is a path we'll reach here and we will add the word and so the world would be a has a the path will contain W from I to J and then some other path from J to n okay and that's pretty much it here um pretty sure fold once you get the idea of using the letters um as as nodes and the and the words here as edges and so if we submit this and that passes our test cases right um you could of course do this DFS um in a iterative way and I think that solution is a is a little bit easier to work with first um so yeah uh as an exercise for you try to do it with iterative DFS um but yeah I think that's pretty much it for this problem please like And subscribe and consider supporting me on | 2024-03-22 15:18:58 | 472 | Leetcode 472: Concatenated Words |
|
DJUI_jCvBHo | hey everyone welcome back and today we will be doing another lead code 598 will be doing another lead code 598 range Edition 2 an easy one you are range Edition 2 an easy one you are given an MX and Matrix M initialized given an MX and Matrix M initialized with all 0 and array of operation oops with all 0 and array of operation oops where oops at I is equal to where oops at I is equal to you can say a limit or a range we are you can say a limit or a range we are provided so means M at X and Y should be provided so means M at X and Y should be incremented according to the range we incremented according to the range we are given and count and return the are given and count and return the maximum integers in The Matrix after maximum integers in The Matrix after performing all these operations performing all these operations so we are given a three by three Matrix so we are given a three by three Matrix as by our rows and columns n will be the as by our rows and columns n will be the columns n will be the rows and N will be columns n will be the rows and N will be the columns and you are given a range the columns and you are given a range two by two so they are basically saying two by two so they are basically saying uh increase or increment the two by two uh increase or increment the two by two column so two rows and two columns will column so two rows and two columns will be incremented by one and the rest will be incremented by one and the rest will not be incremented and in the next not be incremented and in the next they're saying increment three rows and they're saying increment three rows and three columns so the whole Matrix will three columns so the whole Matrix will be updated and incremented be updated and incremented so return the maximum number uh count so so return the maximum number uh count so 2 is coming four times in our Matrix and 2 is coming four times in our Matrix and will be returning 4 in that case will be returning 4 in that case so what we'll be doing is just making uh so what we'll be doing is just making uh variables which will hold our variables which will hold our rows and columns rows and columns so this will be n and for I so this will be n and for I in range of the length in range of the length of the operations we are given of the operations we are given so for m r is equal to the minimum of so for m r is equal to the minimum of Mr itself and oops at I and Mr itself and oops at I and 0 and MC will be the minimum of m c 0 and MC will be the minimum of m c itself and oops at I at one itself and oops at I at one so so we can just return after this the Mr we can just return after this the Mr product MC so what this will be doing is product MC so what this will be doing is we have like this whole Matrix and we have like this whole Matrix and operations and you can say a matrix operations and you can say a matrix three by three three by three so the m r will be initialized as 3 and so the m r will be initialized as 3 and declared and MC will be 3 3 so they both declared and MC will be 3 3 so they both are 3 3 starting from the very start are 3 3 starting from the very start like this from the very beginning and like this from the very beginning and now the m r will be updated by 2 and MC now the m r will be updated by 2 and MC will also be updated by 2 in this first will also be updated by 2 in this first iteration because the value is in the iteration because the value is in the first operation is 2 and in the next one first operation is 2 and in the next one it's going to increase so the minimum it's going to increase so the minimum will not be updated and we can just will not be updated and we can just return the product of these two which return the product of these two which will before that's why uh will before that's why uh it that's why we are going to return for it that's why we are going to return for so let's submit it | 2024-03-20 12:12:27 | 598 | 598. Range Addition II | Leetcode | Python |
|
L8DDTF9LkKY | hello friends so today we're gonna discuss discuss another problem from lead code which is another problem from lead code which is a hard problem a hard problem on bit manipulation the problem name is on bit manipulation the problem name is maximum score words form by letters maximum score words form by letters it states that you are given a word list it states that you are given a word list and some letters add the score of each and some letters add the score of each letter letter so in simple terms you are given some so in simple terms you are given some letters or actually words and there are letters or actually words and there are certain letters you can used so as you certain letters you can used so as you can see can see some letters are repeated which means some letters are repeated which means that you can also use these wrappers that you can also use these wrappers like you can only use like you can only use a but you can use a two times a but you can use a two times what i mean by this is you can assume what i mean by this is you can assume that this is a bag okay which consists that this is a bag okay which consists of of two times a one times c two times or two times a one times c two times or like three times d like three times d and so on now you can only use these and so on now you can only use these letters letters and the score you can get to use a is and the score you can get to use a is one one so if you again use a you'll also get so if you again use a you'll also get again one the score to uc again one the score to uc is nine the score for using d only once is nine the score for using d only once is five is five and so on now you can only use and so on now you can only use these letters and you have to form these letters and you have to form some of these words such that you have some of these words such that you have to to maximize the score but in simple terms maximize the score but in simple terms as you can see in the example as you can see in the example for the first for the first example for the first for the first example because you have one word like one like because you have one word like one like a a give you a score of one c give your give you a score of one c give your score of nine please give your score a score of nine please give your score a five and so on five and so on now if you form the word dad you require now if you form the word dad you require two d two d and one a which you have and for and one a which you have and for forming the word good you need one g two forming the word good you need one g two o's and one more d and because you have o's and one more d and because you have two d's you can also find to do this out two d's you can also find to do this out now you cannot make dog like though you now you cannot make dog like though you can make dog d o g can make dog d o g but now you do not have one more d i but now you do not have one more d i hope you get the point hope you get the point so you have to only use these words only so you have to only use these words only once once or like you can assume this to be a bag or like you can assume this to be a bag and you can only use or take out these and you can only use or take out these words words it means that you have two a's whatever it means that you have two a's whatever word you can fit inside word you can fit inside so that you have to form some words so so that you have to form some words so that you have to maximize the total that you have to maximize the total score you have score you have and that's the whole problem now what and that's the whole problem now what you can see in this problem is you can see in this problem is the constraints the word length is 15 the constraints the word length is 15 14. 14. whenever you see that the number of whenever you see that the number of words words the word length which means that the the word length which means that the length of the array of these words length of the array of these words is up to 14. whenever you see like up to is up to 14. whenever you see like up to like 20 something like that like 20 something like that then you can easily do this in like in then you can easily do this in like in by forming out all the subsets which by forming out all the subsets which means that because you can form out means that because you can form out sorry you can use different subsets now sorry you can use different subsets now because you can format that okay because you can format that okay let's zoom in one case i i only form let's zoom in one case i i only form this word this word or i form this and this word i formed or i form this and this word i formed this and this word this word and these this and this word this word and these three words three words so you have to first take that that i so you have to first take that that i have to form different subsets have to form different subsets and because the length is very small so and because the length is very small so in bit manipulation in bit manipulation in simple integer format you have 32 in simple integer format you have 32 bits bits okay but in simple terms that in 32 bits okay but in simple terms that in 32 bits like you can do like you can do your operations like in ofn you can do your operations like in ofn you can do it with 22 it with 22 like 2 to the power 20 also which is like 2 to the power 20 also which is also like small enough also like small enough so what you can simply do in this so what you can simply do in this problem is sorry problem is sorry because the constraints are small what because the constraints are small what you can easily do here is iterate over you can easily do here is iterate over all the possible subsets all the possible subsets so what you can do here is if you know so what you can do here is if you know that that or actually know that how to interval or actually know that how to interval every possible subset every possible subset in simple terms you can use bit in simple terms you can use bit manipulation manipulation so i'll tell you in simple terms yeah so as you can see what we can do in simple terms is i draw it out first so let's assume that i have some words let's this is the first word second word third word and so on then because there are three words i will define this by a three bit number a three bit number the maximum three bit number is one one one which is equivalent to 8 or sorry like 2 to the power of 0 plus 2 to the power of 1 2 to the power of 2 which is equivalent to 7 okay now what you can easily do in this problem is it take over all the possible numbers of one two three four five six seven now every number will represent one subset that's the beauty of this bit manipulation what you can think over here is like one is like this which means that i'm taking out this subs uh i'm creating a subset which consists of only this third number like this third word the next can be two which is like one this which means i'm taking a subset of only two the three is this which means that i'm taking out a subset of this this and not this this is actually the bit representation of 3 like this number like 0 1 1 so that's what i'm doing i'm representing or taking all the numbers from 1 to 7 and representing in in its bit representation and then finding out whether the like the particular bit is on or off if it is on then take that number or take that word in our subset then if you have taken like okay i'm taking out these two words then what we'll do we have to ensure that whatever characters these two words have we should have in the bucket we have or the like the set we have so we'll what we'll do whatever words we have taken will find out the frequency or the or like the number of characters we have in these words so we will make a frequency map and store out all the words which we have taken in the subset find out the frequency and store them in this map and we also have the frequency for every word we have here also so we'll just match out that whatever frequency we have in this bucket we have and the number of words or characters be required it should be less than or equal to the bucket characters we have like everything should be satisfied okay maybe it has some z and it doesn't have set then it is false or if it it has one z it has three z then it is fine because like my bucket at three set and i only require one z so it's fine but it should not overshoot or it should not be deficient if it is if it is possible then it's okay and if it is okay then this subset is possible if this subset is possible then what we'll do we'll iterate over every character and then the total score will be that okay these number of characters are required so the score is this character and the vertical character value so i have used three a's the total value we have used is three into the value of a so the value of a is let's assume that capital a capital a is the score for a so we have also the scores for every character so the final answer is how many times we have used the particular character and the score for that character and we have to add them out and then we have to maximize that value over all the possible subjects i hope you understand the like somewhat the logic part we'll go through the code part nowadays and make it more clear so what we'll do first here is we have this bucket of different characters we have so we'll first like make a frequency map to store out the frequency of these so that we can easily match them out further in the code so we'll iterate over every possible letters it is stored in this vector and then just making a frequency map that how many times a is present b is present and so on and just updating it out so that in this frequency map f at the position zero we have how many a's are there at the position one how many b's are there and so on in this bucket we have then we have to maximize my answer initializes zero then as you can see we have to find out that we have to iterate over all the possible subsets so if we have let's assume that five numbers then i have to make a maximum number which has five bits how we can form that if i left shift one by five positions which means that i have left shifted one by five position then i will actually get a number which is having five bits and that's the number we have to iterate over so that's what we have done we have left shift this by five numbers then we have to it from one till all these numbers and then it actually represent all the subsets then for every subset what we'll do we have to make a frequency map which stores that how many different like how many characters each word have so we'll iterate over every word and we'll check that whether this particular word is in the subset we are talking about so we'll do an and operation to check that whether this particular word is in the subset we're talking about so we'll do it so if the word is in the subset then the particular bit is on so what i mean by this is if some particular word is in the subset the the corresponding bit should be on one so we are checking that particular bit is on if it is on then we'll iterate over the word and for that particular word we'll find out what are the characters present in that word and we will update this in this capital f frequency map so after that we have two frequency map one is the frequency map for the particular words we have and one frequency map which is actually storing out all the characters which we have now after training or after using one subset then we have to check that whether the particular words we have used is like sufficient too satisfied like they can be easily satisfied by the bucket we have and then we let it over all the possible characters and we just have to check that whether the number of words we have it should be greater than or equal to the particular character we want if it is fine then if they are not greater then we have to make them false which means that like we don't have or we do not get we like we cannot take this subset because this is not valid if it is valid if the flag is true and what we'll do which means that my bucket is sufficient enough to make out these words which we have taken in the subset will iterate over all the port like possible characters and the total score is the character particular character score into how much that character is present and we will add it over all the possible characters and we have to maximize my answer in the end we have to just output the maximums i hope understand the logic and the code part for this problem if you still have any doubts you can mention on i'll see the next one until | 2024-03-19 17:34:31 | 1,255 | 1255. Maximum Score Words Formed by Letters | LEETCODE HARD | LEETCODE | BIT MANIPILATION |
|
AXfCV7z7pb4 | hello everyone welcome to date headings of april youtube challenge and i hope all of you are having a great time my name is sanchez i'm working a software developer for at adobe and today i present day 656 of daily lead code challenge the question that we have in today's spiral matrix here in this question we are given a positive integer n and we need to generate a matrix of size n cross m filled with elements with values starting from 1 up till n square so we have to fill in the values starting from 1 up till n square because in total there will be n square elements and this is the way that using in which we have to fill in these elements in a spiral form to your surprise we have solved a similar kind of a question but not the exactly same which was spiral matrix one so if you carefully look at this particular question then here we were given a matrix size m cross n and we need to print elements in the spiral order so the problem reduces to identifying how to iterate in spiral order so in case if you have you guys have already solved this question or seen the video of this question then this question should be a cakewalk for you however in case not then i will tell you on how to iterate in a matrix in a spiral order in this video itself so let's get started with the presentation and let's quickly hop onto it where i'll be explaining this algorithm as well as walking you through the test case lead code 59 spiral matrix 2 it's a medium level question on lead good and i totally feel the same also in case if you have any doubt with respect to solving this question in general or if you want to ask something from me please feel free to ping on the telegram group of coding decoded or the discord server both the links are mentioned in the description below now let's get started with the question here the value of n that is given to us is 3 that means we need to create the matrix or size n square the total number of elements will start from the range of 1 up till 9. what do we do in this question the first and the foremost thing is to create four pointers the starting row pointer the ending row pointer the starting column pointer the ending column pointer and appropriately set their values these will be set to 0 this will be set to 2 n minus 1 starting column will be set to 0 ending column will be set to n minus 1 which is again 2 and let's start the traversal in the first scope we will be moving from the left to right direction starting from the starting row so the row row parameter remains constant across this reversal whereas the columns keep on changing as a result of which we will be moving and filling in data at starting row matrix of starting row and the variable parameter here would be equal to j and j will line the range of ending starting column up till ending column so we will fill in data over here matrix of starting row and j will be the variable parameter whose range will start from starting column up till ending column makes sense to all of you i believe so this is the first iteration that we are going to do so let's do that iteration we'll create a variable and let's initialize it to one so let's fill one here then increment as we progress along the iteration to 2 then we have 3 once we are done with this traversal we have to move in the downwards direction something over here and as soon as we are done with this what we will do we will update the starting row pointer to the next point location which would be this one so starting row now it now points to here i'll tell you why i am doing this but just remember that as soon as we are done with this iteration don't forget to increment the starting row pointer now we are interested in moving towards the downwards direction which is this one so which parameter will remain constant over here the y param the j parameter will remain constant which is ending column so ending column will remain constant and the variable parameter here would be i and i would start from the range of starting row up till the ending row so we will fill in matrix of i comma ending column and i will start from the range of starting row up till ending row and now you understand the reason why i incremented sr the starting row pointer it was because so that three doesn't get added or consume overwritten by the vertical iteration that we are doing in this direction as a result of which we previously updated starting pointer so let's shoot for it so we have four then we have five pretty awesome we are done with this iteration and remember up once we are done with this iteration what we should do we should update the value of ec ec will now point to one location before which is we will reduce the pointer for ec so ec now points to this particular location because we have iterated over the last column completely let's start the iteration in the next direction which would be this one so what is the constant parameter over here the constant parameter over here is e r that means we will fill in this particular row so the static parameter is er and the variable parameter is j j will start from the range of ending column to starting column remember this time we are moving in the reverse direction not from left to right but from right to left so ec to sc and let's fill in data over here we got six we got seven and once we are done with this iteration remember what we should do we should update the er pointer er is gonna get reduced by one unit so now er points to this particular once we are done with this let's shoot once we are done with this let's shoot for the final iteration towards the for the final iteration towards the upwards direction and by light rating in upwards direction and by light rating in this particular direction which this particular direction which parameter will remain constant starting parameter will remain constant starting column will remain constant that means column will remain constant that means the variable parameter would be i the variable parameter would be i so we will fill in so we will fill in i matrix of i comma i matrix of i comma starting column starting column and i will line the range of and i will line the range of we are right now at the ending row we we are right now at the ending row we are going towards the starting row so e are going towards the starting row so e r r to to s r s r and d r is pointing to this particular and d r is pointing to this particular location sr is also pointing to this location sr is also pointing to this particular location particular location as a result of which we'll simply fill as a result of which we'll simply fill in eight over here in eight over here this process can continue as we have this process can continue as we have more elements in our matrix but right more elements in our matrix but right now there were only nine elements so the now there were only nine elements so the next iteration is pretty simple you can next iteration is pretty simple you can do it by yourself and here we will get do it by yourself and here we will get nine so when is the breakage condition nine so when is the breakage condition the breakage condition is really simple the breakage condition is really simple till the time my sr is less than equal till the time my sr is less than equal to er and my starting column is less to er and my starting column is less than equal to my ending column i'll than equal to my ending column i'll continue filling in data in my matrix in continue filling in data in my matrix in this order that i have just told and this order that i have just told and this is the crux of the problem so there this is the crux of the problem so there are four steps involved in it first you are four steps involved in it first you are moving from left to right direction are moving from left to right direction you are keeping the starting row you are keeping the starting row constant the variable parameter here is constant the variable parameter here is j as i have told here the range for j j as i have told here the range for j will lie from starting column up till will lie from starting column up till ending column once we are done with this ending column once we are done with this iteration we should increment the value iteration we should increment the value of starting row it will point to this of starting row it will point to this particular location particular location this one this one as we did and then it's time to move in as we did and then it's time to move in the downwards direction which is this the downwards direction which is this here the variable parameter would be i here the variable parameter would be i it will range start from sr to er and it will range start from sr to er and the fixed parameter would be the fixed parameter would be ending column which is this one ending column which is this one and once we are done with this what we and once we are done with this what we should do we should reduce the should do we should reduce the ending column pointer ending column pointer it got reduced to this particular it got reduced to this particular location and now it's time to move location and now it's time to move towards the left direction which is this towards the left direction which is this let me just change the color of pen which is this here what do you see we see that the variable parameter happens to be j the row index remains constant and in the static ending row whereas j starts from ec to sc and once we are done with this what we should do we should reduce the er pointer we reduce the year pointer and now the final call where we are moving towards the up direction here the variable parameter is i again and the starting column or the column index remains constant which is sc the i parameter starts from er and goes up till sr so this is the crux of the problem these are the four directions that we are traversing in i'll be exactly following the same steps as i've just talked here and let's quickly hop onto the coding section to actually see everything in action here i've created my answer matrix if my n happens to be 0 what do i do i simply return the empty matrix otherwise i go ahead and create those fourth pointer starting row ending row starting column ending column and i created a count variable till the time my starting row is less than equal to my ending row my starting column is less than equal to my ending column this is the breakage condition if this breaks we get out of the loop what are we going to do first move towards the right direction what is the variable parameter here j is a variable parameter here the starting node remains the same and with each iteration we move from the starting column going up till the ending column and we allocate the count variable to ans of starting matrix comma j and with each iteration we increment the count variable once we are done with this we simply go ahead and increment our starting row pointer now it's time to move in the downwards direction and this time the variable parameter is i it will start from start row goes up till end row and the constant parameter would be end column once we are done with this we should decrement the end column pointer and now comes the case if my starting row is less than ending column that's another safety check what do we do we move towards the left direction here the ending row remains constant whereas the variable parameter is j which starts from ending column goes up to starting column and once we are done with this we decrement the ending row pointer once we are done with this again we go for a safety check here and followed by moving towards the top direction here the constant parameter is starting column that means j value is fixed i value is variable and once we are done with this we simply increment our starting column by one n really simple guys exactly same steps as i just talked in the presentation so let's quickly submit this up accepted the time complexity of this approach is order of n square and space complexity is again order of n square this brings me to the end of today's session i hope you enjoyed it if you did please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more update from coding decoded i'll see you tomorrow with another fresh question but till then goodbye your friend your mentor your catalyst in this journey of | 2024-03-20 10:44:10 | 59 | Spiral Matrix II | Leetcode 59 | Matrix 2D 🔥🔥 | Live coding session |
|
mOpCUBaMBWM | hello and welcome to another video in this video we're going to be working on this video we're going to be working on campus spikes campus spikes 2 and in the problem you have a campus 2 and in the problem you have a campus that's a 2d grid and there are n workers that's a 2d grid and there are n workers and m bikes with n less than or equal to and m bikes with n less than or equal to M each worker and a bike is a 2d M each worker and a bike is a 2d coordinate on a grid like this we assign coordinate on a grid like this we assign one unique bike to each worker such that one unique bike to each worker such that the sum of the Manhattan distances the sum of the Manhattan distances between each worker and their assigned between each worker and their assigned bike is minimized return the minimum bike is minimized return the minimum possible sum of Manhattan distances possible sum of Manhattan distances between each worker and their signed between each worker and their signed bike the Manhattan distance is and I bike the Manhattan distance is and I think this uh is used in a lot of think this uh is used in a lot of problems it's just the absolute value of problems it's just the absolute value of the difference of the x's and the the difference of the x's and the absolute value difference of the Y's so absolute value difference of the Y's so if we take a look at the examples here's if we take a look at the examples here's one example where you have two workers one example where you have two workers and two bikes so you can kind of tell by and two bikes so you can kind of tell by like an IT test what you'd want to do like an IT test what you'd want to do here so you'd want to assign this worker here so you'd want to assign this worker to this bike which would give you to this bike which would give you Manhattan distance of three and this Manhattan distance of three and this over here would give you another over here would give you another Manhattan distance of three right one Manhattan distance of three right one two three one two two three one two three three and in the second uh example you can and in the second uh example you can also kind of like it test it so this also kind of like it test it so this will give you one then this will give will give you one then this will give you another one and then this will give you another one and then this will give you two so that's the shortest so that's you two so that's the shortest so that's four total and there's a third example four total and there's a third example but that number is like way too big and but that number is like way too big and kind of useless so I didn't show it here kind of useless so I didn't show it here but anyway so the constraints are we can but anyway so the constraints are we can have n workers and m bikes and basically have n workers and m bikes and basically you will have um the number of bikes you will have um the number of bikes will at least be equal to the workers will at least be equal to the workers and they will both be 10 or less and and they will both be 10 or less and then basically they just show you that then basically they just show you that like you'll have an array in workers like you'll have an array in workers that every element will have an X and Y that every element will have an X and Y and same thing for the and same thing for the bikes and here are the values which bikes and here are the values which isn't super important and all the bikes isn't super important and all the bikes and uh workers are unique so you don't and uh workers are unique so you don't have to worry about like duplicates or have to worry about like duplicates or anything so basically you have to assign anything so basically you have to assign a bike to each worker and there might be a bike to each worker and there might be more bikes than workers and we have to more bikes than workers and we have to minimize this minimize this distance and from the constraints um and distance and from the constraints um and just from like looking at the just from like looking at the problem you should try to get to the problem you should try to get to the conclusion that which is like reasonably conclusion that which is like reasonably obvious that or maybe there is something obvious that or maybe there is something better but there isn't like some super better but there isn't like some super good way to do this right because the good way to do this right because the constraints are really small and it's a constraints are really small and it's a medium problem so the chances are there medium problem so the chances are there isn't some way to do this like super isn't some way to do this like super efficiently um so one thing you can efficiently um so one thing you can think of is just doing like a think of is just doing like a backtracking right where you would just backtracking right where you would just basically just try to guess which worker basically just try to guess which worker will get each bike you just try like all will get each bike you just try like all combinations right you just try to like combinations right you just try to like assign a bike to a worker and then you assign a bike to a worker and then you try to assign another one and so on so try to assign another one and so on so what's that going to look like so let's what's that going to look like so let's say worst case we have 10 workers and we say worst case we have 10 workers and we have 10 bikes so basically what that's have 10 bikes so basically what that's going to look like is it's going to be going to look like is it's going to be something like every worker will get um something like every worker will get um a bike so the first worker you'll have a bike so the first worker you'll have to try 10 bikes and then for the second to try 10 bikes and then for the second worker there will be nine bikes left and worker there will be nine bikes left and then for the third worker there will be then for the third worker there will be eight B bikes left and then so on and so eight B bikes left and then so on and so on and so on so this is basically 10 on and so on so this is basically 10 factorial which actually if we Google it factorial which actually if we Google it it is small enough to pass so that's one it is small enough to pass so that's one way to do it and so for this type of way to do it and so for this type of problem there's usually two ways of problem there's usually two ways of doing it so I'm going to do the less doing it so I'm going to do the less intuitive one um so backtracking you intuitive one um so backtracking you could do that where you basically just could do that where you basically just backtrack and you just try to randomly backtrack and you just try to randomly assign not randomly but try to assign assign not randomly but try to assign bikes to the workers so you can just bikes to the workers so you can just have like a normal backtracking template have like a normal backtracking template and do that but we're going to be doing and do that but we're going to be doing a DP a DP solution and so for DP we need a couple solution and so for DP we need a couple things right so we need things right so we need State base case and recursive and so State base case and recursive and so this is a this is a good one for DP to this is a this is a good one for DP to practice because the state isn't super practice because the state isn't super obvious right like how do we how do we obvious right like how do we how do we keep track of like what state we're on keep track of like what state we're on what's our base case and so on so when what's our base case and so on so when you can keep track of basically we want you can keep track of basically we want to know for each worker we want to to know for each worker we want to assign them a bike but when we assign assign them a bike but when we assign them a bike we want to make sure that them a bike we want to make sure that that bike is no longer available so we that bike is no longer available so we can write that down for each can write that down for each worker try to assign a worker try to assign a bike from a available bike from a available bikes and then recurse to some state bikes and then recurse to some state where that bike is no longer available where that bike is no longer available okay and this is like reasonably common okay and this is like reasonably common it's like a a little bit tougher version it's like a a little bit tougher version of a DP problem so you basically have a of a DP problem so you basically have a small number of items that you need to small number of items that you need to distribute right you can only have 10 distribute right you can only have 10 bikes and once you give a bike to bikes and once you give a bike to someone once you say like I used it I someone once you say like I used it I need to make sure it's no longer need to make sure it's no longer available available and how do I have a state that and how do I have a state that represents that so the way to do this represents that so the way to do this and this will only work when you have a and this will only work when you have a small number of bikes but in this case small number of bikes but in this case we do is using a bit mask so essentially we do is using a bit mask so essentially we're just going to say for our bikes we we're just going to say for our bikes we are going to initialize it to like let's are going to initialize it to like let's say we have 10 bikes we'll just have or say we have 10 bikes we'll just have or let's use a smaller thing to demonstrate let's use a smaller thing to demonstrate e say we have five bikes we can just e say we have five bikes we can just have something like this where these are have something like this where these are the bikes and then anytime we pick a the bikes and then anytime we pick a bike and we're actually going to index bike and we're actually going to index them backwards so if our bikes are you them backwards so if our bikes are you know zero index one index two index know zero index one index two index three index four index uh we will index three index four index uh we will index them backwards so if this one's them backwards so if this one's available this will be index 0 1 2 3 and available this will be index 0 1 2 3 and four and essentially what we do then is four and essentially what we do then is if we say we want to use the bike like if we say we want to use the bike like let's say we're going to Loop through let's say we're going to Loop through these numbers backwards basically and these numbers backwards basically and the way to do this the way to check each the way to do this the way to check each each bit is you just take a one and you each bit is you just take a one and you shift it by some number to match what shift it by some number to match what bit you want so let's say for example uh bit you want so let's say for example uh we can actually show this with an we can actually show this with an array so let's say I have like I said array so let's say I have like I said we'll just have five bikes so let's get we'll just have five bikes so let's get rid of five of them and let's have it rid of five of them and let's have it like like this right and this will represent index this right and this will represent index 0 one two three four of the actual bikes 0 one two three four of the actual bikes are it be backwards essentially you just are it be backwards essentially you just take a one and you shift it by the take a one and you shift it by the index and then you will have a one in index and then you will have a one in some location so let's say I wanted to some location so let's say I wanted to be at this location over here I will be at this location over here I will shift it by two then I'll have a one shift it by two then I'll have a one here here right and so what I I I what I here here right and so what I I I what I really want to do is I want to check if really want to do is I want to check if this bit is on but I need to make sure this bit is on but I need to make sure all the rest uh don't matter right so all the rest uh don't matter right so the way to do this is you just and these the way to do this is you just and these two things and when you and basically two things and when you and basically these the rest of these will be zero so these the rest of these will be zero so when you and uh anything ended with a when you and uh anything ended with a zero be zero so every other bit will zero be zero so every other bit will just be zero and then this will be a one just be zero and then this will be a one if this is on and if it's a zero then if this is on and if it's a zero then will be a zero and then you can just will be a zero and then you can just check like if this thing ends up if this check like if this thing ends up if this is non zero then this bit is on so if is non zero then this bit is on so if that bit is on then you can use that that bit is on then you can use that bike and if you want to turn it off like bike and if you want to turn it off like let's say this is on you want to turn it let's say this is on you want to turn it off the way to do this is the same thing off the way to do this is the same thing and one with the shifts right so you'll and one with the shifts right so you'll have something like this now what think have something like this now what think about what bit operation you'd want to about what bit operation you'd want to use to turn just this bit off but keep use to turn just this bit off but keep the rest the same here you'd want to use the rest the same here you'd want to use an X or right so any anything X word an X or right so any anything X word with zero stays the same so this will be with zero stays the same so this will be 1111 or whatever it was and this 1111 or whatever it was and this together will be zero so that's how you together will be zero so that's how you turn it off and the check use an and so turn it off and the check use an and so that's what we can do so for our state that's what we can do so for our state now that we know how we can represent now that we know how we can represent our bikes because we don't want to have our bikes because we don't want to have like an array of available bikes we can like an array of available bikes we can just have a bit mask and we just turn it just have a bit mask and we just turn it off if we've used it so for one of our off if we've used it so for one of our state variables we will have bit state variables we will have bit mask of bikes and the other state is mask of bikes and the other state is just going to be the worker we are on just going to be the worker we are on right so we want to go through all of right so we want to go through all of the workers and we want to try to just the workers and we want to try to just assign every bike to every worker that's assign every bike to every worker that's available that's available we'll just available that's available we'll just try all of them and then whatever gives try all of them and then whatever gives us our minimum result is what we will go us our minimum result is what we will go with so our base case here is pretty with so our base case here is pretty straightforward it's just when we are straightforward it's just when we are out of workers right so when when we out of workers right so when when we went through the whole workers array went through the whole workers array then what should we return this is kind then what should we return this is kind of St for we want to return zero because of St for we want to return zero because we're not assigning anything there and we're not assigning anything there and the recursive case is just going to be the recursive case is just going to be try to try to assign an assign an available bike to current available bike to current worker Mark bike worker Mark bike unavailable and recurse and what's the unavailable and recurse and what's the value we're going to have like like value we're going to have like like what's that going to look like when we what's that going to look like when we recurse so that part what we're going to recurse so that part what we're going to add here is we are going to add add here is we are going to add Manhattan Manhattan distance of assigning bike to worker right plus the D the DP of their curs of state which is just going to be like whatever index on the workers were at plus one and the new bit mask and we can just start with our result and I'll show that in the code we can start as our result being like infinity or something and then we can just return the minimum that's kind of how you do this it's a little bit tricky but that's this is reasonably common when you have um some kind of thing that you want want to assign and then you want to turn it off so then the next person can't use it and you don't have too many of them right cuz if we had like a 100 bikes we can't use 100 bits cuz that would be too big but for something like 10 or 20 or something that works pretty well so now we can code it up kind of uh I think I explained most of the work for it so let's take a look so what we're going to do is we're going to have a cache for normal DP then we're going to keep track of the length of bikes so make a variable for that and we're going to have a DP so there's going to be two uh states that we care about W which is where we are in the workers array and then we can use like b or something as our bit mask or we can call it like mask okay so basically if W equals length of workers that means we have no more workers to assign bikes to so we can just return zero because the cost of assigning nothing is nothing now the next thing is what we want to do is the cache case right so if W mask and you can have you can have have the same state multiple times let's say you try to assign like like you're on worker zero and you assign them the first bike and then you recurse down to worker one and you you assign them the second bike uh that's going to be the same thing as assigning the bikes in the other order because from where we're at we just want to know the cost of assigning all the bikes left or sorry assigning bikes to all of the workers left so the previous step doesn't matter so you will have uh same States in here so you do want to have a cash so we just cache going W and mask okay now we can cache going W and mask okay now we can initialize our result to Infinity cuz initialize our result to Infinity cuz the strategy is if we want to minimize the strategy is if we want to minimize we just make it Infinity now basically we just make it Infinity now basically what we want to do is we want to go what we want to do is we want to go through all of our bikes and we want to through all of our bikes and we want to check is it available and if it's check is it available and if it's available we want to try to assign it available we want to try to assign it and recurse and we just want to get the and recurse and we just want to get the minimum one of all those so we can say minimum one of all those so we can say for I in range for I in range B and remember this is going to be B and remember this is going to be backwards so the mask if if the mask is backwards so the mask if if the mask is like this let's let's say this is index like this let's let's say this is index zero this is index one and so on right zero this is index one and so on right because we're going to shift an i that's because we're going to shift an i that's going to start over here so it'll be one going to start over here so it'll be one and we're going to shift it to the left and we're going to shift it to the left some some bits so this part is just going to be if bits so this part is just going to be if um the actual bit mask so mask um the actual bit mask so mask and I or one shifted uh left I bits is and I or one shifted uh left I bits is non zero that means that bit is on that non zero that means that bit is on that means I bit is on so we want to use the means I bit is on so we want to use the I index in this worker or in the spikes I index in this worker or in the spikes array so we will try to minimize our array so we will try to minimize our results so we'll say res equals minimum results so we'll say res equals minimum the old result and then we want to get the old result and then we want to get the Manhattan distances right so it's the Manhattan distances right so it's going to be the absolute value of workers yeah and then what's the index in the workers well the work the index in the workers is our current W index and then we just want the x value here minus bikes and then which bike is it so it's going to be bikes High y i z and then you want to add the same thing for the Y values right so this is the x value difference now we just need the um y value difference so we will add those together so same thing for the Y values okay and so it's these two things right this is the manhatt distance plus the DP of the recursive case so the DP of the recursive case is you go to the next worker and then you want to take the bit this bit over here and you want to turn that off now and remember that's just uh taking this and doing this right so it's just mask xor one uh shifted left High bits because that will turn it off okay and then finally once we get our minimum result and there is always going to be a result because there's guaranteed more bikes than workers or the same so you'll never like end up with infinity here or anything but you will try to minimize it so then you just say cach um this is going to be W mask equals result and return and return the result and finally so what do we want to initialize this to so obviously the worker is zero but what do we want to initialize our bit mask so remember we want it to be all ones so if you have um let's say you have five like uh your bike is length five you want to have something like this right so what ises this equal to so this this is always the case whenever you have five ones that's always equal to two to the number of ones you have so in this case 2 5 minus one because 2 5 is basically one and 5 zeros five zeros so this minus one will be zero and all of the rest of these five zeros will turn into ones so that'll be this so what we want this to be is two and this is pretty common as well to get this like pattern of all ones it's just two to the length of the bikes so this is going to be uh I think we have B here and yeah it's going to be this minus one so that'll give you that'll give you the same number of ones as the length of the bikes and that should be it so let's take a that that see yeah and then as far as the run see yeah and then as far as the run times once again um it's kind of a times once again um it's kind of a reasonably fast run time so if you just reasonably fast run time so if you just run it a bunch it like speeds up or run it a bunch it like speeds up or slows down or whatever so I think I the slows down or whatever so I think I the most I got it I can look it's like let's most I got it I can look it's like let's take a look yeah so I think I got it to take a look yeah so I think I got it to like adms with the same solution so it's like adms with the same solution so it's kind of like all over the place again kind of like all over the place again but pretty good it's also very hard to but pretty good it's also very hard to analyze runtime of um DP versus uh analyze runtime of um DP versus uh versus backtracking because backtracking versus backtracking because backtracking is usually inefficient and kind of hard is usually inefficient and kind of hard to analyze because it's like it's to analyze because it's like it's usually like two to the end times usually like two to the end times something times something kind of hard something times something kind of hard to say or like some factorial thing it's to say or like some factorial thing it's kind of hard to say like what's better kind of hard to say like what's better like some factorial function or s like 2 like some factorial function or s like 2 to the n 10 n squ or whatever you all um to the n 10 n squ or whatever you all um and obviously the El code solution like and obviously the El code solution like run times aren't the don't really show run times aren't the don't really show you um too often how fast your thing is you um too often how fast your thing is unless it's I think I talked this about unless it's I think I talked this about this before so like let's say you submit this before so like let's say you submit this and your solution takes like 4,000 this and your solution takes like 4,000 Ms or something and then there's Ms or something and then there's solution that takes like 200 then solution that takes like 200 then obviously there's something better but obviously there's something better but if they're roughly the same then it if they're roughly the same then it doesn't really matter okay so let's look doesn't really matter okay so let's look at the uh runtime for this so essentially W is going to be the length of workers so we'll call that like o w and then the mask is basically two to the bikes so that part is that and then we bikes so that part is that and then we are also looping through every single are also looping through every single bike in bike so this will be like w * B bike in bike so this will be like w * B probably so I think it's something like probably so I think it's something like this W * B * time two number of bikes this W * B * time two number of bikes but because these are only 10 it ends up but because these are only 10 it ends up being like 10 the 5th or something total being like 10 the 5th or something total which is which is fine um and for the fine um and for the space so this is just like normally the space so this is just like normally the cache which is just W Times the uh two cache which is just W Times the uh two to the two to the number of to the two to the number of bikes and yeah so I do think this is a bikes and yeah so I do think this is a good one to learn I think uh this bit good one to learn I think uh this bit mask stuff comes mask stuff comes up reasonably often to be honest in the up reasonably often to be honest in the harder um DP problems so I definitely harder um DP problems so I definitely think you should learn how to do it and think you should learn how to do it and use it and if this is helpful please use it and if this is helpful please like the video and subscribe to the like the video and subscribe to the channel and I'll see you in the next one channel and I'll see you in the next one thanks for watching | 2024-03-25 16:40:56 | 1,066 | LeetCode 1066 - Campus Bikes II - Python |
|
rWO3VWW0B2k | hi everyone welcome to my YouTube channel and in this video we will look channel and in this video we will look at problem 1680 from the code so the at problem 1680 from the code so the subject the title of this problem is subject the title of this problem is concatenational consecutive binary concatenational consecutive binary numbers and the person you see on the numbers and the person you see on the left hand side is live needs I don't left hand side is live needs I don't know his first name he was the German know his first name he was the German mathematicians mathematicians and maybe at the time I think was here I and maybe at the time I think was here I think was Germany or maybe it is called think was Germany or maybe it is called Prussia but anyway he not only invented Prussia but anyway he not only invented binary system but also he was the binary system but also he was the inventor of well you can say calculus inventor of well you can say calculus along with Newton so well that is for along with Newton so well that is for that for historical fact and let's look that for historical fact and let's look at the problem statement so here is the at the problem statement so here is the problem statement and pause this video problem statement and pause this video for a second try to come up with your for a second try to come up with your own solution so I will be using n equals own solution so I will be using n equals 3 as an example to illustrate my you 3 as an example to illustrate my you know my code for this problem so n know my code for this problem so n equals three that means we have to equals three that means we have to consider 123 and then we have to apply consider 123 and then we have to apply you know we have to make those numbers you know we have to make those numbers those integers into binary those integers into binary representation and then and then in representation and then and then in Python we will be using binary of I Python we will be using binary of I so we will be applying that so this one so we will be applying that so this one will become binary of one this one will will become binary of one this one will become binary of two this one will become binary of two this one will become in a binary of three now you have become in a binary of three now you have to remember that when you apply binary to remember that when you apply binary say one say one um you you not only get this one um you you not only get this one um you know this is a string but you um you know this is a string but you also get like some two characters like I also get like some two characters like I think it was zero B so you we do not think it was zero B so you we do not want them so that's why we have to apply want them so that's why we have to apply this you know slicing here so that so this you know slicing here so that so that we only care about the numbers like that we only care about the numbers like except the first two letters so that's except the first two letters so that's what's going on here and then we will be what's going on here and then we will be concatenating here so s plus equals uh concatenating here so s plus equals uh so yeah so s is an empty string and then so yeah so s is an empty string and then we will be you know building our con we will be you know building our con yeah our string string for this so for yeah our string string for this so for if you look at this one we have one and if you look at this one we have one and one zero we will be concatenating those one zero we will be concatenating those two guys and then we will get one one two guys and then we will get one one zero and then we will be concatenating zero and then we will be concatenating this guy and this guy so we will get one this guy and this guy so we will get one one zero one one now after that we have one zero one one now after that we have to you know return the numbers so we to you know return the numbers so we have to return the what is it the have to return the what is it the decimal value of the binary string decimal value of the binary string and that we have to also take the and that we have to also take the modular so here we have a modular modulo modular so here we have a modular modulo equals 10 to the power of 9 plus 7. so equals 10 to the power of 9 plus 7. so that part is like we cannot we can that part is like we cannot we can always you know take the modular in the always you know take the modular in the end how do we get the decimal value of end how do we get the decimal value of the binary string the binary string uh if you look at int function in the uh if you look at int function in the python we have like you know where we python we have like you know where we have say if we are given a integer trip have say if we are given a integer trip like some numbers say 3.5 and then we like some numbers say 3.5 and then we put int of 3.5 that will give us three put int of 3.5 that will give us three so that function it also has this so that function it also has this property so property so s can be in this case will be some s can be in this case will be some number right and then we have number right and then we have this um the representation in this case this um the representation in this case would be 2. would be 2. so what this function does is this one so what this function does is this one will return the decimal value of the will return the decimal value of the binary string binary string so if you say if you have int 11011 and so if you say if you have int 11011 and then we have two here that will give us then we have two here that will give us um you know 27 right and then we have to um you know 27 right and then we have to take the module but in this case since take the module but in this case since this number is you know smaller than this number is you know smaller than this 10 to the power of 9 plus 7 that this 10 to the power of 9 plus 7 that doesn't really affect this one but when doesn't really affect this one but when you have like very big number you have like very big number like n equals 13 15 then this one will like n equals 13 15 then this one will become handy become handy um so that's for this problem and let's um so that's for this problem and let's look at the code for this so this is the look at the code for this so this is the exactly same code that you just saw and exactly same code that you just saw and let's try to run this together and see let's try to run this together and see what we get so that's for this problem and hope my video helps you guys understanding this problem um I think this problem you can also use you know like beat manipulation because all this yeah this one if you look at this approach you can also come up with a bit manipulation to solve this problem um I think that has about the same time complexity but um I think if you want to try practice speed manipulation then you can try that on your own or I can you know have a separate video on this I still don't forget about you know how those string matching algorithms so I'm making a video on on those topics and also I don't forget about numerical linear algebra so just um pair with me you guys and I will try to create like really uh great videos for this um because well anyway that's for that um just hope my video helps you guys and well have a wonderful you know weekend | 2024-03-20 11:16:31 | 1,680 | Leetcode 1680 solution |
|
Qdmw-F8ojds | hi everyone it's albert today let's solve the it's albert today let's solve the contest median question contest median question restore the array from adjacent pairs restore the array from adjacent pairs 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 questions classic clinical questions with clear explanation animation and with clear explanation animation and visualization visualization now let's look at a question for this now let's look at a question for this question question there is an integer array numbers that there is an integer array numbers that consist of consist of unique elements but we have forgotten unique elements but we have forgotten it for some reason however we do it for some reason however we do remember remember every pair of adjacent elements in the every pair of adjacent elements in the original array original array and we are given a 2d integer array and we are given a 2d integer array adjacent pairs adjacent pairs of size -1 and that of size -1 and that each item in adjacent pairs is an array each item in adjacent pairs is an array of two elements of two elements uv that it indicates uv that it indicates the elements uv they are adjacent the elements uv they are adjacent in the original arrays numbers and it's in the original arrays numbers and it's guaranteed that guaranteed that every adjacent pair of elements every adjacent pair of elements num psi and nums i plus 1 num psi and nums i plus 1 they will exist in adjacent pairs array they will exist in adjacent pairs array but the pair can appear in different but the pair can appear in different order order so given a json pairs array we have to so given a json pairs array we have to reconstruct reconstruct and return the original array numbers and return the original array numbers and if there are multiple solutions we and if there are multiple solutions we can return can return any of them so for example one any of them so for example one the adjacent pairs array is 2 1 the adjacent pairs array is 2 1 3 4 3 2 and the original array is 3 4 3 2 and the original array is array 1 2 3 4. array 1 2 3 4. an example 2 the adjacent pairs is an example 2 the adjacent pairs is 4 negative 2 1 4 4 negative 2 1 4 negative 3 1 and the original nouns negative 3 1 and the original nouns array is array is negative two four one negative three and for example three the adjacent pierce array only has two elements so that would be exactly the original numbers array and data constraint the length of the adjacent pairs array can go up to 10 to the power of 5. any intuition to solve this question the first step is to build a graph data structure which is a hash map from adjacent pairs and in this hash map the key will be every node or every item in the nums array and then a value will be the left or right neighbor of that node in the nums array and next we can use dfs that first search to reconstruct the original numbers array from the graph so the main data structure to use for this question is graph which is also a hash map now let's look at the code okay and first step is to create the graph hash map and here we can use python's collections default dictionary to create a graph g and then we will loop through adjacent pairs array and then append the node and neighbors and next we have to find a starting and next we have to find a starting point and the starting point can be point and the starting point can be either either the head or the tail in the nose array the head or the tail in the nose array which is the first which is the first or last element and once we found the or last element and once we found the head or the tail head or the tail we will make it the starting point we will make it the starting point and next we will need a visited set to and next we will need a visited set to check at check at which nodes have been visited and then which nodes have been visited and then the rest array the rest array to append the nodes and then return at to append the nodes and then return at the end the end and finally is to dfs into and finally is to dfs into the graph and then append the nodes the graph and then append the nodes into rest and return at the end into rest and return at the end now let's see the code in action okay and here we'll be looking at example two the input adjacent pair is four negative two one four negative three and one so with a given adjacent piece array we can create a graph looking like this and you can notice that key negative 3 and negative 2 they only have one neighbor which means that they are either the head so we can pick either one of them to be so we can pick either one of them to be the starting point the starting point and here we'll pick a negative 2 as and here we'll pick a negative 2 as start and next is to start dfs and the first dfs call is dfs negative 2 and negative 2 will be added into visited since it has been visited and then append negative 2 into rest and the next dfs call is the neighbor of and at dfs 4 following the same process and at dfs 4 following the same process we will add 4 into visited and rest we will add 4 into visited and rest array array and the left and right neighbor of 4 is and the left and right neighbor of 4 is negative 2 negative 2 and 1 and negative 2 has been visited and 1 and negative 2 has been visited so you will be skipped so the next dfs so you will be skipped so the next dfs call call is dfs1 and at dfs one again add one into visited and rest and the neighbors of one is four and negative three four has been visited so the next call is dfs and at dfs 3 the same at and at dfs 3 the same at negative 3 into visited and rest negative 3 into visited and rest and up to here we have visited all the and up to here we have visited all the nodes nodes in the graph so we would return in the graph so we would return a rest negative 2 4 1 a rest negative 2 4 1 negative 3 which is the output for this negative 3 which is the output for this example example and this will conclude the algorithm finally let's review so the main idea to solve this question is to build a graph hash map from a json pairs array and the key of this hash map is a node in the array and then a value is the neighbors the left and right neighbors of that node and then we can use dfs to reconstruct the original nouns array from the graph so the main data structure to use for this question is a graph data structure which is also a hash map and time and space complexity of this approach are both linear 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 | 2024-03-20 18:07:12 | 1,743 | LeetCode 1743. Restore the Array From Adjacent Pairs | Visualization | Python |
|
iQuw7mID_30 | welcome back to algojs today's question is leak code 212 word search two is leak code 212 word search two so given an n by m board of characters so given an n by m board of characters in a list of string words return all in a list of string words return all words on the board so each word must be words on the board so each word must be constructed from letters of sequentially constructed from letters of sequentially adjacent cells where adjacent cells are adjacent cells where adjacent cells are horizontally and vertically neighboring horizontally and vertically neighboring the same letter cell may not be used the same letter cell may not be used more than once in a word so let's have a more than once in a word so let's have a look what our first example looks like look what our first example looks like so we have an m by m board with a number so we have an m by m board with a number of different characters within it and we of different characters within it and we need to find need to find if any of these words right here exist if any of these words right here exist within the board we have f which starts within the board we have f which starts at the first position and ends right at the first position and ends right here and we have eat which is backwards here and we have eat which is backwards over here so there are two words within over here so there are two words within the word re that can be found within the the word re that can be found within the board so we return those as the output board so we return those as the output in terms of implementing it i would say in terms of implementing it i would say it's very similar to number of islands it's very similar to number of islands but there is an extra level of but there is an extra level of complexity to this because we have complexity to this because we have characters as opposed to zeros and ones characters as opposed to zeros and ones so so in order to make this as optimized as in order to make this as optimized as possible possible what we could use is a try data what we could use is a try data structure structure to store all of our words in the to store all of our words in the dictionary so firstly what we need to do dictionary so firstly what we need to do is is create our tri data structure with these create our tri data structure with these words the tri-data structure looks like words the tri-data structure looks like this so there is nothing within the this so there is nothing within the initial position and then we create the try so we've traversed down earth and we've put that within the try and at the bottom position what we usually have we're going to try is a flag of some sort to say that this is a word but instead what we're going to have is word equal to this entire word so it's essentially going to be equal to oath so we've checked over now we can go to p so p e a so now we can just add eat and rain to the try and this will make more sense in a minute when we start dfs in through this 2d array as to why we've done this so again word at this point at a is going to equal p word here is going to equal eighty and word in this section is going to equal brain okay so we've created our tri data structure now we can start carrying out the dfs on this tree so let's start the first position we have an o so firstly we need to check if o has the word attached to it in this case it doesn't so we can start looping through so we can check to see whether it's in the first position of our try so is it equal to p e r o well we have the o right here so at this point we can dfs to the next position right so up right down and left so there are four possible positions but we have to check if it's inbound so this and this are invalid because it's not inbound right so across this way is j is less than zero up this way i is less than zero we also have to check whether it's too far down this way so i is greater than board dot length minus one we also have to check whether it's too far over this way where it's board j is greater than board at i dot length minus one right so we need to check whether it is valid to begin with so that's the first step to check whether the positions are valid also we need to check so say we went to e e is not within the next position of this tri so this descendant of o is not equal to this value so we cannot go down this way so the only position we can go is to this a because it's equal to the a within the tri so we can dfs at this position so we can go up right down and left so we can't go up because that's out of bounds we can't go right because the next value within the tri is t and this is equal to a so we can't go that way can we go back well we've already visited o so we can't go this way so we need to make an adjustment for this and the way we do that is we could use either a visited flag so we could have visited and pass in all the positions that we have visited but this increases your space complexity but this increases your space complexity so what we're going to do is we're so what we're going to do is we're actually going to just set this value actually going to just set this value before we finish this section we're before we finish this section we're going to set this to an arbitrary piece going to set this to an arbitrary piece of data so we're going to set it to a of data so we're going to set it to a hash so it's no longer equal to an o so hash so it's no longer equal to an o so we never go back to that position then we never go back to that position then we can go to t we can dfs at that we can go to t we can dfs at that position so we can't go back because we position so we can't go back because we set this a to a hash we go to t we try set this a to a hash we go to t we try go to e we can't go to e because the go to e we can't go to e because the next position in the tri is a h next position in the tri is a h we go to a we can't go to a because it's we go to a we can't go to a because it's a h so the only position we can go to is a h so the only position we can go to is this value right here now this value has this value right here now this value has word attached to it word attached to it okay so it has a dot word attached to it okay so it has a dot word attached to it and if that is the case then we push and if that is the case then we push this value this value so we're going to add this value to our so we're going to add this value to our result so we're going to have a result result so we're going to have a result array array and we're just going to push in both now and we're just going to push in both now we want to stop this from being we want to stop this from being duplicated again so what we can do at duplicated again so what we can do at this point in time this point in time is we can set this is we can set this to null now because we have found it so to null now because we have found it so if there's two positions where there is if there's two positions where there is oath within the board we're not going to oath within the board we're not going to get that now because we have set this get that now because we have set this word to not great so at this point word to not great so at this point what we need to do now is we need to what we need to do now is we need to backtrack because we found this value we backtrack because we found this value we need to go back up because all these need to go back up because all these values are currently a hash right values are currently a hash right we need to reset this board right so we we need to reset this board right so we need to reset this to a h we need to need to reset this to a h we need to reset this to a t this to an a and this reset this to a t this to an a and this to an o to an o so we can go ahead and do that so now so we can go ahead and do that so now that we've done that we can traverse that we've done that we can traverse through the board so we can check at through the board so we can check at position a is that within the first position a is that within the first position position of the try no it's not so we can move to of the try no it's not so we can move to the next position again a is the same so the next position again a is the same so we move to n n is not found within this we move to n n is not found within this first level of the try so again we move first level of the try so again we move along e is found within it but if you along e is found within it but if you see if we traverse or dfs through e see if we traverse or dfs through e the next position is a and we don't have the next position is a and we don't have this so we can move on to t t is not this so we can move on to t t is not within the first position within the first position a is not within the first position a is not within the first position we go to e we go to e e is within the first position so we e is within the first position so we have this e so we check is word attached have this e so we check is word attached to it no it's not white is not attached to it no it's not white is not attached to it word is attached to the t down to it word is attached to the t down here so we can carry out dfs on this we here so we can carry out dfs on this we can't go this way because it's out of can't go this way because it's out of bound we can't go to n up here we can't bound we can't go to n up here we can't go to r down here we can only go to a go to r down here we can only go to a because the second position within this because the second position within this try now is a and before we move over to try now is a and before we move over to a remember we need to convert this to a a remember we need to convert this to a hash so that we don't go back to him we hash so that we don't go back to him we go to a with dfs go to a with dfs at a we can't go this way because we've at a we can't go this way because we've converted e to a hash we can't go to a converted e to a hash we can't go to a up here we can't go to k down here we up here we can't go to k down here we can only go to t because the next value can only go to t because the next value in that try is a t so we check at t does in that try is a t so we check at t does this have a word property yes it does this have a word property yes it does so we can push in so we can push in that value here into our result array that value here into our result array and then again we need to clean this up and then again we need to clean this up so we need to convert the hash back to so we need to convert the hash back to an a a hash back to an e so that we can an a a hash back to an e so that we can carry on traversing through the board so carry on traversing through the board so i h k and r if we look at the top level i h k and r if we look at the top level the only one that we can find is r and the only one that we can find is r and all its next positions if we dfs in all all its next positions if we dfs in all directions directions do not equal a so we can move on i f l do not equal a so we can move on i f l and v unlocked within this first level and v unlocked within this first level either either so we can end this and just return so we can end this and just return our output the result here so that's the our output the result here so that's the basis for solving this problem basis for solving this problem tonight complexity in this case so say tonight complexity in this case so say we had a board that looked something we had a board that looked something like this and we were at this position like this and we were at this position and the words we have to look for are a and the words we have to look for are a a a and treble a how many steps can we take and treble a how many steps can we take from this initial position well firstly from this initial position well firstly we need to loop through every we need to loop through every value within this board value within this board so time complexity is going to be om so time complexity is going to be om where m is the number of characters where m is the number of characters within the board and if we're at within the board and if we're at position a within the middle here position a within the middle here what is the maximum number of positions what is the maximum number of positions that we can go to those are inbound and that we can go to those are inbound and valid valid it's four so it's going to be four times it's four so it's going to be four times what is the maximum number of positions what is the maximum number of positions say we had extra a's added on down here say we had extra a's added on down here what is the maximum number of positions what is the maximum number of positions that this a can go to well that this a can go to well it's going to be three in this case that it's going to be three in this case that are inbound and valid so it's going to are inbound and valid so it's going to be three and it's going to be to the be three and it's going to be to the power of l minus one power of l minus one l in this case is the length of the l in this case is the length of the words within the try so that is the time words within the try so that is the time complexity so space complexity is going complexity so space complexity is going to be o n to be o n where n is the amount of characters where n is the amount of characters within the try so firstly we need to within the try so firstly we need to create a function called build try create a function called build try which is pretty self-explanatory because which is pretty self-explanatory because we need to we need to obviously create our try so to start off obviously create our try so to start off the try we're going to have the try we're going to have root which is going to be equal to an root which is going to be equal to an empty object we're going to loop through empty object we're going to loop through the words we're going to get the current node we're going to pass it as a reference to root then we're going to loop through the characters of the word okay so if current node at the character it's equal to null then we can just say current node at character which is equal to an empty object so we're just creating an empty object that's that current node at position chart otherwise and then once we've reached the end and and then once we've reached the end and we built this tryout we built this tryout we need to add the word property and the we need to add the word property and the word property is going to be equal to word property is going to be equal to the word so the word that we've looked the word so the word that we've looked through within these words just so that through within these words just so that we can return this within our results we can return this within our results and finally we need to return root so and finally we need to return root so within the main body of the actual within the main body of the actual function we need to initialize result function we need to initialize result which is going to be an empty array which is going to be an empty array we need to create or we need to build we need to create or we need to build out the try so let's call it root and we out the try so let's call it root and we can say build try and we can pass in can say build try and we can pass in words then we need to loop through the board moving through the rows looping through the columns and then within the dfs we're going to pass in the root so the try that we've just created i j gonna pass in board and we're also going to pass in result and pass in board now we need to create the dfs function so dfs we can call the root node i and j can stay the same so the first thing we do within our dfs so the first thing we do within our dfs function is check whether the position function is check whether the position or whether the node has the word or whether the node has the word property attached to it property attached to it if it is we know we found if it is we know we found a word within the board a word within the board so we can push node.word the property which we created down here which is equal to the word that we loop through we can push that into the result array and then we need to set the word property to null and the reason i stated in the solution was because we cannot have duplicates so say we found h here that's gonna have the word property attached to it if there was another oaf within this board the h on that would also have the word property attached to it because it's the exact same word within the try so we need to set that to null so that we don't have duplications within our final result then we need to check whether the value is inbound so if i is less than zero i is or j is less than zero that's out of bounds if i is dot length minus one or j dot length minus one or j is greater than board at zero dot length minus one we can return so these are all out of bound if node board i j is null we can return what this is saying is if the position in the board is not found within the try just return because that isn't a potential path now we need to stop an infinite loop from occurring so we create a reference to board ij and we'll explain what this is for in a second we set board at i j to equal the hash and this is to stop an infinite loop so we don't go back to the previous value which we've already looked at we need to carry out the dfs in all four directions now so we know that c so know that board i j i j result and board now we can copy this three more times and we just need to change the direction so i plus one i minus one j plus one j minus one okay so once we've dfs for all of the positions and we've checked the board and they've all returned a value we need to reset border ij so that's where c comes into play so board at i j is currently a hash and we need to convert it back to the value to carry on traversing through each value within this board so we just set that back to c and then finally we need to return result that's looking good let's give this a run and there you go | 2024-03-22 10:31:36 | 212 | Word Search II - LeetCode 212 - JavaScript |
|
BDi5U4TF6e0 | So today we will see Longest substring without repeating characters is a good problem and they have two output D. If there is longest substring without repeating characters then it has ABC. Longest ABC is right. If ABCA is not there because there is repeating character then the answer is it has all one. So there is one, there is blue, so we will solve this problem by doing dictionary, music], we will do music], we will do zero, when is it added, we got the string of ABC reset. also possible that E may become something else in the future, okay, so once we repeat A, we will okay, so once we repeat A, we will increase the alcohol further and bring R back increase the alcohol further and bring R back to L, you will also check, okay [ Remove [Music mean, then what will be the length? Now, whatever is our then what will be the length? Now, whatever is our dictionary, we have not taken a condition in it which we have not taken a condition in it which would be that the Deputy Collector is never there, otherwise the would be that the Deputy Collector is never there, otherwise the character will not be lost if it character will not be lost if it is a reporting character. ok, submit this correct SIM, | 2024-03-18 10:31:52 | 3 | 3. Longest Substring without repeating characters | Python | Leetcode Medium |
|
R7IjtzZpcl4 | we are going to solve find minimum and rotated sorted array today rotated sorted array today this is the medium kind of problem this is the medium kind of problem let's look for our problem statement let's look for our problem statement we are given an array of length n which we are given an array of length n which was initially sorted in ascending order was initially sorted in ascending order then it's got rotated now we have this then it's got rotated now we have this rotated array with us so what the rotated array with us so what the rotation means if initially we have an rotation means if initially we have an array zero one two three four five six array zero one two three four five six seven if we do it for the first time our seven if we do it for the first time our array will look like our 7 will come array will look like our 7 will come up front then we have 0 1 2 up front then we have 0 1 2 4 4 5 6. this is result after one rotation 5 6. this is result after one rotation if again we rotate it it will look like if again we rotate it it will look like so this is our third rotation so after so this is our third rotation so after fourth rotation it will look like fourth rotation it will look like something like this now we need to note something like this now we need to note that all the elements are unique in this that all the elements are unique in this area area and we need to return the minimum and we need to return the minimum element of this array and we need to element of this array and we need to write our algorithm which runs in four write our algorithm which runs in four login time telling us that we need to login time telling us that we need to use the binary search because when we use the binary search because when we use find research then only we can get use find research then only we can get our time complexity to log in if we can our time complexity to log in if we can use a linear time it's very simple we use a linear time it's very simple we are going to traverse whole array and are going to traverse whole array and see which is the minimum and will return see which is the minimum and will return that element as our result but we need that element as our result but we need to implement it in login time if we have to implement it in login time if we have a sorted array and we try to plot our a sorted array and we try to plot our sorted error in a number range graph of sorted error in a number range graph of that sorted array will look like that sorted array will look like something like this it will give us a something like this it will give us a straight line because all the elements straight line because all the elements are unique are unique but here our array is rotated by m time but here our array is rotated by m time so this means now our new array so this means now our new array after rotation after rotation our number from 0 to let's say rotated our number from 0 to let's say rotated by m times so this is 0 to m by m times so this is 0 to m this is m plus 1 till this is m plus 1 till n n now we know how our binary search work now we know how our binary search work basically in binary search what we do we basically in binary search what we do we just find the we have a defined range just find the we have a defined range this is our sorted array let's say this is our sorted array let's say so this is our left and right so this is our left and right and we need to find our target okay and we need to find our target okay target is x target is x so firstly we try to find the mid value so firstly we try to find the mid value after finding the mid we try to compare after finding the mid we try to compare with the target with the target if our mid value is smaller than target if our mid value is smaller than target it means that it means that our target will lie in this range our target will lie in this range from mid to from mid to mid plus 1 to right our target will be mid plus 1 to right our target will be in this range because this is a sorted in this range because this is a sorted array array so all the elements from left to mid so all the elements from left to mid will be smaller than this mid value will be smaller than this mid value and our target is greater than mid so and our target is greater than mid so there is no way that our target is going there is no way that our target is going to lie in this range to lie in this range so we don't need to search in this space so we don't need to search in this space we need to decrease our search space we need to decrease our search space so what we can do here we can just make so what we can do here we can just make our left our left to mid plus 1 because we know our target to mid plus 1 because we know our target is greater than mid is greater than mid now the second case could be our target now the second case could be our target is smaller than mid is smaller than mid this means that our target is not going this means that our target is not going to be in the range of mid to r because to be in the range of mid to r because our target is smaller than mid so we our target is smaller than mid so we need to look for need to look for from left to from left to mid minus 1 so we need to update our mid minus 1 so we need to update our right pointer to mid minus 1 and keep right pointer to mid minus 1 and keep repeating over this step until we find repeating over this step until we find our target so this is the basic of our target so this is the basic of binary search now we try to modify this binary search now we try to modify this condition so that we can find the condition so that we can find the minimum element in this rotated sorted minimum element in this rotated sorted array array so this is our left this is our right so this is our left this is our right that is this is our zero index this is that is this is our zero index this is our our n minus one so firstly we will try to n minus one so firstly we will try to find the mid value because we are going find the mid value because we are going to apply binary search here to apply binary search here so let's suppose our mid life somewhere so let's suppose our mid life somewhere here so this is our mid here so this is our mid then we are going to compare this mid then we are going to compare this mid with our right with our right because all the numbers are unique because all the numbers are unique if our mid value greater than right this if our mid value greater than right this means that our minimum value will lie in means that our minimum value will lie in the range of mid plus 1 till out the range of mid plus 1 till out this means that our number in this right this means that our number in this right part are smaller than the mid value part are smaller than the mid value there is no possibility that it could be there is no possibility that it could be in the range of left to mid in the range of left to mid because this left to mid will contain because this left to mid will contain the numbers greater than our minimum now the numbers greater than our minimum now the second condition could be our mid is the second condition could be our mid is lying this is our left this is right lying this is our left this is right our mid is lying in this right part our mid is lying in this right part itself so when we compare our mid and itself so when we compare our mid and right right our mid value our mid value is smaller than our right value is smaller than our right value this means that the smallest value is this means that the smallest value is not going to be in this range not going to be in this range because all the numbers in this range is because all the numbers in this range is going to be greater than the mid value going to be greater than the mid value so we need to look for the value in the so we need to look for the value in the range range left to mid so here we are going to set left to mid so here we are going to set our right pointer our right pointer to mid to mid so we have just two rules if firstly we so we have just two rules if firstly we are going to find the mid value after are going to find the mid value after finding the mid value we are going to finding the mid value we are going to compare with the right value we are compare with the right value we are going to compare the right hand side going to compare the right hand side value if our right hand side value is a value if our right hand side value is a smaller smaller this means that our smallest value is this means that our smallest value is not going to lie in the range left to not going to lie in the range left to mid mid it is going to fall in the range mid it is going to fall in the range mid plus 1 to right so we are going to shift plus 1 to right so we are going to shift our search space our search space from mid plus one to right and the from mid plus one to right and the second case could be second case could be our right value is greater than our mid our right value is greater than our mid value this means that our smallest value value this means that our smallest value is is is not going to lie in the range mid is not going to lie in the range mid plus one to right so we need to shift plus one to right so we need to shift our range so we are going to set our our range so we are going to set our right pointer to write is equal to mid right pointer to write is equal to mid okay so it's very simple let's code this okay so it's very simple let's code this problem problem we are going to apply binary search so we are going to apply binary search so firstly we need to declare our range for firstly we need to declare our range for the binary search so let's get the size the binary search so let's get the size of the array and let's declare the range of the array and let's declare the range of our binary search now we are going to of our binary search now we are going to start our binary search so these two start our binary search so these two lines are the exactly same as we do in lines are the exactly same as we do in our binary search in normal binary our binary search in normal binary search we check with the target value search we check with the target value but here our target value is the minimum but here our target value is the minimum value value so if our middle value is greater than so if our middle value is greater than our right most value it means that our our right most value it means that our minimum element is going to lie in mid minimum element is going to lie in mid plus one till r it could be anywhere in plus one till r it could be anywhere in this range so we need to shift our left this range so we need to shift our left pointer to mid plus one pointer to mid plus one otherwise it means that our medium value otherwise it means that our medium value is not going to lie in the range of mid is not going to lie in the range of mid plus 1 till r because mid plus 1 till r plus 1 till r because mid plus 1 till r is greater than our medium value is greater than our medium value so our minimum value will be in the so our minimum value will be in the range of left to mid so we need to shift range of left to mid so we need to shift our right pointer so that we can cut our our right pointer so that we can cut our search space now at the last we are search space now at the last we are going to return going to return nums left nums left so that's our code let's run our code okay so it's good to go let's submit our okay so it's good to go let's submit our code okay so it's efficient space complexity is also good so yeah that's it for this problem we took login time to solve this problem because it's a binary search and we are not taking any extra space here so that's all for today | 2024-03-21 13:17:55 | 153 | Find Minimum in Rotated Sorted Array | LeetCode:153 | Solution & Explanation |
|
5liJnc8iNeY | hey how'd our today I'm looking at the questions 648 to replace words so the questions 648 to replace words so the question is as follows in English we question is as follows in English we have a concept I call the root which can have a concept I call the root which can be followed by some other words so the be followed by some other words so the root is a word root is a word the root word can be followed by some the root word can be followed by some other words to form another longer word other words to form another longer word that's called this word successor so the that's called this word successor so the successor is the longer word that formed successor is the longer word that formed by concatenating two words by concatenating two words the first word is called root so for the first word is called root so for example the root and followed by other example the root and followed by other can form another word I just so happened can form another word I just so happened that another word is another so I think that another word is another so I think the end here should be prefix the other the end here should be prefix the other here is the actual root for this word so here is the actual root for this word so so I'm just gonna do replace words so I'm just gonna do replace words myself for about this question myself for about this question description I will replace all those description I will replace all those roots with prefix so keep reading now roots with prefix so keep reading now given a dictionary consist consisting of given a dictionary consist consisting of many roots many prefix and a sentence we many roots many prefix and a sentence we need to replace all the successors in need to replace all the successors in the sentence with the prefix forming it the sentence with the prefix forming it if a successor has many prefix if a successor has many prefix conformant we will replace the word with conformant we will replace the word with the shortest prefix we have so that's the shortest prefix we have so that's best what the question is asking looking best what the question is asking looking an example we have the sentence the an example we have the sentence the cattle was rattled by the battery and we cattle was rattled by the battery and we have three different prefix cat bad and have three different prefix cat bad and rat so we'll replace Caro with cat rat so we'll replace Caro with cat replace rattled with rat and replaced replace rattled with rat and replaced battery weighs bad there is no word with battery weighs bad there is no word with multiple prefix so there is no multiple prefix so there is no conflicting about there is no need to conflicting about there is no need to see which prefixes shortest or something see which prefixes shortest or something like that you miss example so basically like that you miss example so basically for this question we're just going to for this question we're just going to chop this sentence into inch limited chop this sentence into inch limited individual words and map this wording to individual words and map this wording to some kind of replacement function some kind of replacement function in that function we're just gonna check in that function we're just gonna check the the word we are search for I will the the word we are search for I will try to do replacement with the other try to do replacement with the other prefix we have if we do find exactly one prefix we have if we do find exactly one prefix that the word starts with then we prefix that the word starts with then we return that prefix if we find multiple return that prefix if we find multiple prefix maybe we have CIT prefix maybe we have CIT C cat or a single C we return this C cat or a single C we return this shortest one so for this case whoo if we shortest one so for this case whoo if we do have another C as the prefix we do have another C as the prefix we return C so if we don't find any prefix return C so if we don't find any prefix we just left and leave the word we just left and leave the word unchanged just return the original word unchanged just return the original word so we map that they replace function to so we map that they replace function to all the words here and click to the all the words here and click to the result and pieced them together that result and pieced them together that would be the approach to solve this would be the approach to solve this problem so the only thing here is that problem so the only thing here is that how we're actually going to code this how we're actually going to code this replacement code to have that to be more replacement code to have that to be more efficient of course we can do the blue efficient of course we can do the blue force to just try try all the pairs and force to just try try all the pairs and all the prefix and just try to see if all the prefix and just try to see if the word starts with those but the a the word starts with those but the a better approaches to create a try for better approaches to create a try for all the prefix so that all we need to do all the prefix so that all we need to do is to just traverse inside to try using is to just traverse inside to try using the characters in the word so if we do the characters in the word so if we do find a try node which with the with a find a try node which with the with a terminal termination flag and a port terminal termination flag and a port flag that means we have a prefix that flag that means we have a prefix that matches the word we are looking for so matches the word we are looking for so in that case we will just return the the in that case we will just return the the pass in the try that leads us to the pass in the try that leads us to the termination of lab so if we do have a termination of lab so if we do have a trial here in this question we will have trial here in this question we will have a pass that's route C 80 if we search a pass that's route C 80 if we search for Cairo for Cairo inside the try would follow the route to inside the try would follow the route to node C node a node T and no T we have an node C node a node T and no T we have an end of word flag so with that flag you end of word flag so with that flag you were indicating that the path from root were indicating that the path from root to that node C 80 or it's just the past to that node C 80 or it's just the past we the the characters we'll look at from we the the characters we'll look at from the front the word you know until the the front the word you know until the time we see the flag is a actual prefix time we see the flag is a actual prefix that matches the word so so if we use a that matches the word so so if we use a try try it would just be linear time search with it would just be linear time search with respect to the lens of each individual respect to the lens of each individual word and for the whole sentence it would word and for the whole sentence it would just be linear with respect to the just be linear with respect to the length of the sentence that's the run length of the sentence that's the run time complexity of use to try so but time complexity of use to try so but used Phi we have additional time and used Phi we have additional time and space complexity to create a try the try space complexity to create a try the try is going to be the size of the input is going to be the size of the input dictionary in terms of both the time to dictionary in terms of both the time to construct it and also the space to store construct it and also the space to store it but with that the search for the it but with that the search for the replacement in a sentence will be linear replacement in a sentence will be linear with respect to the length of the with respect to the length of the sentence so if the sentence can be super sentence so if the sentence can be super super long using in a try could be more super long using in a try could be more efficient so that's a pretty much the efficient so that's a pretty much the big idea about using try to solve this big idea about using try to solve this problem problem yeah so let's close this off I'm just yeah so let's close this off I'm just going to maybe code the bigger bigger going to maybe code the bigger bigger idea first and then try to finish the idea first and then try to finish the details so we initialize a tri data structure create an object or from the class and just before I would do a little bit change there I think this should be prefix okay I'll code a insert function for the try to insert a pass that cost value to the prefix so that's a that takes that take care of that try search space join join together all the worst space join join together all the worst I've been passed into some kind of a I've been passed into some kind of a replacement helper function so that's replacement helper function so that's the the workforce of the workforce for the the workforce of the workforce for this problem is going to be this this problem is going to be this replacement function so you will take a replacement function so you will take a word and try to return this replacement word and try to return this replacement so for this we're just gonna traverse so for this we're just gonna traverse inside the try for I character in inside the try for I character in enumerate over the characters in the enumerate over the characters in the word character by character if the word character by character if the character is not in the try node that character is not in the try node that means the current to pass inside the try means the current to pass inside the try is not a valid prefix for the word so in is not a valid prefix for the word so in our case we'll just return the word our case we'll just return the word itself we don't do any replacement and itself we don't do any replacement and this joint here we'll put that back put this joint here we'll put that back put that work back into the modified that work back into the modified sentence otherwise we will just keep sentence otherwise we will just keep reversing once we move to the next node we want to check do we have an upward flag if we do have one that means the path right now is the prefix for this word so since we also have an int index generator here you know we iterating over 2 pairs of index and character so from the beginning towards here is the actual prefix so we just return this so that's the replacement - of course - to facilitate this we have to actually code up at the wide area structure so here our constructor is basically a creative empty root node define this node object inside the try class which I would just stare as my as my code yesterday are just gonna subclass the default and we will have a kind of flag that end and we will have a kind of flag that end up war flag for this new so everything up war flag for this new so everything has to be false has to be false its initial to be false so that's the its initial to be false so that's the try node and the constructor for the try try node and the constructor for the try all we need is to have this insert all we need is to have this insert function the search function is function the search function is implemented inside the solution carrots so we basically just for all the prefix we have we will try to insert that into the try and at the end of each prefix we will flag that to be the end of the word so when we actually search for the word if we just just follow the character by character in the world if we find it and a wonderful word flag inside the try note we will return the the portion of the word along until the point so I so I would just call this search now or so I would just call this search now or replace replace is fine so or just replace replace is fine so or just replace this with South our route yeah so that's so I would just call this tried or replace okay let me see if I have honest problems so this replace function I just gonna start off on the route enumerate over character by character inside this word so it will be something like ca TT le so the first iteration we grab C which the is 0 and we see do we have a C note after the root which we do have 1 so we will just move to that node and test the do we have an end of word flag obviously we don't so we keep in the cube to then move to the next character which is a and just keep going on till we find character t if we find the character T the node would have an end of war flop so we return the portion of the search word opponent in that position so it will be CIT the actual prefix so it looks looks pilots if I run it I was working not working what's the problem okay I see I should convert this to list I guess so the map object is non what's this test case so it's a lot of prefix and the search world are quite long what do my code outputs the expecting string instance so which is the problem here mr. so which is the problem here mr. Schneider if I split by space the we do Schneider if I split by space the we do have a bunch of words could could it be have a bunch of words could could it be that after this full loop I'm not that after this full loop I'm not returning anything so I don't have returning anything so I don't have neither the end of word or oh it could neither the end of word or oh it could be that my word is actually shorter than be that my word is actually shorter than a prefix so that I do have partial March a prefix so that I do have partial March with the prefix but I don't I don't even with the prefix but I don't I don't even meet the shortest prefix so the word is meet the shortest prefix so the word is actually shorter than the prefix so actually shorter than the prefix so let's if we have a single character like let's if we have a single character like see here inside this input sentence the see here inside this input sentence the replace will return nothing ok so to replace will return nothing ok so to catch that we just return word in the US catch that we just return word in the US that lost the resort so I don't I don't that lost the resort so I don't I don't need this map right I don't need this need this map right I don't need this list the conversion right so let's see list the conversion right so let's see yeah this time is working so yeah this yeah this time is working so yeah this this this return here handles the case let's try this okay it's working so that's the twice solution so with the try implementation the code is really really really simple the rant is that linear with respect to the size of the prefixes we have in terms of bonus time and space to you know to populating the try and also to store the try for the for the replacement part it's a linear waste of s with respect to the impose sentence size so yeah so that's that's | 2024-03-20 14:40:13 | 648 | Leetcode 648 Replace Words |
|
WZB2EMwpLJo | hey guys welcome or welcome back to my channel so today we are going to discuss channel so today we are going to discuss another problem problem is wiggle another problem problem is wiggle subsequence so a wiggle sequence is a subsequence so a wiggle sequence is a sequence where the difference between sequence where the difference between successive numbers strictly alternate successive numbers strictly alternate between positive and negative between positive and negative okay meaning the difference between uh okay meaning the difference between uh alternate numbers should be alternate so alternate numbers should be alternate so if this is differences if this if this is differences if this difference is positive then this difference is positive then this difference should be negative then this difference should be negative then this should be positive this should be should be positive this should be negative like this negative like this the first difference may be either the first difference may be either positive or negative so this first positive or negative so this first difference like between the first two difference like between the first two elements difference could be either elements difference could be either positive or negative positive or negative a sequence with one element and a a sequence with one element and a sequence with two non-equal elements are sequence with two non-equal elements are trivially wiggle sequences okay for trivially wiggle sequences okay for example this is a vehicle sequence why example this is a vehicle sequence why this is the vehicle sequence C this is the vehicle sequence C difference between 1 and 7 7 minus 1 6 difference between 1 and 7 7 minus 1 6 then 4 minus 7 is minus 3. then 9 minus then 4 minus 7 is minus 3. then 9 minus 4 will be 5 4 will be 5 then 2 minus 9 will be minus 7 and then then 2 minus 9 will be minus 7 and then 5 minus 2 will be 3. so see these are 5 minus 2 will be 3. so see these are alternate differences positive negative alternate differences positive negative positive negative positive so this whole positive negative positive so this whole is a wiggle sequence is a wiggle sequence this is not a wiggle sequence because this is not a wiggle sequence because 4 minus 1 will be 3 and 7 minus 4 will 4 minus 1 will be 3 and 7 minus 4 will also be 3. so also be 3. so both the differences are positive only both the differences are positive only so this is not wiggle sequence and this so this is not wiggle sequence and this is y not wiggle sequence because the is y not wiggle sequence because the last two elements have different 0 and 0 last two elements have different 0 and 0 that is not that is not uh wiggled okay so it is mentioned here uh wiggled okay so it is mentioned here so a subsequence we know that so a subsequence we know that subsequence is uh deleting some elements subsequence is uh deleting some elements from the original sequence and leaving from the original sequence and leaving the remaining elements the remaining elements given an integer array so array is given given an integer array so array is given to us and we need to find out the length to us and we need to find out the length of the longest wiggle C subsequence of the longest wiggle C subsequence meaning alternate uh difference meaning alternate uh difference subsequence the largest length we need subsequence the largest length we need to just return in the output the length to just return in the output the length okay okay so I hope you understood the problem so I hope you understood the problem let's see this test case let's see this test case so here here see what would be the so here here see what would be the maximum length maximum length back length back length what could be that just stop the video what could be that just stop the video uh and try to think what could be the uh and try to think what could be the maximum length of this uh sequence where maximum length of this uh sequence where uh maximum length of the uh vehicle uh maximum length of the uh vehicle sequence the figure sequence sequence the figure sequence so see first we can take one so see first we can take one seventeen seventeen so this will be positive so this will be positive then we can take 5 then we can take 5 so this will be negative so this will be negative then we can take 10 then we can take 10 so 10 minus 5 will be 5 which is so 10 minus 5 will be 5 which is positive positive after 10 we should take 30 after 10 we should take 30 no we should not take 13 because 10 13 no we should not take 13 because 10 13 minus 10 will be positive 13 minus 10 minus 10 will be positive 13 minus 10 will be 3 so that is positive and will be 3 so that is positive and positive positive we should not have we positive positive we should not have we should have alternate should have alternate so there is no benefit of taking 13. so there is no benefit of taking 13. so we can take 15 no can we take 10 no so we can take 15 no can we take 10 no we should take 5. we should take 5. why we should not take 10 because then why we should not take 10 because then it will be 0 and we saw that we cannot it will be 0 and we saw that we cannot do right so 5 we will take this 5 so 5 do right so 5 we will take this 5 so 5 minus 10 will be minus 5. then 16 we can minus 10 will be minus 5. then 16 we can take take 16 minus 5 will be what 11 which is positive and then 8. that is 8 minus 16 will be minus 8 which is negative so see positive negative positive negative positive negative and what is the length one two three four five six seven so maximum length is 7. output will be 7. all right see this test case output is 7. so I hope you got some idea uh see I'll I'll give you some idea that how you can approach this problem as we see saw this test case right what we were checking see let's let's try run again let's uh again see how we can do it uh how we just find found out this length what we did was initially we have we were taking this one so we had taken this one and then we have taken the 17 and we saw that okay their differences positive so the next difference next difference we should take should be what negative right obviously because this is positive so next difference which should take as negative so previous difference previous was positive right now we should take negative so if we have 5 here what will be the difference it will be minus 12 which is negative so we can take this 5 right so we can take this 5. now the previous difference will be what negative so here the previous difference is now negative similarly now the next difference we will uh find we will we should consider is positive because the previous was negative right it was negative so we will take this 10. because 10 minus 5 will be what positive 5. so now the previous will be 5 because we have taken this 10. right positive similarly now we will take we will now we will find a negative difference so should we take 13 no should we take 15 no because 13 or 15 will give us positive difference so we will not take 10 also so we will take 5 because 5 minus 10 will be minus 5 and we will we we should because previous is positive right so now we should take negative and we found negative so something this we should do right based on the previous difference we should find the next difference okay so dry you do one thing try to Now using this approach try to dry run once think of the uh like this was the idea think of the approach what you can do using the previous difference so now let's dry in this approach right a very easy approach C what I will be doing right I will be taking two variables total three variables I will be taking one variable will be to store the count or you can say the length of the subsequence current one different one will be the previous what was the previous difference like the was it negative or was it positive and one will be the difference like this is the current difference to store the current difference okay so first of all see at least at least there should be two elements right at least two elements will be there so at least two will be the answer because 1 17 right or one like a single element or two elements so if there are two elements answer will be two if there is only one element so answer will be one right so this is simple okay so this is one thing now what we will do right at least see if there is if the length if the length of this whole subsequence whole sequence right is more than two it means at least 2 will be the answer count will be at least 2 because we can take any two elements we can take this or this we can take this or this right no not this and this this or this so if the if there is if the length is more than two at least 2 will be the answer I hope this is clear so initially count value I will take as 2 and what I will be doing is this is 10 uh so what I will be doing is uh here previous will be what previous will be this difference between nums of 1 minus nums of zero so nums of 1 is 17 minus nums of 0 is 1 so this will be what 16 so previous will be 16. difference right so this previous will store the previous difference and this difference will be the current difference so right now we will start our Loop right we will Traverse we will start reverse because we have taken these two so we will start traversing from two index that is from here so every time what I will be doing uh will be let me remove this so I will be doing these steps what are the steps first of all I will be calculating difference difference is what I I minus nums of minus nums of the last element that is numbers of I the last element that is numbers of I minus 1. okay this is I right this is I so 5 minus 17 this will be what minus 12 so current difference is minus 12. so should we take this 5 right how we will decide should we take this 5 or not previous was 16 that is previous difference was positive 16 is positive right and the current difference is negative is this fine think previous difference was positive this is negative so it's fine right we should have alternate so we will take this 5. so if difference what is difference current difference is negative if difference is less than zero and and previous is greater than 0 previous is greater than 0 right 16. in that case we will do what count plus plus because this is fine right alternate this is alternate so we will increment we will increment our count that is we will take this subsequence so count will become 3 and what we will do now now we should update the previous why because now this will be the previous difference so previous what we can do simply we can assign the difference value to previous that is for the next further iteration this will be the pre this now this will be the previous difference so that is difference will be equal to difference will be assigned to previous right so now what we will do okay and I I will move forward all right so I hope you got this thing now let's again do the same steps first of all we will find out the difference so what is difference 10 minus 5 so 10 minus 5 will be what five the difference is positive previous difference was what negative this previous difference is What minus 12 which is negative so again if difference is what positive greater than 0 and previous is less than 0 which is negative so is is less than 0 which is negative so is it fine it fine yes it's fine these are alternate so we yes it's fine these are alternate so we will again do the same thing count plus will again do the same thing count plus plus plus and now difference will be assigned to and now difference will be assigned to previous because now this will become previous because now this will become the previous difference the previous difference the difference was what five five will the difference was what five five will be assigned to minus 12 here 5. be assigned to minus 12 here 5. okay okay and also I forgot to increment the count all right I will also move forward now I will come here now let's find out the difference 13 minus 10 will be what three so difference is positive previous difference is what again positive is it fine no this is not fine these are not alternate so we will not do anything that's not satisfy this condition does not satisfy this condition so we will not do anything and what we will do we will just move forward again we will find out the difference 15 minus 13 which is 2 so difference is positive and previous difference is what again positive these are not alternate so we will again increment this will be what this will be what 10 10 minus minus 15 15 right 10 minus 15 so now what we will do um this will be what minus 5 right this will be what we are doing here 10 minus 15 so this will be minus 5 negative and previous was positive so negative and previous was positive so this is fine right so we will increment this is fine right so we will increment count count and we will assign the current and we will assign the current difference which is -5 here difference which is -5 here to previous to previous and we will increment so I will come here now 5 minus 10 will be What minus 5 this is negative and previous was also negative so this is not alternate so we will move forward now what we will do now again we will find out the difference 16 minus 5 16 minus 5 which will be 11 so this is positive previous was negative so it will it is uh this condition this one so count increment assign previous so current is 11 so we will assign this to previous now okay okay so I I will come here so I I will come here 8 minus 16 now it will be minus a 8 minus 16 now it will be minus a so current difference is What minus it's so current difference is What minus it's negative minus it in previous was negative minus it in previous was positive so this is alternate positive so this is alternate so we will this will be set this is so we will this will be set this is satisfying this condition satisfying this condition so we will increment count 7 and we will so we will increment count 7 and we will assign this difference minus 8 to assign this difference minus 8 to previous previous so out we have traversed the array whole so out we have traversed the array whole array and the array and the output is 7 count is seven so this is output is 7 count is seven so this is our output our output so I hope you understood the problem and so I hope you understood the problem and the approach let's see the code once the approach let's see the code once very simple problem just we have to very simple problem just we have to keep a record of the previous right keep a record of the previous right so if the size is less than 2 that is so if the size is less than 2 that is the answer we will find out the previous the answer we will find out the previous count we will keep count we will keep and then we will Traverse this array and then we will Traverse this array okay and we will find out the difference okay and we will find out the difference and if it's see these are two conditions and if it's see these are two conditions right but the this thing was same right right but the this thing was same right so we have taken these two conditions so we have taken these two conditions and we have and we have or in between or in between and we are just doing the same thing and we are just doing the same thing and at last we will be returning the and at last we will be returning the count count so we have a single traversal right we so we have a single traversal right we are doing a single reversal so time are doing a single reversal so time complexity is O of n complexity is O of n and space we are not using any extra and space we are not using any extra space we are just taking variables so space we are just taking variables so this will be space will be constant this will be space will be constant so I hope you understood the problem and so I hope you understood the problem and the approach let me know in the comments the approach let me know in the comments if you have any doubt if you found the if you have any doubt if you found the video helpful please like it subscribe video helpful please like it subscribe to my channel and I'll see in the next to my channel and I'll see in the next video thank you | 2024-03-24 11:42:44 | 376 | Wiggle Subsequence | Leetcode 376 | Arrays |
|
AHI_Kd6W6sQ | hey guys what's up today the question we're gonna say is 305 the number of we're gonna say is 305 the number of islands two right islands two right it's basically the question derivative it's basically the question derivative from the question two hundred likes from the question two hundred likes uh the number of islands one if you guys uh the number of islands one if you guys haven't finished that can just try that haven't finished that can just try that first first and they said that it gives us you know and they said that it gives us you know the two degrees the two degrees uh both you know zero and the one uh both you know zero and the one specifically and we specifically and we uh to initialize we're just gonna give uh to initialize we're just gonna give us zero and us zero and there will be the parameters m and the n there will be the parameters m and the n to be represented by the row and the to be represented by the row and the column column and also it will give us the positions and also it will give us the positions which means that zero one one which means that zero one one blah blah blah so what are those blah blah blah so what are those constraints used for they will be constraints used for they will be uh the updated operations where we first uh the updated operations where we first build zero one build zero one means that zero one there will be this means that zero one there will be this one we will replace that into one one we will replace that into one to you know to philippines into the one to you know to philippines into the one and uh here obama means that we have and uh here obama means that we have to be one here and one here this is one to be one here and one here this is one zero zero and then zero zero and every time we and then zero zero and every time we will consider them to be connected will consider them to be connected if they you know the up down left and if they you know the up down left and the right the right are both you know the same value will be are both you know the same value will be the one right so this kind of the one right so this kind of you know operations are updated uh to you know operations are updated uh to update our board and update our board and to see finally uh let's see if you to see finally uh let's see if you finally have the board which will be finally have the board which will be like like 0 1 0 0 1 y zero one 0 1 0 0 1 y zero one so they will be like quantity four like so they will be like quantity four like three because like this is the first one three because like this is the first one the second one is in the third one so the second one is in the third one so yeah that's basically the uh yeah that's basically the uh the whole idea for this question so how the whole idea for this question so how are you gonna see that and are you gonna see that and basically uh before i just saw this basically uh before i just saw this question question i see that there's one description i see that there's one description that's that there will be like the uh that's that there will be like the uh any band after each and the land any band after each and the land operations operations so if you guys can see that they will so if you guys can see that they will have a constant update have a constant update of kinetic components so yeah that's of kinetic components so yeah that's basically what are we going to do basically what are we going to do we first will see number statements we first will see number statements we first will register will be we first will register will be considered considered the unified operation why is that the unified operation why is that because because unified can actually after the you know unified can actually after the you know two different two different connected components and to merge it and connected components and to merge it and using that efficient way and using that efficient way and it's quite useful when you are dealing it's quite useful when you are dealing with you know with you know uh connection and the business component uh connection and the business component between each part and between each part and to make some updates and to get the to make some updates and to get the information that you want so basically information that you want so basically we will just we will just perceive using the wf the widget unif perceive using the wf the widget unif file which is the optimized version of file which is the optimized version of union file and union file and we can see that code later uh what's the we can see that code later uh what's the most intuitive idea for this algorithm most intuitive idea for this algorithm the first way we're just gonna the first way we're just gonna uh traverse that and uh notice that uh traverse that and uh notice that there will be the duplicated data which there will be the duplicated data which means that we need to means that we need to avoid those kind of things in our avoid those kind of things in our calculations right so the first step calculations right so the first step the first step will be like how do we the first step will be like how do we use the unified to use the unified to modify that first i will just gonna um modify that first i will just gonna um to to imitate the process of you know adding imitate the process of you know adding these points and first it will be zero y these points and first it will be zero y so we're just gonna be here will be one so we're just gonna be here will be one here here will be one so that one of here here will be one so that one of that but you can that but you can define whatever values that you want it define whatever values that you want it doesn't matter it's different from you doesn't matter it's different from you know know the existing uh sales right and that the existing uh sales right and that will just be one one one will be here so will just be one one one will be here so we're just gonna have to do that we're just gonna have to do that however because first our result said however because first our result said because we want us to return the list of because we want us to return the list of you know integer results first will be you know integer results first will be one because we only have one one because we only have one connected component right uh after we connected component right uh after we enter the one one enter the one one point here we will actually we will the point here we will actually we will the value will also be one because like this value will also be one because like this can be connected by this one and you can can be connected by this one and you can know after left and right know after left and right whenever they have the same value for whenever they have the same value for the one it will just still be connected the one it will just still be connected right right and then we're just gonna be like uh go and then we're just gonna be like uh go to here one zero one zero which will be to here one zero one zero which will be this part this part so we're gonna be becoming well one and so we're gonna be becoming well one and we will also we will also to add that to be the one and then to add that to be the one and then finally we're just gonna add the zero finally we're just gonna add the zero zero which means that we zero which means that we need to add it here so this will be uh need to add it here so this will be uh zero zero and we also zero zero and we also because those fours are actually because those fours are actually connecting together right so basically connecting together right so basically whenever we just whenever we just added that we can define the object added that we can define the object which is the which is the unified object and it has a count unified object and it has a count which can be used to you know counter which can be used to you know counter how how how many components have we left because how many components have we left because we usually initialize we usually initialize that with you know m plus n this is a that with you know m plus n this is a classic problem classic problem or unified so that you are supposed to or unified so that you are supposed to have some kind of background that's have some kind of background that's running on this knowledge running on this knowledge and yeah that's basically the whole idea and yeah that's basically the whole idea and also will be uh and also will be uh take this for example three or uh three take this for example three or uh three or or one however this will be in the one however this will be in the duplicate data so we're just gonna duplicate data so we're just gonna ignore that ignore that we will be like here and whenever we you we will be like here and whenever we you know have the three or one three or one know have the three or one three or one this is here we're just gonna edit that this is here we're just gonna edit that and here we actually rather will be and here we actually rather will be changed to two because that changed to two because that uh this is just gonna be like uh the uh uh this is just gonna be like uh the uh the unique one that uh do not connect it the unique one that uh do not connect it to any of these components right so to any of these components right so yeah that's basically the process when yeah that's basically the process when we're using the uh we're using the uh uh the union effect however there are uh the union effect however there are still some details that we still some details that we that i want to go through with you that i want to go through with you because that it's kind of hard to figure because that it's kind of hard to figure out out and to be honest i have spent some time and to be honest i have spent some time on this problem so i hope on this problem so i hope you guys can after seeing this video to you guys can after seeing this video to save you some time so yeah that's the save you some time so yeah that's the goal with the goal with the second step so how to use that is that second step so how to use that is that we first will define a variable which is we first will define a variable which is www we'll cons we will continue like www we'll cons we will continue like you can see from here we will actually you can see from here we will actually have those kind of messes for example have those kind of messes for example we will have like union to unite those we will have like union to unite those kind of kind of uh for example union two points this is uh for example union two points this is uh our dividend uh our dividend uh take int and end and also we will uh take int and end and also we will have one we will have a fine have one we will have a fine to find the root because like in the to find the root because like in the union fight we need to find the root of union fight we need to find the root of the you know the the you know the point so it's also will be like five point so it's also will be like five operation and also we will just kind of operation and also we will just kind of uh have a connection uh connected to uh have a connection uh connected to charge whether or not there are two charge whether or not there are two points are connected points are connected right and also we need to you know uh right and also we need to you know uh return the cut we need to get a con return the cut we need to get a con so how exactly that is algorithm works so how exactly that is algorithm works first we will first we will define those uh we'll define first the define those uh we'll define first the variable variable and uh yeah just before i start i want and uh yeah just before i start i want to say that my version of to say that my version of unified are derivative from the unified are derivative from the princeton algorithm that you know the princeton algorithm that you know the course has really course has really read and my code are really the same read and my code are really the same from here if i define the id item means from here if i define the id item means that the root of the that the root of the uh the root of the node and uh say the uh the root of the node and uh say the size size will be like because we want size size will be like because we want the balance tree we don't want in the the balance tree we don't want in the one tree to be one tree to be so long and the other child will be just so long and the other child will be just you know this strong so you know this strong so actually using the size side here we're actually using the size side here we're actually to add actually to add the uh add the little tree to the uh add the little tree to the bigger bigger one the bigger bigger one and this used to keep track of uh and this used to keep track of uh keep track of the size this side you keep track of the size this side you have to keep our have to keep our side and wherever we have the union side and wherever we have the union operation we're just going to add a operation we're just going to add a little one little one into the bigger one in order to make the into the bigger one in order to make the you know balance tree to make it look you know balance tree to make it look nicer right nicer right so yes that's basically our operation so yes that's basically our operation and for our algorithm that's actually and for our algorithm that's actually the most important one the most important one actually we first will knew the new uh actually we first will knew the new uh wf right and the second one will be like wf right and the second one will be like because we actually because we actually we're just gonna transfer that so what we're just gonna transfer that so what are we gonna first of that i'm just are we gonna first of that i'm just gonna gonna first uh because you guys understand one first uh because you guys understand one question also i'm just gonna question also i'm just gonna you you read that and uh you you read that and uh we're all very good we will be like okay we're all very good we will be like okay this part this part and uh for this algorithm and uh for this algorithm uh first we were just gonna new the uh uh first we were just gonna new the uh uh wf uh wf and with parameter over m plus n because and with parameter over m plus n because like uh we will convert like uh we will convert the two dimensional array into the one the two dimensional array into the one one dimension by using you know one dimension by using you know maybe you'll give me the point of zero maybe you'll give me the point of zero zero 3.0 and zero 3.0 and i can convert it to this one right so i can convert it to this one right so i'm just gonna i'm just gonna say convert it from the two different say convert it from the two different two dimension to one dimension right two dimension to one dimension right and yeah and the second step the second and yeah and the second step the second thing thing is that we when we need to go to rest of is that we when we need to go to rest of that we're just gonna four that we're just gonna four four into position and the two four into position and the two uh positions and uh further in this loop uh positions and uh further in this loop we're just gonna check we're just gonna check because first whenever we introduce one because first whenever we introduce one point in this board point in this board we actually because we're here we have a we actually because we're here we have a contour right and i'm just gonna contour right and i'm just gonna using the using the right using the using the right counter will be the most important part counter will be the most important part in our algorithm we first of all define in our algorithm we first of all define counter to be zero because there will be counter to be zero because there will be no component no component in our report however where we added the in our report however where we added the zero y so at first we were just gonna zero y so at first we were just gonna uh increase uh increase we're just going to increase let's see our increase the counter your contrast pass and then we're just going to see whether or not the up down left and the right are they connected yet if they have already connected we should just you know to decrease counter otherwise the number will be you know are invalid because we have increased that where we increase that we perceive he or she as a unique identity they don't connect with anybody however if we found out you have already connected to you know this particular start so we're just gonna delete that and you can see from here uh i will just you know to check that and after that we are just going to add it uh using our result editor result is a kind of value that we want to return so that it will be like our result editor say our record value so that's basically the organs for that first we're just gonna introduce one union five object and a second we're just gonna go through that and the first we're just gonna increase the contract and every time whenever i just occur uh to find out if you guys have never connected before i'm just gonna connect with that and say let's see because there's one tricky part let's see we have this guy this guy is a guy what do you see uh this guy this guy has already connected and uh they are already connected and we first will go like uh first find the first one and we connect them right so we're just gonna count minus minus right however wherever we connected those guys and we want to find out this this guy and we're connected with them because they haven't planned it yet right so we also need to perform the con minus minus because we need to eliminate the this energy in order to make the count be valid however wherever you see that because those three bodies are connected already if we see weakness in this guy and we also need to minus that that was just going to be a problem so we need to first to examine whether or not this guy and this guy has already connected if yes we are just going to continue that otherwise we are just going to follow this operation and finally we are just going to edit our result into the result set so that's basically the uh the whole idea for this and also there's another part which is called the uh to how to handle our duplicates because never see here if you just go through this logic and we will also encounter the comb miners when we mix the duplicates so they one pro one possible result will be like we can use like we can use we can attach that and every time we use the uh to define the symbol which is a string from the x coordinate and y coordinate and the arrow kind of everything encounter the same part for example we can define a variable which is uh this is our headset and we can define the x variable plus our i plus the uh variable this is become our symbol uh as well and uh simple and the arrowhead has been u whether or not has been examined if it does we'll continue that otherwise we will introduce the you know duplicates and if not we're just going to add it to our headset which we can call it uh relative and uh to you know go towards this step one two three and finally yeah that's basically the whole idea for this question and let's go see how could you implement in those kind of steps oh yeah after go through the basic process let's see the uh implication of the code well first we were just going to the the union fight and uh the codes that i write are from uh sir princeton the all gold yeah that's all algorithm prison and i believe that the code that he writes are you know really elegant so i'm just gonna borrow from that yeah and uh to be honest i modify a little bit this count and just uh to promote it to be the public and also to remove the operation of the comb minus after we just make the union because like we have another usage so we don't you know follow that rule and uh for our main code we first we're just gonna this is a video that we define the other two y duplicates and this is just a unified the object that we define uh with a parameter of m times seven because we need to convert those uh say uh two array dimensions to one to one dimension right and also this is simple we need to a y duplicate and we added that and this is actually the most the core part you can see from here we first will just change it to the one because we use one to uh two distinct from other kind of surrounding cells for example zero and which means that it has been you know to added and um yeah and every time we go through this process and do you remember that where we find one that we haven't connected we're just gonna minus one right otherwise we're just gonna you know because sometimes wherever we connect like the first two and uh there will be the possibility that uh the layer two will be connected because we have connected previously so you need to first to find out whether or not it has not been connected if yes we're just gonna uh to minus that otherwise we don't do anything because like you will you if you actually minus four times every time you in the loop you will just gonna introduce the uh duplicates situation which will result in a uh raw number and finally which is gonna result i added and every time we're just gonna edit the wfs.com console that we will just uh uh this part will introduce us with one entity and we see that whether or not these are connected both up down left and the right yeah that's basically the whole idea and we're just going to return it out so yeah that's actually a great question considering using the model of wf the weighted unified to solve this problem the uh it's actually a classic unified problem and uh yeah that's it for question 305 the | 2024-03-24 10:04:56 | 305 | leetcode 305 Number of Islands II |
|
Do2BcLMfyoE | Hello hello everyone welcome dandruff exactly edison electronic in this question on subscribe oil olive oil ko hai to subscribe oil olive oil ko hai to electronics and example electronics and example possible se 0110 neurotic last 2 and will update possible se 0110 neurotic last 2 and will update were 2002 c the tarzan tarzan tarzan the car were 2002 c the tarzan tarzan tarzan the car ki stock board heart ki stock board heart ki stock board heart Subscribe Subscribe 10 And Subscribe Subscribe Subscribe 10 And Subscribe Button And Button And That Unless Ronit The Question Example Of That Unless Ronit The Question Example Of Bird's Logic Wife Viewer Test Cases subscribe the Bell Icon Subscribe This Is The One Is The One Is The One The First One Events During The Previous Protest Starting In Dowry Is Up Till Recently Introduced Into Something 10 Subscribe 2018 201 Number One Adhikar Hai 200 Win This Implies Cafe 20 Tax Unleashed You Don't Witness Forest Wealth Stupid This Trick Paul Possible So If Stupid This Trick Paul Possible So If Stupid This Trick Paul Possible So If In Pimples Going For Electronic Vid U To In Pimples Going For Electronic Vid U To 101 60 Convert Into Your Monotonic Increasing 101 60 Convert Into Your Monotonic Increasing Sequence A Sequence A Possibility Is New Updates 2025 Button Video Subscribe To That Button Video Subscribe To That And 231 Rates From Distant View Of And 231 Rates From Distant View Of Possibilities In More And Two Possibilities In More And Two A Novel Which Will Have Been Put In More A Novel Which Will Have Been Put In More Money And In The Mid-1960s Subscribe To That Money And In The Mid-1960s Subscribe To That I Will Pick Up Do Minimum Voting Service I Will Pick Up Do Minimum Voting Service To People Didn't Listen To Be Converted To People Didn't Listen To Be Converted From 210 210 Videos Vidmate Vidmate From 210 210 Videos Vidmate Vidmate Element 2021 Adb School Vid U Element 2021 Adb School Vid U Mein 150 Mein 150 Mein 150 Ek Ansh Do The Best Variable Digestive Want Get Updates subscribe to the Video then subscribe to subscribe to the Video then subscribe to the Video then Main the Video then Main Unferval COD Don't Want But In Unferval COD Don't Want But In Doing So Will Lead You To Contest Channel Ko Subscribe And Subscribe The Protest for the Protest for the Protest for the shampoo Bihar 2.0 to and the Shravan ko shampoo Bihar 2.0 to and the Shravan ko and beautiful post my balance 1.138 volts and beautiful post my balance 1.138 volts and short to waste time subscription and short to waste time subscription that Arvind current account Dr to banaras that Arvind current account Dr to banaras vansh updated on Thursday cnn-ibn understand what vansh updated on Thursday cnn-ibn understand what is the what will subscribe Old Old Old Subscribe The Channel Subscribe Subscribe To That Politics And Dancer Option 2000 Updated On One Plate Hour Showpieces One Plate Hour Showpieces Hai Andhra Green Beans Tutorial C That Hai Andhra Green Beans Tutorial C That Deposit 1021 Account Deposit 1021 Account Dada Becomes Number One Sathya Witness To Offer Report Vansh One Will Update Soon In This Again There There There are two Next VCD in this video 021 Subscribe to ke din kshatriya hai iss vansh will update same Bill-2012 subscribe to The Amazing All Bill-2012 subscribe to The Amazing All Videos Subscribe to Play List Talk About a Very Interesting Half Minute Adhir Video then subscribe to The That I Want How To See And Post Element Wale Episode Subscribe Cr Video subscribe And Subscribe Subscribe To That Is To And Institute Of Getting 80 Will To That Is To And Institute Of Getting 80 Will Update 120 Updates 2120 Donate Subscribe What Update 120 Updates 2120 Donate Subscribe What We will do do do do subscribe to and We will do do do do subscribe to and add account dip account is to to the add account dip account is to to the latest update 2021 will do to take off but answer are to day 30 update to subscribe one and will update the same account 238 Lo Urgent Lo Urgent Lo Urgent To Show The Answer Stills Elements To Accident To Show The Answer Stills Elements To Accident To Back Once Its Importance Of To Back Once Its Importance Of A Guru Can Update Between 210 Subscribe A Guru Can Update Between 210 Subscribe subscribe and subscribe the Video then subscribe and subscribe the Video then subscribe to the Page That Aap Side Effects 200 Gram 10021 Content Is Visible To Deal With Videos Twist Videos Twist Videos Twist Life In Preventing Start Flu Subscribe 21 2012 Pickup The Phone I Hope That's Logic And Looting liked The Video then subscribe to the Video | 2024-03-25 11:14:20 | 926 | Flip String to Monotone Increasing | Leetcode 926 | Live coding session |
|
XN1RKQJ6l7Q | so guys let's proceed to the question number number 1171 remove zero some consecutive notes 1171 remove zero some consecutive notes from link list so basically in this we from link list so basically in this we have to remove have to remove the uh zero sums that is for example in the uh zero sums that is for example in this array 1 + 2 = 3 and 3 and minus 3 this array 1 + 2 = 3 and 3 and minus 3 is also zero so we will remove Min -3 is also zero so we will remove Min -3 and also - 3 + 3 = to 0 so we will and also - 3 + 3 = to 0 so we will remove 3 so the answer should be 1 to remove 3 so the answer should be 1 to one so for this we will create map running Su for running sum and we willay sual to z l star W list node and we point point we will find the next to will sum equal to sum this current value and also uh we we will do what we store store current [Laughter] [Laughter] [Laughter] equal to Sun Su equal to Su plus current value and Su equal to Su plus current value and if Su not find to do to do n that means we have ENC counted zero so n that means we have ENC counted zero so we we will to next next current current next we will return Dom equal to solution so we will run it time in this there is little problem text property so it property so it is is as we want it to run as we want it to run so this is so this is basically code is basically code is submitted thank you for watching | 2024-03-25 18:40:48 | 1,171 | Leetcode 1171. Remove zero sum consecutive Node from linked list |
|
4e1gVeQ0AEs | hello and welcome back to the cracking fang youtube channel today we're going fang youtube channel today we're going to be solving lead code problem number to be solving lead code problem number 71 simplify path let's read the problem 71 simplify path let's read the problem description given a string path which is description given a string path which is an absolute path starting with a slash an absolute path starting with a slash to a file directory in a unix-style file to a file directory in a unix-style file system convert it to the simplified system convert it to the simplified canonical path in a unix-style file canonical path in a unix-style file system a period refers to the current system a period refers to the current directory a double period refers to the directory a double period refers to the directory upper level and any multiple directory upper level and any multiple consecutive slashes are treated as a consecutive slashes are treated as a single slash single slash for this problem any other format of for this problem any other format of periods such as three periods are periods such as three periods are treated as file treated as file directory names the canonical path directory names the canonical path should have the following format the should have the following format the path starts with a single slash path starts with a single slash any two directories are separated by a any two directories are separated by a single slash the path does not end with single slash the path does not end with a trailing slash a trailing slash the path only contains the directories the path only contains the directories on the path from the root directory to on the path from the root directory to the target file or directory ie no the target file or directory ie no period or double period return the period or double period return the simplified canonical path simplified canonical path so if we look at our examples we're so if we look at our examples we're given you know path equals slash home given you know path equals slash home slash and we should return slash home slash and we should return slash home why do we get rid of the slash well why do we get rid of the slash well remember the path does not end with a remember the path does not end with a trailing slash so we need to get rid of trailing slash so we need to get rid of this what about this example slash home this what about this example slash home double slash foo slash well again we get double slash foo slash well again we get rid of the trailing slash and we need to rid of the trailing slash and we need to treat this double slash as a single treat this double slash as a single slash slash so we've read the question prompt and so we've read the question prompt and we've looked at an example but how are we've looked at an example but how are we actually going to solve this problem we actually going to solve this problem intuitively let's think about it okay so intuitively let's think about it okay so we read the question prompt and we we read the question prompt and we looked at a few examples but we didn't looked at a few examples but we didn't talk about how we're actually going to talk about how we're actually going to solve this problem solve this problem well the first thing to realize is that well the first thing to realize is that the problem tells us that there's really the problem tells us that there's really going to be only a few elements that we going to be only a few elements that we can see in our path right we're only can see in our path right we're only going to honor you know a single slash going to honor you know a single slash some potential like multiple slash we some potential like multiple slash we could have a single dot we could have could have a single dot we could have you know multiple dots two of them you know multiple dots two of them we could have you know some sort of like we could have you know some sort of like directory name directory name and that's about it and that's about it we can't have anything else in our path we can't have anything else in our path so the algorithm that we want to use so the algorithm that we want to use here is actually going to be to take the here is actually going to be to take the path path and we're going to want to split it on and we're going to want to split it on you know slashes you know slashes so what this will give us so what this will give us in the end is um you know we're going to in the end is um you know we're going to split the path whatever we have on split the path whatever we have on slashes so this is going to return to us slashes so this is going to return to us you know a list you know a list which is going to be you know which is going to be you know we could have like the single dot we we could have like the single dot we could have you know the double dot could have you know the double dot we could have you know the directory we could have you know the directory name name whatever it is and then okay what whatever it is and then okay what happens when we split on slashes and happens when we split on slashes and there's multiple slashes there's multiple slashes well what ends up happening is that you well what ends up happening is that you split them but since there's nothing split them but since there's nothing between them you actually get an empty between them you actually get an empty string string so that's going to be the only possible so that's going to be the only possible values we can get so what we want to do values we can get so what we want to do is actually work with a string builder is actually work with a string builder and what we're going to do is we want to and what we're going to do is we want to go from left to right of our you know go from left to right of our you know split items here split items here and we're going to maintain a stack and we're going to maintain a stack which is going to work as our string which is going to work as our string builder builder and what we're going to do is we're and what we're going to do is we're going to go through our you know going to go through our you know thing from left to right here so the thing from left to right here so the elements that we split elements that we split and okay remember that if we see a dot and okay remember that if we see a dot this represents the same directory so we this represents the same directory so we can actually ignore this because that can actually ignore this because that means that we'd be staying in the same means that we'd be staying in the same place we don't have to do anything place we don't have to do anything if we see a double dot remember that if we see a double dot remember that that means that you need to go that means that you need to go up one level up one level so that means that we're going to pop so that means that we're going to pop whatever's in the stack when we see like whatever's in the stack when we see like a double dot if and only if the stack is a double dot if and only if the stack is not empty right because if we try to not empty right because if we try to call stack.pop on a stack that's empty call stack.pop on a stack that's empty we're gonna have um you know an error be we're gonna have um you know an error be thrown so we can't do that so we're only thrown so we can't do that so we're only gonna pop if we see a double dot in the gonna pop if we see a double dot in the case that the stack here case that the stack here is you know non-empty is you know non-empty and you know if we see some sort of and you know if we see some sort of directory name you know it can be directory name you know it can be something like abc or it can just be something like abc or it can just be like root it doesn't matter it's just like root it doesn't matter it's just gonna be some you know value that isn't gonna be some you know value that isn't a dot double dot or not a um a dot double dot or not a um you know just an empty string so anytime you know just an empty string so anytime we see anything that's not one of those we see anything that's not one of those three then it's just a directory name in three then it's just a directory name in which case we're just gonna add it to which case we're just gonna add it to the um the um the stack here and then you know if we the stack here and then you know if we see an empty string we just continue so see an empty string we just continue so we don't have to do anything in that we don't have to do anything in that case case so pretty much that's what we want to do so pretty much that's what we want to do we just want to go through our path here we just want to go through our path here and again if we see a dot don't do and again if we see a dot don't do anything if we see a double dot pop from anything if we see a double dot pop from the stack if there's something to pop if the stack if there's something to pop if we see a directory name added in there we see a directory name added in there if we see an empty string don't do if we see an empty string don't do anything and at the end you know our anything and at the end you know our stack's gonna be full of like you know stack's gonna be full of like you know directory so this is gonna be you know directory so this is gonna be you know directory one it's gonna have like directory one it's gonna have like directory 2 directory 2 directory you know three blah blah blah directory you know three blah blah blah and remember that we just need to join and remember that we just need to join these directories together so these directories together so with like slashes right so it's gonna be with like slashes right so it's gonna be like dear one plus dear two plus like dear one plus dear two plus directory three and you know that's all directory three and you know that's all we need to do and remember that we need we need to do and remember that we need a leading slash so we're simply just a leading slash so we're simply just going to add you know going to add you know a leading slash to you know this a leading slash to you know this concatenated string here and this is concatenated string here and this is going to be our result so hopefully going to be our result so hopefully that's not too confusing if it is we're that's not too confusing if it is we're just gonna go into the editor now and just gonna go into the editor now and you're gonna see that it's gonna be you're gonna see that it's gonna be super clear this problem is really super clear this problem is really simple so once you see the code you'll simple so once you see the code you'll be like okay this is super simple i get be like okay this is super simple i get how to do it so i'll see you in the how to do it so i'll see you in the editor let's solve this problem okay editor let's solve this problem okay we're back in the editor now let's write we're back in the editor now let's write the code remember that we're going to the code remember that we're going to stack to basically store our path that stack to basically store our path that we've built so far so let's define that we've built so far so let's define that variable so we're going to say stack is variable so we're going to say stack is going to be equal to an empty list going to be equal to an empty list and and remember that we need to extract the remember that we need to extract the path items from our original string and path items from our original string and the way that we're going to do that is the way that we're going to do that is we're going to take the path that we're we're going to take the path that we're given and we're going to split on the given and we're going to split on the slash characters so let's do that so slash characters so let's do that so we're going to say path items is going we're going to say path items is going to equal to path dot split and we're to equal to path dot split and we're going to do that on you know a slash going to do that on you know a slash here here now we need to go through the path items now we need to go through the path items and basically check okay is it a dot is and basically check okay is it a dot is it a double dot is it you know a it a double dot is it you know a directory name or is it an empty string directory name or is it an empty string which is the case where you know we have which is the case where you know we have multiple slashes together multiple slashes together so what we want to do is iterate over so what we want to do is iterate over our items here so we're going to say for our items here so we're going to say for item in item in path uh items path uh items what we want to do what we want to do is okay we want to check the cases uh is okay we want to check the cases uh where we don't do anything so remember where we don't do anything so remember if item equals to a single dot or if item equals to a single dot or not item so if the item is an empty not item so if the item is an empty string which is the case where you know string which is the case where you know we had two or more you know slashes we had two or more you know slashes together so for example in this one together so for example in this one where it's like foo and then or sorry where it's like foo and then or sorry home two slashes and then foo home two slashes and then foo you know if you try to split uh on slash you know if you try to split uh on slash when there's two of them together like when there's two of them together like that you're going to get an empty string that you're going to get an empty string because technically there's nothing in because technically there's nothing in between them between them so in this case so in this case we just continue we actually don't do we just continue we actually don't do anything here anything here otherwise we could have potentially a otherwise we could have potentially a double dot so we're going to say l if double dot so we're going to say l if item item equals to oops equals to oops double dot then what we want to do is double dot then what we want to do is remember we want to pop remember we want to pop whatever is at the top of our stack and whatever is at the top of our stack and the reason we do this is because in you the reason we do this is because in you know unix systems two dots means you know unix systems two dots means you know go to the previous directory so know go to the previous directory so we want to pop from the stack but we want to pop from the stack but remember our stack needs to actually remember our stack needs to actually have an element in it for us to call pop have an element in it for us to call pop on it if we try to pop from an empty on it if we try to pop from an empty stack we're gonna you know blow up our stack we're gonna you know blow up our code uh and it wouldn't be correct so we code uh and it wouldn't be correct so we only want to pop when the stack actually only want to pop when the stack actually has at least one element so we're gonna has at least one element so we're gonna say if stack so basically if it has at say if stack so basically if it has at least one element we're gonna say stack least one element we're gonna say stack dot pop otherwise we don't do anything dot pop otherwise we don't do anything now the last case is that we have a now the last case is that we have a directory name because if you read the directory name because if you read the problem here you know the only thing problem here you know the only thing that can be in path is going to be a that can be in path is going to be a single dot slash single dot slash uh or you know double dots some sort of uh or you know double dots some sort of digits but these are all just you know digits but these are all just you know the directory name so we don't have to the directory name so we don't have to worry about it so the only thing left worry about it so the only thing left now is like a directory name so we can now is like a directory name so we can simply just append that to our stack so simply just append that to our stack so append append uh item right uh item right and at the end remember that we needed and at the end remember that we needed to join to join our stack together with slashes and we our stack together with slashes and we also needed to add that also needed to add that uh leading slash right all of the uh leading slash right all of the answers need a leading slash and joining answers need a leading slash and joining our elements will actually not put a our elements will actually not put a slash in the beginning it's gonna put a slash in the beginning it's gonna put a slash after each element but it won't slash after each element but it won't add one at the beginning of our string add one at the beginning of our string so we need to do that manually so we're so we need to do that manually so we're going to say oops we want to return you going to say oops we want to return you know a slash plus the concatenation know a slash plus the concatenation of of all the elements here with you know a um all the elements here with you know a um a slash in between them so we're simply a slash in between them so we're simply going to join our stack going to join our stack and we're going to simply submit this and we're going to simply submit this double check that it works double check that it works and it does cool and it does cool so what is the runtime complexity of our so what is the runtime complexity of our algorithm algorithm well in the worst case well in the worst case we are you know we are you know going to have to basically split our going to have to basically split our string here right so no matter what we string here right so no matter what we have to call this split so this is going have to call this split so this is going to be a big o of n operation and then we to be a big o of n operation and then we have to iterate all over all the splits have to iterate all over all the splits here here so what that means is it's going to be a so what that means is it's going to be a big o of n big o of n um time complexity because this is going um time complexity because this is going to be big o of n and then this entire to be big o of n and then this entire process is going to be big o of n so you process is going to be big o of n so you know our entire algorithm is big o of n know our entire algorithm is big o of n also the joining of the stack here is also the joining of the stack here is potentially a big o of n operation so potentially a big o of n operation so you know we've done three big o of n you know we've done three big o of n operations but they all happen you know operations but they all happen you know serially they're not nested so the serially they're not nested so the asymptotic runtime complexity is still asymptotic runtime complexity is still going to be big o of n going to be big o of n and space complexity wise it's also and space complexity wise it's also going to be big o of n going to be big o of n because you know we need to maintain because you know we need to maintain this stack which is going to be filled this stack which is going to be filled from elements in our path here and then from elements in our path here and then the path items um the length of this is the path items um the length of this is going to be dependent on you know the going to be dependent on you know the number of number of items in our path so in the worst case items in our path so in the worst case you know we can just have a lot of um you know we can just have a lot of um elements elements that we need to use but this is still that we need to use but this is still going to be constrained on path going to be constrained on path so our time complexity is going to be so our time complexity is going to be big o of n and our space complexity is big o of n and our space complexity is going to be big o of n so hopefully that going to be big o of n so hopefully that makes sense like i said this problem is makes sense like i said this problem is pretty simple uh even if you haven't pretty simple uh even if you haven't seen it before you can pretty easily seen it before you can pretty easily derive this one derive this one so hopefully this clears up any so hopefully this clears up any confusion if you needed to watch this confusion if you needed to watch this video to understand the solution or even video to understand the solution or even how to do the solution in the first how to do the solution in the first place um that being said place um that being said if you enjoyed this video please leave a if you enjoyed this video please leave a like comment subscribe let me know if like comment subscribe let me know if there's any questions that you'd like me there's any questions that you'd like me to do i'd be happy to make the videos to do i'd be happy to make the videos for you guys just let me know in the for you guys just let me know in the comment section below and i'll do my comment section below and i'll do my best for you guys so best for you guys so that being said happy coding and i'll that being said happy coding and i'll see you next time | 2024-03-20 11:25:45 | 71 | SIMPLIFY PATH | PYTHON | LEETCODE # 71 |
|
eg_FgZ9_3e4 | hello today we will be doing the problem number 1876 that is substring of problem number 1876 that is substring of size size three with distinct distinct characters three with distinct distinct characters so like to dislike youtube so we'll be so like to dislike youtube so we'll be doing it today doing it today the problem statement here is a string the problem statement here is a string is good is good if there are no repeated characters if there are no repeated characters given a string given a string s return the number of good substrings s return the number of good substrings of length 3 in of length 3 in s note that if there are multiple s note that if there are multiple occurrences of same substring occurrences of same substring every occurrence should be counted a every occurrence should be counted a substring is a contiguous sequence of substring is a contiguous sequence of characters in a string characters in a string so the input statement here given is so the input statement here given is x y z a and z so we will be taking x y z a and z so we will be taking three contiguous statements that is x three contiguous statements that is x y and z and we'll check if there are any y and z and we'll check if there are any repetitions of any characters let me repetitions of any characters let me just write this in a whiteboard x white just write this in a whiteboard x white that set xyz said he said sorry for the bad handwriting uh so first we will check we will be using the sliding window technique here to find the uh if there is any repetition characters in the substring so this uh total substring here is xyz that is that the substring size is one two three four five six so the substring size here will be five uh n minus one of course so first we will check in this sliding window xyz if it does have any repetition no so we'll t by one t by one so we'll be increasing the counter by so we'll be increasing the counter by one then we'll be checking one then we'll be checking through this sliding window and through this sliding window and the question here it is mentioned that the question here it is mentioned that uh the sliding video should be three let uh the sliding video should be three let me just show it me just show it yes return the number of good substrings yes return the number of good substrings of of length three in s so the sliding window length three in s so the sliding window given here is given here is three so we will first then three so we will first then we will check in y z z so we are seeing we will check in y z z so we are seeing that that here we have two occurrences of z so the here we have two occurrences of z so the count will still remain one count will still remain one then we'll be checking from z a then we'll be checking from z a will be incrementing the i and we'll be will be incrementing the i and we'll be checking the checking the third uh contiguous subsequent third uh contiguous subsequent contiguous substring contiguous substring so that's that a we have double z here so that's that a we have double z here so again we'll be so again we'll be skipping this part and we'll be checking skipping this part and we'll be checking from z from z a z which is our last configure string a z which is our last configure string that is that that is that is that and see we are getting here is that and see we are getting here the z twice so the count remains once the z twice so the count remains once and we'll be returning this and we'll be returning this one and one and let's see yes the output here is one let's see yes the output here is one so let's see the code let me just so let's see the code let me just enlarge it first we will check if the size is less than or equal to one uh if it is less than or equal to one will be returning zero and this here is the base case base case will be iterating from size uh from 0 to size minus 2 by size minus 2 since we'll be iterating from here which is this point the point this point is zero and will be iterating till here so as to avoid the index out of bonds let's check the a follow which is we will be iterating till n minus 2 then we'll be checking s of i is equals to s of i plus 1 or i plus 1 is equal to s of i plus 2 or i plus 2 is equals to s 5 let me just explain it here so s of s of i is x here and s of i plus sorry i plus 1 is z y here sorry and s off i plus 2 is z here so first we will be checking between i and i plus 1 if they are equal or not they are not equal then we will be checking if s of i plus 1 and i plus 2 is equal or not they are not equal and then at last we will be checking s of i plus 2 and s of i is equal or not which is not equal so we will be implementing the count to one let me take one more example of this the second iteration and let me just release this so this is uh released yes let me take the pen yes so the second subsequence will be y z and z here the eyes value is now one so we'll be taking the string y z and z s of i is what y s of i plus 1 is that and s of i plus 2 is that first we will be comparing i and i plus 1 y is not equal to z clear then we'll be comparing s of i plus 1 which is z and s of i plus two which is again said so this will just dominate and skip to the next iteration which will be two i shall move the iteration two and it will be going till n minus two times and we'll be here taking a result variable for the counter and yeah that's it we are done with the code so let's just submit it the font size yes so it is getting accepted and 0ms which is 100 percent faster that's it so hope you guys uh learned something new today thank you | 2024-03-25 11:42:47 | 1,876 | Substrings of size three with distinct Characters | Leetcode 1876 |CP |
|
ORLBbFd5U_A | Hello friends today I'm going to solve with problem number 93 restore IP with problem number 93 restore IP addresses so in this problem we need to addresses so in this problem we need to construct a valid IP address from a construct a valid IP address from a given string s so what's a valid IP given string s so what's a valid IP address uh it consists of four integers address uh it consists of four integers which are separated by single dots and which are separated by single dots and each integer can be between 0 to 255 each integer can be between 0 to 255 inclusive and cannot have any leading inclusive and cannot have any leading zeros for example this is a valid IP zeros for example this is a valid IP address because address because none of them have any leading zero none of them have any leading zero however this has a leading zero so it's however this has a leading zero so it's not a valid IP address this is also a not a valid IP address this is also a valid IP address however this is not a valid IP address however this is not a valid IP address because it has value valid IP address because it has value greater than 255 and in this case it has greater than 255 and in this case it has an an um a symbol which is other than an um a symbol which is other than an integer and a DOT value so it can only integer and a DOT value so it can only have a DOT value which separates have a DOT value which separates integers which are between between 0 and integers which are between between 0 and 255 and each integer there are four 255 and each integer there are four integers in total so now given the integers in total so now given the string as we need to construct a valid string as we need to construct a valid IP address and we are going to construct IP address and we are going to construct like return as many valid IP addresses like return as many valid IP addresses that are possible to be reconstructed that are possible to be reconstructed from the given strings so we are given from the given strings so we are given this example let's see how we could this example let's see how we could solve this problem so from this example let's see what are the valid IP addresses that we could get from this example so first of all let's check the length of the IP at of this string as so for an IP address what do we need is four integers separated by dot right for integers and Dot so what would the minimum length of an IP address be the minimum length would be if each IP address has integer of only length 1 and each are separated by a DOT so this is of length one of length one length one and separated by dot so if we are constructing this IP address from a string then what is the length of the string if string only has integer values and we are actually inserting dots in it so basically length would be 1 2 3 and 4. so the minimum length of the string should be four what about the maximum length so each IP address can have values from 0 to 255 right and 255 means if each integer is offline 255 then it's of length 3. and since we have four such integers so the maximum length is 3 times 4 which is equals to 2 valve so the length of the string should be between 4 and 12. so this will be our base condition if the length is less than 4 or greater than 12 then we cannot construct a valid IP address from our string so this is one base condition that we found now let's see how we are going to solve the problem so let's look at the length is it valid so we have three plus three six plus three nine plus two which is equals to 11. so since the length is equals to 11 so it falls up in within the range right and then so we move on to the next step that is to construct an um to construct a valid IP address so how could we construct a valid IP address um well one way is to start as a um start from the first digit so what are we going to do is we look at the very first digit here so the first is it is to and we try to add a DOT after that uh just that the first integer is of single digit the next integer is 5 and then we put a dot again the next integer is five we add five and we put a dot again and the remaining integer since there will there must only be four integers so this the remaining uh value should be the fourth integer right but is the land between the range the given range the valid range well it is not it's greater than that right so we cannot form our IP address uh uh with this uh in this way like by only taking one integers at a time so what we do is now we actually backtrack so we backtrack from this section from here and what where we reach is 2 5 dot so foreign so now we have raised this step and what we do is now we check uh if we can take these two integers together as our third integer so we take these two and then we add a DOT and then we look at the remaining integer and it's still great so we again backtrack and then we take these three as our third integer and now if we take these three the value is greater than our given range so again we backtrack now we are backtracking since the length is greater than 3 so we are backtracking from where we are backtracking from this position to this position now here so since we backtrack we have we reach where the value only with only first integer and then now we take two integers between 55 and then we take the second integer and then the remaining is again greater so we keep on doing unless and until we take like 25 and then 52 and then 5 55 and then again this whole big integer so we again backtrack and then our 25 and then we take 52 and 551 it's again greater than that so we backtrack we take this three it's greater than 255 so we're working backtrack and we take these three integers and then what we do is we look we again keep on like taking only individual integers unless we get this whole big in number with backtrack there we take these two values and then again these values still greater so we backtrack now we take these three values but now these three values greater than so we take we backtrack to this point and then we take these two values and then we again take a single value and we still have this whole big number so we backtrack and we take two values and this is still greater so we backtrack and we take three values two digits and now when we take three digits it's greater than 255 right so we again backtrack from there and we take these three values and then in that way we end up with our valid integers that would be uh one would be this value and this value the other would be these three digits and the last two digits so now that we understand how we could solve this problem let's uh start coding so what we need is um let N close to the length of the string and then we need our result array to and then we need our result array to store our result store our result and we are going to create our DFS and we are going to create our DFS function since okay let me not function since okay let me not let me Define these at back tracking let me Define these at back tracking back tracking function back tracking function which text value so what are the values which text value so what are the values it would require well we basically need it would require well we basically need to keep track of where we are like to keep track of where we are like um um in the string so we need the index of in the string so we need the index of the string indexing this string and then the string indexing this string and then we also need we also need to keep our IP address right keep track to keep our IP address right keep track of the IP that we are forming and we of the IP that we are forming and we also need to keep track if we are at we also need to keep track if we are at we already have four uh digits if we have already have four uh digits if we have like not four digits but four integers like not four digits but four integers if we have already formed four integers if we have already formed four integers or not so we'll keep track of the count or not so we'll keep track of the count of the integers of the integers and let me just create our calling and let me just create our calling function so we are going to pass zero and the IP address would be um an empty string initially and the count would be equals to four because there should be four integers and we are going to return our result now here [Music] um in the back tracking function we check the base case okay we actually check the base case here so if the length and is less than four or n is greater than 12 which means that the range it would be between 4 and 12 right if it is greater uh it doesn't fall in that range then we are going to return an empty array because that that is the case where we cannot form a valid um valid IP address all right now once we have reached our function so in the function what's the case when we are going to push uh the IP address to our result well it's the it's rain um we have found all of our four integers and uh this the length of this string is uh equals to zero so is equals to zero because we will be slicing our um string to form our IP address so see both of them should be equals to zero then we are going to push to our result array push our IP address and if in case the length is not equals to zero which means that it would be the condition where we have 2 2 5 and then which means we have two five five and the remaining integer values is this much and this integer value is uh basically we can only take maximum of three right and the remaining would be this value and since the length is not equals to zero however we already found our four integers uh that's not a valid case so in that case also if C is equals now what we'll do is we will Loop over now what we'll do is we will Loop over um um the value of our Loop over this string the value of our Loop over this string starting from its first starting from its first index in isopylis then the length of the index in isopylis then the length of the string at plus plus so what are we doing string at plus plus so what are we doing here is we are actually doing the here is we are actually doing the iteration so let's just see so one of iteration so let's just see so one of the strings that we formed was a valid the strings that we formed was a valid IP was this one right the another is IP was this one right the another is valid IPA we could form is these three valid IPA we could form is these three values these three these three digits values these three these three digits and and these three and this the last two right these three and this the last two right so how we're going to form that well so how we're going to form that well basically basically uh in the substring uh in the substring uh so this would be our substring so we uh so this would be our substring so we choose choose these uh only length of one only first these uh only length of one only first fact is it in the next case what are we fact is it in the next case what are we going to do is we are going to choose going to do is we are going to choose these two slice the first two digits and these two slice the first two digits and then similarly slice the next uh then similarly slice the next uh slice one plus so slice one plus so so that we form our IP address so that so that we form our IP address so that is what uh we'll be doing so we are is what uh we'll be doing so we are going to create a sub IP going to create a sub IP equals to equals to slice slice um um from index 0 to the index I plus one from index 0 to the index I plus one and and value of the sub IP the sub IP address value of the sub IP the sub IP address should be in the range should be less should be in the range should be less than and it should not have any leading zeros so we are going to check if the sub IP the first value is equals to zero then we are going to return um call our backtracking backtracking function with index I plus 1 and our sub IP address being uh increased being appended by our sub IP so we append our sub IP but we are going to paint based on where we find the sub IP if this sub IP is the very last integer then we do not need to add the value C so if the value of C is equals to zero then we are just going to append it actually if it's the very first I very actually if it's the very first I very first uh integer in this in our IP first uh integer in this in our IP address so we are just going to append address so we are just going to append it without any leading dot else we are it without any leading dot else we are going to add a DOT going to add a DOT before the sub IP and then C minus one now um talking about the sub IP comparison with this value so since sub IP is a string we need to convert it into an integer so we are going to pass it through integer values and and this would not be an and operated this would be an or operation and we are going to also check if the sub IP length so so by length is greater than one so so by length is greater than one and the first uh element first digit in and the first uh element first digit in the integer is equals to zero that is the integer is equals to zero that is when we return when we return also we need to check if the length of I also we need to check if the length of I I is greater than I is greater than the length of the string if that is the length of the string if that is greater than length of the string that greater than length of the string that we need to return back because we need to return back because um it could be the case that the length um it could be the case that the length of string is only one and of string is only one and and basically it will only run over the and basically it will only run over the value of 4. now let's try to run our value of 4. now let's try to run our code and let's see what the result is code and let's see what the result is okay something went wrong all right so these are the final changes that I made to my code now let's try to great | 2024-03-20 13:18:59 | 93 | 93. Restore IP Addresses | JavaScript | BackTracking | LeetCode Daily Challenge |
|
xfPyRVGmUy0 | hello friends today let's of the surrounding regions probably given a 2d surrounding regions probably given a 2d bode contain the X and O the letter or bode contain the X and O the letter or capture all regions surrounded by X a capture all regions surrounded by X a region is captured by sleeping on earth region is captured by sleeping on earth into X in that surrounded region less is into X in that surrounded region less is this example we sleep these Rios but we this example we sleep these Rios but we do not sleep this or why because the do not sleep this or why because the surrounding region should shouldn't be surrounding region should shouldn't be on the border that means ending all in on the border that means ending all in this folder we will not flip it so let's this folder we will not flip it so let's think think if there is no these restorations we can if there is no these restorations we can just do a simple DFS or PFS or a unified just do a simple DFS or PFS or a unified or just iterate this border and when we or just iterate this border and when we find oh we will do DFS to find the find oh we will do DFS to find the author also contact connected to this author also contact connected to this all in a flip data to the X right and all in a flip data to the X right and mockito as VT but the TIF the only mockito as VT but the TIF the only difference is that if this all can difference is that if this all can connected to all on the board we will connected to all on the board we will not flip all these O's so how to solve not flip all these O's so how to solve that I think there we can just start that I think there we can just start from these four borders we check this from these four borders we check this for border if there is a all we will do for border if there is a all we will do a DFS to mark all this chart owed to the a DFS to mark all this chart owed to the victim and all the O's connected to this victim and all the O's connected to this all will also be marked admitted then we all will also be marked admitted then we just do a single iteration on the inner just do a single iteration on the inner region like we start from here and the region like we start from here and the as it oh and we have an ability the as it oh and we have an ability the before we just mark it at X and there we before we just mark it at X and there we do the FS that you mark all these also do the FS that you mark all these also chooser X so let's see these algorithms chooser X so let's see these algorithms first we check the bode are actually first we check the bode are actually is a powder if the Buddha IJ coccioli is a powder if the Buddha IJ coccioli mock although connected to this or to mock although connected to this or to Vegeta and here we do a depth first Vegeta and here we do a depth first search and now certain establish search and now certain establish iterator from the Row one to row and iterator from the Row one to row and minus one from column one who callin a minus one from column one who callin a minus one if both IJ go to this all and minus one if both IJ go to this all and we have the video before that means it we have the video before that means it doesn't technically the chili powder doesn't technically the chili powder will flip the old to the X and also we will flip the old to the X and also we do a depth first search here so you see do a depth first search here so you see this example we first checked the full this example we first checked the full powder and there we find that here is powder and there we find that here is all we mark it and eat it and there all we mark it and eat it and there unfortunately there are no oh connected unfortunately there are no oh connected to this all so we just a magazine Oh to to this all so we just a magazine Oh to the video then we iterate their inner the video then we iterate their inner region and both a 1 1 equal to O we flip region and both a 1 1 equal to O we flip either to X and we keep find on video either to X and we keep find on video connected to this all and we mark will connected to this all and we mark will flip all these oz to the X so this flip all these oz to the X so this example and the extra weekend combines example and the extra weekend combines into their first search just use one into their first search just use one function that is the boat and the function that is the boat and the current row count current color and the current row count current color and the video array and also use a boolean video array and also use a boolean variable flip to mark whether we need variable flip to mark whether we need that you flip the current Oh if the flip that you flip the current Oh if the flip is true when we meet all we change it to is true when we meet all we change it to true X and Mark littell visitor which true X and Mark littell visitor which means we are in there in the region means we are in there in the region otherwise just mark it a date that means otherwise just mark it a date that means we are on the border so ok let's write we are on the border so ok let's write the code now we first do educate Shack the code now we first do educate Shack if boat or yacht you know or for the if boat or yacht you know or for the door lens you go to 0 we return door lens you go to 0 we return otherwise we kept the rows equal to both otherwise we kept the rows equal to both the lens colors equal to both zero the lens colors equal to both zero dollars and we use a visitor there will dollars and we use a visitor there will be food in rows be food in rows Collins Collins then we first checked the folk folder we then we first checked the folk folder we first checked the first and the last row first checked the first and the last row so there will be J less then called a : so there will be J less then called a : j plus plus so if the boulder 0j e kochu j plus plus so if the boulder 0j e kochu oh we do that for such we pass both oh we do that for such we pass both current row index is zero and current current row index is zero and current calling that J and the past is visit and calling that J and the past is visit and the currently we do not need to flip so the currently we do not need to flip so it has a force and if the error will be it has a force and if the error will be the last row there will be rows minus 1 the last row there will be rows minus 1 j e ho - OH j e ho - OH with also do a depth first search both with also do a depth first search both rows minus 1 there will be J we did rows minus 1 there will be J we did force okay then there will be the force okay then there will be the leftmost color in the rightmost color so leftmost color in the rightmost color so I call to zero unless then the rows I I call to zero unless then the rows I plus plus so if both there will be i0 plus plus so if both there will be i0 the leftmost column you got you oh we do the leftmost column you got you oh we do their first search there will be both their first search there will be both there will be I 0 and the revealed sedum there will be I 0 and the revealed sedum there will be a force okay then for the there will be a force okay then for the rightmost : there will be Colin's minus rightmost : there will be Colin's minus 1 equal to oh we do therefore search 1 equal to oh we do therefore search fold there will be I Collins minus 1 fold there will be I Collins minus 1 related and the force finally we do we related and the force finally we do we iterated there in the region so I will iterated there in the region so I will start from 1 I less than rows minus 1 I start from 1 I less than rows minus 1 I plus plus and there jo21 jealous and plus plus and there jo21 jealous and collins minus 1 j plus plus if the collins minus 1 j plus plus if the forward i j equal to or and we haven't forward i j equal to or and we haven't read here before the I J we do DFS enter read here before the I J we do DFS enter Oh Oh i jz it's it this time we mark it at you i jz it's it this time we mark it at you because we need to flip it so now let's because we need to flip it so now let's implement this avoided DFS there will be implement this avoided DFS there will be charged boat intro in the current korean charged boat intro in the current korean VHC them and there will be food yet VHC them and there will be food yet sleep we first check if the index is sleep we first check if the index is valid if Rho less than 0 or : less than valid if Rho less than 0 or : less than 0 or Rho great them powder tolerance 0 or Rho great them powder tolerance minus 1 or : course import $0 minus 1 we minus 1 or : course import $0 minus 1 we return if we visited before we return if return if we visited before we return if the board row : equal to X we return the board row : equal to X we return otherwise we check if the flip equal to otherwise we check if the flip equal to true we need to flip the current or to true we need to flip the current or to the X otherwise we just mark it to visit the X otherwise we just mark it to visit it so there will be true then we do the it so there will be true then we do the four directions def for such there will four directions def for such there will be Rho plus one called eat it and flip be Rho plus one called eat it and flip the FS board Rho minus one called bility the FS board Rho minus one called bility to flip and the FS food row column plus to flip and the FS food row column plus 1 DT to flip then would row : 1 DT to flip then would row : - what they did sleep okay sorry - what they did sleep okay sorry yeah singer finish it ah yeah this is a yeah singer finish it ah yeah this is a typo okay thank you for what you see you typo okay thank you for what you see you next time | 2024-03-21 11:41:43 | 130 | LeetCode 130. Surrounded Regions Explained with Examples and Solution |
|
OLHFYGp2bvg | hi everyone I'm Dr surjit Singh today we'll talk about the lead code problem coin change let us begin we are given a list of coin denominations and a Target amount we are to find the fewest number of coins that will make up the amount bottom up solution of the problem is iterative we are given a list of coin denominations we will use the minimum number of these coins to make up the given amount in the bottom up dynamic programming we will find the solutions for all the amounts from 0 to 11 we Define an array named DP to record the number of coins requ required for each amount to begin with we assume that for every amount we require infinite number of coins we do not need any coin for amount zero so we assign Zer to DP 0 we Loop over all the coin denominations first one is a $2 coin denomination let us see how many solutions are possible with this a takes all values up to the Target amount however as the $2 coins cannot generate amounts less than two we start with a equal to 2 and not with zero as we select $1 two coin amount increases from 0 to two it means that adding one coin to the empty bin gives us an amount of $2 so we replace our solution for or amount two with one coin it means that just one coin is enough to get the amount equal to $2 next value of a is three present solution for an amount of $3 requires infinite coins we can get three by adding a $2 coin to amount equal to 1 however AAL to 1 itself needs infinite number of coins so there is no use adding another coin to it we leave the result for three unchanged and we move to a equal to 4 we can get four by adding a $2 coin to amount equal to two our DP table tells us that amount two needs one coin so four needs two coins which is much less than the earlier requirement of infinite coins so we replace it with two we can get amount five by adding a $2 coin to a equal to three however both of them require infinite coins so there's no change in the result we can easily deduce that odd amounts cannot be produced with $2 coins further we can easily check that to produce amounts 68 and $10 we require three four and five coins at the end of the inner for Loop we get these DP entries we obtain all these by using $2 coins now let us see the refinements in the solutions by including coins of $3 denominations minimum amount that this can generate is dollar three if we add a $3 coin to empty bin we get a equal to 3 with just one coin this is less than infinite coins needed in the existing solution so we replace it with one for amount four we must look for previous result for a equal to 1 but for amount one we need infinite coins so the present result for a equal to 4 that requires two coins is good enough for us we do not change it we can get amount five by adding a $3 coin to a equal to 2 we get amount two with one coin so we can get a equal 5 with two coins and therefore we replace dp5 with two existing solution says that we can get amount six with three coins let us see if we can improve upon it for amount three we need one one coin if we add a $3 coin to it we get $6 with just two coins so we reduce dp6 from 3 to two we can get an amount of $7 by adding a $3 coin to $4 DP table tells us that we get $4 with two coins so we need three coins for making $7 that we now record in DP table amount 8 is achieved by adding a $3 coin to a equal to 5 so we don't need four coins for eight we can make it with three coins remember that our aim is to reduce the number of coins for amount nine we need just three coins as seven is possible with three coins 10 is possible with four coins and 11 also with four coins we will now further revise the counts using $ do coins we start with a equal to 5 amount five is now possible with just one coin and we replace the old count for five with one coin AAL to 1 requires infinite coins so there is no improvement for the amount six AAL 2 requires one coin so amount 7 is possible with two two coins eight Now does not require three but two coins coins for nine however remain three five is possible with one coin so 10 is possible with just two coins a equal to 6 is possible with two coins so 11 is possible with three coins with this both the for Loops end keeping a record of previous Optimal Solutions in DP helps Us in making immediate decision for every amount without trying all combinations and their subc combinations for the final amount we now have the best solution for every amount up to 11 we may notice that the amount of $1 is not possible with the coins available to us we return three as the optimal solution that involves minimum number of coins for amount 11 in case the desired amount needs infinite coins we return minus1 as the answer let us assume that n is the length of the coins list total iterations in the two for Loops are n times the target amount a Time complexity is therefore n * a space complexity is the size of the DP array that is equal to the required amount thank you for your time I hope you like the video please stay tuned for videos | 2024-03-24 10:30:01 | 322 | Coin Change | Leetcode #322 |
|
YdaG_03fQ6E | hi there so today I'm looking at a little bit manipulation question which little bit manipulation question which is 371 sum of two integers we need to is 371 sum of two integers we need to calculate the sum of two integers a and calculate the sum of two integers a and B but we are not allowed to use the B but we are not allowed to use the addition and the subtraction operator so addition and the subtraction operator so we have to look into the binary we have to look into the binary representations for those integers and representations for those integers and see what's actually kind of happening in see what's actually kind of happening in the binary level when we do the addition the binary level when we do the addition so let's just take the very first so let's just take the very first example we have 1 & 2 so add those two example we have 1 & 2 so add those two together for simplicity simplicity together for simplicity simplicity purpose we're looking at four bit purpose we're looking at four bit unsigned integers we have four positions unsigned integers we have four positions one is 0 0 0 1 2 is 0 0 1 0 and the one is 0 0 0 1 2 is 0 0 1 0 and the result is 3 which is 0 0 1 1 basically result is 3 which is 0 0 1 1 basically this this result is the one can obtain this this result is the one can obtain this by doing an exclusive all rip this by doing an exclusive all rip between 1 & 2 and then looking at some between 1 & 2 and then looking at some other examples for simplicity we're other examples for simplicity we're looking at something simple again 1 plus looking at something simple again 1 plus 1 notice that the 1 & 2 there are no 1 notice that the 1 & 2 there are no there is no carry about the you know the there is no carry about the you know the digits that you need to do so so let's digits that you need to do so so let's just look at 1 plus 1 which deliberately just look at 1 plus 1 which deliberately force us to looking at the carry overs force us to looking at the carry overs so 1 plus 1 the result it's 2 and the so 1 plus 1 the result it's 2 and the binary is 0 0 1 0 so we can see we find binary is 0 0 1 0 so we can see we find those numbers have a 1 bit in the ones those numbers have a 1 bit in the ones position so that suggests that we have position so that suggests that we have to carry over that to the per tooth to carry over that to the per tooth position so we can do an end operator position so we can do an end operator between this 2 number to find the between this 2 number to find the position we need to do do the carry over position we need to do do the carry over and the to carried over to the next and the to carried over to the next position it's done by doing a left shift position it's done by doing a left shift so so this is how we obtain this so so so this is how we obtain this so let's look at a let's look at a some example that will actually involve some example that will actually involve both of this step to do this calculation both of this step to do this calculation by doing bit manipulation so simplest by doing bit manipulation so simplest example is just 1 plus 3 we get a 1 a 0 example is just 1 plus 3 we get a 1 a 0 0 0 1 3 is 0 0 1 so we do so we take a 0 0 1 3 is 0 0 1 so we do so we take a take a look at the exclusive all which take a look at the exclusive all which is 0 0 1 0 and the carry is going to be is 0 0 1 0 and the carry is going to be doing an operator we have the 1 bit to doing an operator we have the 1 bit to the ones position from post number so the ones position from post number so similar to here we do an end operator to similar to here we do an end operator to extract that and shift towards left extract that and shift towards left which is 0 0 1 0 so that's shifted their which is 0 0 1 0 so that's shifted their version of the end so the question version of the end so the question essentially becomes 2 + 2 we just essentially becomes 2 + 2 we just continue this procedure so look at the continue this procedure so look at the exclusive all and the shifted version of exclusive all and the shifted version of the end operation the exclusive all here the end operation the exclusive all here is obviously 0 because the number 2 is obviously 0 because the number 2 numbers are the same so it's 0 the we numbers are the same so it's 0 the we shift of the shift of the end it will be shift of the shift of the end it will be 4 so we translates this summation 4 so we translates this summation question into basically we decompose the question into basically we decompose the the summation into a series of exclusive the summation into a series of exclusive all and shifted the end operation the all and shifted the end operation the exclusive is that for that digits we exclusive is that for that digits we don't have overflow we don't need to do don't have overflow we don't need to do the carry and the end operation is the carry and the end operation is basically to extract the bit positions basically to extract the bit positions where we do have a / follow we need to where we do have a / follow we need to deal with and the shift to left by 1 is deal with and the shift to left by 1 is 2 2 you know get the carry in their right you know get the carry in their right position then we just resume to this position then we just resume to this calculation until one of the result from calculation until one of the result from either exclusive or the shifted version either exclusive or the shifted version of the end becomes zero then we just add of the end becomes zero then we just add those one one last time doing exclusive those one one last time doing exclusive all between those two numbers one last all between those two numbers one last time we can get the final result which time we can get the final result which is four and that's what we be looking is four and that's what we be looking for for so right now using the positive in the so right now using the positive in the lumbers it's all looking fine lumbers it's all looking fine the the problem here is just that the the the problem here is just that the actually have negative numbers so that's actually have negative numbers so that's a little bit funky let's grab a binary a little bit funky let's grab a binary for negative two and we know that when for negative two and we know that when we actually shifted the negative number we actually shifted the negative number towards left at least in the signed towards left at least in the signed version that's undefined it's a version that's undefined it's a problematic usually a the workaround is problematic usually a the workaround is to convert that into a no sign but the to convert that into a no sign but the thing that I want to do before actually thing that I want to do before actually just do the conversion is to just verify just do the conversion is to just verify it's just a sort of simple example that actually okay to convert into unsigned because when we convert to unsigned and do the left shift the sign bit it's it's basically going to be truncated so we need to I guess at least to do some verification that this truncation would would would be okay so looking at negative two plus three so we definitely have a flip of the sign bit three is so we do the exclusive all it will so we do the exclusive all it will become 1 1 1 and the end coming over is become 1 1 1 and the end coming over is going to be a 1 0 0 so then I continue going to be a 1 0 0 so then I continue doing this procedure we do exclusive all doing this procedure we do exclusive all 1 0 0 1 the end operation shipped over 1 0 0 1 the end operation shipped over its a 1 0 0 0 and then we do the just its a 1 0 0 0 and then we do the just continue doing this exclusive all we get continue doing this exclusive all we get a very get a single one at the very end a very get a single one at the very end and when we do the end operation we get and when we do the end operation we get 1 in the sign bit and when we shifted 1 in the sign bit and when we shifted that over by left by one we need to that over by left by one we need to truncate that out and we have the 0 0 0 truncate that out and we have the 0 0 0 0 so the result is 0 0 0 la so so if we 0 so the result is 0 0 0 la so so if we use the unsigned version left to left to use the unsigned version left to left to shift it just discard the one that's shift it just discard the one that's being shifted towards left and the being shifted towards left and the result is actually ok so just a quick result is actually ok so just a quick not proof but verifying that it's okay not proof but verifying that it's okay to to use end operation and let the to to use end operation and let the shipped by one you know casting that shipped by one you know casting that into unsigned to utilize this procedure into unsigned to utilize this procedure to solve the summation of between to solve the summation of between negative numbers and positive numbers negative numbers and positive numbers another verification I think I should do another verification I think I should do is to check out the other kind of is to check out the other kind of extreme we have two negative numbers extreme we have two negative numbers that's adding together so so so the the the case that we should consider is that if we have something like negative seven negative four which are you know sort of like you know it's it's it's only a larger side in an active regime and when we do the you know negative eight and negative seven when we follow that procedure we will get a whomp it in the end when we do the exclusive all the end operation and the shifted out towards left if we disregard that we're gonna have just a one and that might be problematic but I guess you can argue negative eight and negative seven you we wouldn't really expect it to to have those two numbers as input if we're looking at the 4-bit signed integers because those two when we add two together it's gonna overflow so but but but following this procedure we pretty much gonna return positive one so you know so you might be problematic maybe we should just testing should test the two negative numbers has to be less than half of the maximum possible like like less than or equal to otherwise we would just throw out some arrow I guess but if we just following this procedure for for this negative eight and negative seven cases it's going to be automatic but nothing in the code nothing in the procedure will actually handle that yes so that's potentially some some problematic Singh yeah so so let's say let's just code this cook this solution up I'm actually interested as to see what it sees if I put the inter minimum there okay so we have something like the exclusive all let's just call this diff and another another variable for the carry so the logic has just while the one of those is not zero we can just have a Charlie chose B actually because when we should choose B because we should just a carry thing and we should choose the carrier while the carry is not zero and we're gonna basically assign a to the diff to a procedure so that when we determine procedure so that when we determine whether we are terminate or not we just whether we are terminate or not we just check whether B is nonzero check whether B is nonzero what whether B is there when B is there what whether B is there when B is there or the a must have the also that we want or the a must have the also that we want so just going to do the death which is so just going to do the death which is the exclusive or between this two number and the carry is going to be by casting by custody the end operation into a sign unsigned integer and then after that was shifted to the left by one and obviously we casted that back to integer so we basically truncate out the the one I guess if if we cast this 232 unsigned 32 integer when we do the leftist shifter you will already be to do the truncation so when we convert that back it's the truncation up and actually happens in the lattice shift and then we're just gonna assign those things back to a and B in the end we shall return a that's the sum of those two numbers so we just brought some examples yeah this is a hard coding example that I put there let me actually try something that's larger oh no it's so it's not for bit so how big is to new to the oh no sorry so one to the Saudi one okay oh no sorry so one to the Saudi one okay I'm stupid this number so I'm just gonna throw this maybe a little bit smaller copy this it's actually working it's actually working [Music] anyway it's a it's definitely overflow anyway it's a it's definitely overflow there and actually accept overflow ulcer there and actually accept overflow ulcer so if we're looking at negative 7 and so if we're looking at negative 7 and negative 7 when we do in the 4-bit negative 7 when we do in the 4-bit version which we when we do the end version which we when we do the end operation and the shifted towards left operation and the shifted towards left and disregard the the 1 carry we get one and disregard the the 1 carry we get one plus one and we actually result in some plus one and we actually result in some positive number which it doesn't make positive number which it doesn't make sense but yeah this actually where is my sense but yeah this actually where is my console there's actually but that's just console there's actually but that's just how I think in the in the back end of how I think in the in the back end of their judge system it's actually doing their judge system it's actually doing this similar to this so yeah I would I this similar to this so yeah I would I would think that they will actually sell would think that they will actually sell some arrows but but apparently it's not some arrows but but apparently it's not anyway so that's the question yeah just doing exclusive all to add those that don't need to add those bit positions where you don't need to worry about the carry and using an operator to find that the little the position where you want to do the carry to put the carries on to the right position we left the shifter that were slapped by wand and to deal with the case that when we actually got shifted the negative numbers we recast that into unassigned and yeah this have undesired properties so I guess whether it's on a sign or signed better not to do the left shift so yeah that's pretty much it the question for today | 2024-03-24 11:33:56 | 371 | Leetcode 371 Sum of Two Integers |
|
h44am-dWvO0 | hey everyone welcome back to my channel before we get started don't forget to before we get started don't forget to click the Subscribe button if you want click the Subscribe button if you want more videos about coding interviews so more videos about coding interviews so in this video we'll be solving the in this video we'll be solving the problem lead called reverse string so problem lead called reverse string so let's get started the problem is that let's get started the problem is that they give us a string as an array of they give us a string as an array of characters and the task here is to characters and the task here is to reverse this input array of character in reverse this input array of character in place so for example if we have this place so for example if we have this input array of characters the results input array of characters the results should start with the last character and should start with the last character and so on and what we mean by in place is so on and what we mean by in place is that we must reverse the characters and that we must reverse the characters and the array without using auxiliary data the array without using auxiliary data structures or we can say and constant structures or we can say and constant space memory but in this video I will space memory but in this video I will show you multiple way to solve it using show you multiple way to solve it using the stack data structure and also the stack data structure and also without using it so let's start by the without using it so let's start by the first solution let's say we have this first solution let's say we have this input array of characters the first way input array of characters the first way to solve this problem is by using a data to solve this problem is by using a data structure which called a stack and as we structure which called a stack and as we know the stack their structure is know the stack their structure is something called less and first out or something called less and first out or we can say levo so the first thing we we can say levo so the first thing we will do is iterate throughout the array will do is iterate throughout the array of characters and at each iteration of characters and at each iteration we're gonna add characters to the stack we're gonna add characters to the stack so once we add them all to the stack so once we add them all to the stack we're going to implement the lifo we're going to implement the lifo technique and we're gonna start popping technique and we're gonna start popping from the stack and add to the output from the stack and add to the output array so the time complexity for this array so the time complexity for this solution is often where n is the number solution is often where n is the number of character and the inputs array and of character and the inputs array and the space complexity is often because we the space complexity is often because we are using auxiliary data structure the are using auxiliary data structure the stack list to store the characters and stack list to store the characters and the input string so the second way to the input string so the second way to solve this problem and the best way and solve this problem and the best way and the easy way to solve 90 percent of the easy way to solve 90 percent of array problems is by using the two array problems is by using the two pointers technique and the two pointers pointers technique and the two pointers technique is an algorithm that involves technique is an algorithm that involves iterating over an array with two iterating over an array with two pointers at the same time so the basic pointers at the same time so the basic idea is to have one pointer that starts idea is to have one pointer that starts at the beginning of the array and at the beginning of the array and another pointer that starts at the end another pointer that starts at the end of the array and we're gonna use those of the array and we're gonna use those two pointer to swap the elements pointed two pointer to swap the elements pointed to the start pointer and the last to the start pointer and the last pointer and after that we move the star pointer and after that we move the star pointer to the next character and the pointer to the next character and the last pointer to the previous character last pointer to the previous character so until the start is equal to the end so until the start is equal to the end pointer or the star is bigger than the pointer or the star is bigger than the end pointer and that's how we're gonna end pointer and that's how we're gonna reverse the array of character and place reverse the array of character and place by using the two pointers technique so by using the two pointers technique so the time complexity for the solution is the time complexity for the solution is often where n is the number of character often where n is the number of character and the input array and the space and the input array and the space complexity is all fun because we are not complexity is all fun because we are not using any accelerate data structure to using any accelerate data structure to store the result that's it guys so let's store the result that's it guys so let's jump at code in the solution so the jump at code in the solution so the first solution is by using the stack first solution is by using the stack data structure so I start by data structure so I start by initializing a stack and we iterate initializing a stack and we iterate throughout the input string at each time throughout the input string at each time we append or we add the character to the we append or we add the character to the stack list so after that we set another stack list so after that we set another loop that iterate throughout the input loop that iterate throughout the input string and each time we pop from the string and each time we pop from the stack the character and we assign it to stack the character and we assign it to the current index of the input string the current index of the input string the second way to solve this problem is the second way to solve this problem is by using the two pointers technique so by using the two pointers technique so we'll start by initializing two punchers we'll start by initializing two punchers start at the beginning of the array and start at the beginning of the array and the end pointer at the end of the array the end pointer at the end of the array then we set a while loop that iterate then we set a while loop that iterate well the start is less than the end so well the start is less than the end so inside the loop we call the function inside the loop we call the function swap to swap the character at the start swap to swap the character at the start and the end pointers and after Double and the end pointers and after Double increments start monitor by 1 and we increments start monitor by 1 and we decrement the end pointer by one so decrement the end pointer by one so let's define our swap function so the let's define our swap function so the swap function take three argument the swap function take three argument the start pointer and the end pointer and start pointer and the end pointer and the array of characters so the function the array of characters so the function swapped the character at I index and G swapped the character at I index and G index and we don't return anything index and we don't return anything because we are modifying the input because we are modifying the input string in place so at the end we'll have string in place so at the end we'll have an output array reverse and place or we an output array reverse and place or we can write it in one line by using a can write it in one line by using a method in Python called reverse which is method in Python called reverse which is an in place method that reverse the an in place method that reverse the order of elements an array and have a order of elements an array and have a Time complexity of often and space Time complexity of often and space complexity of off one because it does complexity of off one because it does not use any auxiliary data structure to not use any auxiliary data structure to store the result that's it guys thanks store the result that's it guys thanks for watching see you on the next video | 2024-03-24 11:05:00 | 344 | Reverse String - LeetCode 344 - Coding Interview Questions |
|
QvKsYAhTnsM | all right so this question is three divisors so you are given the integer n divisors so you are given the integer n so return true if n has exactly three so return true if n has exactly three positive divisor and I'll just write positive divisor and I'll just write return false so a divisor is actually return false so a divisor is actually like you I mean you can assume an equal like you I mean you can assume an equal to K times n and K is integer and it's to K times n and K is integer and it's also integer and then also integer and then and then m is actually the floating and then m is actually the floating number between the 1 to n so um number between the 1 to n so um let's briefly talk about like if n equal let's briefly talk about like if n equal to two the divisor is what one and two to two the divisor is what one and two right so there are two only so you right so there are two only so you return false why so you say uh two more return false why so you say uh two more by one by one this is what this is what or two more by two or two more by two mobile two this is zero and two mobile mobile two this is zero and two mobile one this is actually what uh zero right one this is actually what uh zero right like every single number more by one is like every single number more by one is always zero right and two more back to always zero right and two more back to the two divided by two the remaining is the two divided by two the remaining is actually zero right two divided by one actually zero right two divided by one the remaining is zero so uh the remaining is zero so uh you know no this is straightforward you know no this is straightforward enough so uh let's talk about the next enough so uh let's talk about the next one so for the next one uh don't equal to four right so 4 divided by one right this is for the remaining is actually zero four divided by two this is two remaining 0 4 divided by three this is one dot three three three three three three right so they are remaining so you don't count this one and fourth divided by four this is one remaining section zero so we just do get a little remaining and this is our list of the answer three and you return two so uh let's just know like we assume one is always one one is always about it then I have a deal with one D represent divisor so I have to make sure my return is D equal to three right so when it Traverse I have to Traverse from the two and all the way to the what all the way to the end and also my I'm I'm going to assume my P is inside my full condition so D less than equal to three and I plus plus so if uh if the earn more by I is actually equal to zero you increment your divisor which is e and this is pretty much a solution so let me run it at time and space and this is straightforward a space is constant time is all of them and it's actually a little on right and yeah you break all the value earlier then you save a lot of time but whatsoever so this is the solution so if you still have question uh just leave a comment below subscribe if you want it and I don't think you need the bar for this one this is 34 enough and | 2024-03-25 13:41:10 | 1,952 | LeetCode 1952 | Three Divisors | Math | Java |
|
bv17A76ZAe8 | Ko Hi I am Aayushi Rawal and welcome to my channel today will gather September light to turn channel today will gather September light to turn on this death problem repeated sub skin on this death problem repeated sub skin problem give this can be constructed by taking problem give this can be constructed by taking subscribe and multiple co subscribe subscribe and multiple co subscribe till take English letters in chief till take English letters in chief output bullion true output bullion true that your will see that your will see that your will see problem flu positive one ok are putting a easy that I will declare substring in this app let's you be easy a plus calculate the length of the input spring dels 49 will channel there string Be Be Be Always With Strangers Hey Baby Now Wicket Always With Strangers Hey Baby Now Wicket And Minerals String With Easy Repeating In Loop And Minerals String With Easy Repeating In Loop subscribe The Amazing 999 2515 Will Be subscribe The Amazing 999 2515 Will Be Result Will Be Amazed I Will Result Will Be Amazed I Will Multiply subscribe The Channel Multiply subscribe The Channel Petai 10th Result Match The Thing This Vitamin Petai 10th Result Match The Thing This Vitamin Loop Returns True For Results For It is not possible to make It is not possible to make It is not possible to make a string with co subscribe abcd abcd a string with co subscribe abcd abcd abcd abcd is form abcd abcd is form subscribe bc affairs for time and even subscribe bc affairs for time and even with abc d abc akash roy ok with abc d abc akash roy ok knowledge video like subscribe and knowledge video like subscribe and subscribe kare length offer subscribe kare length offer initial input singh naav nor will calculate nor will calculate that alcohol play the length of the substring next will calculate that resulting substring meeting copy e that girl looted 5850 result in sub string and input stringer exactly this show will return as that this control below this line number for Hai one return truly dot in decade that Hai one return truly dot in decade that Hai one return truly dot in decade that they have not found subscribe search net they have not found subscribe search net banking ko subscribe pendi extra banking ko subscribe pendi extra strength so in that case will return strength so in that case will return forms and a forms and a hua hai hua hai mein knowledge immediately koan a a dozen roy ok kya idli oo I have knowledge and such a meeting, take I have knowledge and such a meeting, take loot, loot, another principle is another principle is a friend you for watching my video please a friend you for watching my video please like share and subscribe my channel they like share and subscribe my channel they are true victims | 2024-03-22 14:51:42 | 459 | Repeated Substring Pattern | September Leetcode Challenge | Leetcode 459| Day 3 |
|
heujOW9WiHE | okay let's do this question this questions let's do this question this questions give me a hard time so you're given a network of nodes represented by this adjacency matrix so one if the nodes are connected and a zero if and those are corresponding to the index and those are corresponding to the index within this matrix within this matrix and you're also given this vector of and you're also given this vector of initial nodes which represent initial nodes which represent nodes infected by some malware nodes infected by some malware and if two nodes and if two nodes are directly connected to each other are directly connected to each other then they're both and one of them are then they're both and one of them are in the initial in the initial vector then vector then both nodes are infected so we want to find out if we were to just remove one node from which node should we remove so as to which node should we remove so as to minimize the total number of infected minimize the total number of infected nodes so there is a very tricky case here say one is node zero node one is say one is node zero node one is connected to two which is connected to connected to two which is connected to three and we also have a node three and we also have a node zero here zero here that's not really connected to anything that's not really connected to anything and we have that and we have that node one is infected so three is node one is infected so three is infected infected and node zero is infected so and node zero is infected so we have 0 we have 0 1 3 1 3 is our initial nodes so which one should we remove from initial such that so as to minimize the number of total infected nodes so if we consider all nodes are in the network or infected nodes the number of infected the the resulting graph will have all nodes infected because 2 is is connected to 3 and 2 is so if we were to move say 1 for example so if we were to move say 1 for example the number of infected nodes we remove the number of infected nodes we remove is one is one from because two will still be infected from because two will still be infected because it's still connected to three because it's still connected to three same same case if we just remove a three same same case if we just remove a three in the same case actually if we just in the same case actually if we just move zero all of them are still infected so [Music] what do we do here which one do we remove since all of them kind of remove the same number of infected nodes in the resulting network then we should return the node with the smallest index so we should return zero let's consider another let's consider another we have one two two two three we have one two two two three and two four and we have that two is infected and three is infected and we have three is also connected to five so the obvious answer is three right because if we move three then we get to [Music] we get two less nodes infected in the when we remove a node it also removes when we remove a node it also removes the edges as well that are connected to the edges as well that are connected to that node that node so that means so that means four and five will no longer be infected four and five will no longer be infected in the resulting graph so we kind of see you can see that the number we if we can count the number of nodes that belong to an infected node that uniquely belong to an affected node is the highest for then we remove when we then we select that node to remove so for example three is connected to four and five there are two nodes that uniquely belong to three and one is uniquely belongs to two now what now let's see what happens if two a node a node six here six here since six belongs to both two and three since six belongs to both two and three they both connect they both can be they both connect they both can be touched by touched by by six by six by two and three by two and three then six doesn't uniquely belong to two then six doesn't uniquely belong to two and three so we don't count six because and that kind of makes sense because if you remove two six will still be infected so if we move three six will stimulate and the other thing to note is if three and the other thing to note is if three is when we try to find what nodes uniquely belong to three um we we can't find one because to go to find one we would have to go through this infected node so we try to avoid going through going through other infected nodes to find yeah and that's basically it so what's yeah and that's basically it so what's the time complexity of this the time complexity of this solution solution what we're doing we can do a dfs from what we're doing we can do a dfs from each infected node and we could mark we can have a counter for each node and just increment a count and so that that's so eventually two this one here will have a count of two uh four and five will have a count of one and one will have a count of one and then we have to do a device for all infected nodes again and just count the number of nodes that we see that have count of 1 and if we see a if you see a count of if you see a count of greater than 1 greater than 1 then stop there you know it's like a then stop there you know it's like a return condition so dfs to go through this graph this graph is like a 300 by 300 matrix so the n goes up to 300 so that's like 300 squared to this 300 squared edges and dfs is complexity of dfs is v plus e where v is complexity of dfs is v plus e where v is number of vertices and e's number of number of vertices and e's number of edges and we have to do this dfs for all the initial nodes and initial nodes can go up to n as well or let's just say it can go up to n so that means our final time complexity would be something looking like this n cubed well 300 cubed is like 27 million and assuming that the time complex the the time limit is one second or something like that we should be able to solve this problem in time i mean fast enough why because if we take the rule of thumb that 10 to the power 8 is the number of operations that we can do in one second in one second then then [Music] is a 10 times 10 to the power of 6 that's times 10 to the power of 6 that's definitely less than 10 to the power of definitely less than 10 to the power of 8 so we can do this in one second 8 so we can do this in one second all right so let's start creating this all right so let's start creating this up to check if the node is affected or not it's best to have this initial node in some kind of an ordered set so we can figure out if a node is infected in constant time um saying infected and go all right so for i in initial i in initial [Music] [Music] affected insert you also need to keep track of the count you also need to keep track of the count of the vertices so vector of the vertices so vector and and count count and we need to go through a df and do a dfs and make sure we need a scene array and make sure we need a scene array so we don't a time symplexy doesn't go overboard um boolean we can say maybe keep track of n as n is equal to the graph dot psi so graph then we can take then we can take count is equal to a vector count is equal to a vector hence size n and starts at zero and we also have the scene to be equal to the vector okay that will increment the count for a that will increment the count for a particular node particular node for a particularly particular infected for a particularly particular infected node node starting at starting at say v so if we've seen this before it should be a vector v before then return otherwise set scene to equal to one otherwise set scene to equal to one true count of v should be incremented count of v should be incremented and then we have to go through each of and then we have to go through each of the connected nodes so for nt i is equal to 0 i less than n plus plus i going through each of the infected nodes so the graph of v at i if that is the one right then do a dfs on this node which is i which might say u okay cool but uh okay cool but uh so this has to be done for each of the so this has to be done for each of the initial nodes so for initial nodes so for into you in initial oh and also i don't if if it's if the note is infected so if u is infected then skip so i could skip it up here you can skip up here just keep it down you can skip up here just keep it down here it doesn't really matter so if here it doesn't really matter so if if infinite dot find so trying to find u if infinite dot find so trying to find u is equal to oh does not equal to end so infinite end that means yeah actually i want it down here because if i put it down up here then that means i want the the first one that i i pass in won't be uh then now i want to continue cool and then here i want to go through for interview initial so for each of the initial nodes i want to do a dfs on that passing the graph and you yeah and that should initialize the counts for me and now i just need to account account and that takes in and that takes in vector graph so we're doing a dfs so we probably need to we're doing a dfs so we probably need to every stage clearing out the dfs so fill every stage clearing out the dfs so fill and fill the scene vector so begin let's seeing end so i haven't seen it yet and do this so i haven't seen it yet and do this and you go through all the nodes and keep track of the best answer so the and keep track of the best answer so the answer is answer answer is answer and let's say the and let's say the the number the number the count the count is equal to minus one initially uh max count here uh max count here so you can say into count is equal dfs so you can say into count is equal dfs count on count on graph with v should be you less than less than it's greater than if the count is greater than max count or um the mac all the count is equal to the max count and then i want to update the answer to be then i want to update the answer to be equal to u and max count equal to u and max count to count to count at the end return the answer so now this part makes sure that and here i need to do it if scene v return so here i'm doing dfs so i need to make sure i fill do this line here because i'm doing another dfs how to do and let's go through here if i've seen and let's go through here if i've seen it return it return otherwise i've seen it so set it to otherwise i've seen it so set it to scene and also for so go through all of the loans and can if it's an infected node continue if it's an infected node continue again again and also if the count and also if the count of of u is u is greater than one um i need to count right so let's say end count is equal to zero my count is one because i'm counting the my count is one because i'm counting the current node count plus count plus equals to dfs of count then i'll return my count here okay there's probably a lot of bugs here defense of u defense of u takes in the graph as well somewhere takes in the graph as well somewhere so 34. oh wrong answer all right oh wrong answer all right oh if you could check if they're actually that's kind of important that's kind of important there we go okay took me a while took me a while i haven't actually solved this question i haven't actually solved this question yet so i'm hoping that i've solved it yet so i'm hoping that i've solved it this time around this time around had so many wrong attempts had so many wrong attempts let's uh let's try on one of my failed test cases oh my this one almost i tried i tried dsu before it didn't i tried i tried dsu before it didn't work okay i'm like 70 percent confident with this solution yes so the other i think i'll try again with so the other i think i'll try again with dsu some other time | 2024-03-25 11:29:38 | 928 | 928. Minimize Malware Spread II - Daily Leetcode (Day 4) |
|
KkOweCEADjA | guys uh so welcome to my legal serving section section the easy part so 1 7 the easy part so 1 7 32 find the highest attitude 32 find the highest attitude uh sorry finding the audit sorry not 82 uh sorry finding the audit sorry not 82 sorry sorry so uh there is a bike going a road trip so uh there is a bike going a road trip and the pro and the pro uh triple count has m plus one points at uh triple count has m plus one points at different different uh altitude uh the bike the biker is uh altitude uh the bike the biker is starting his stop on po zero the rd is starting his stop on po zero the rd is equal to zero right so basically okay equal to zero right so basically okay you should you should i mean you can call height okay so there i mean you can call height okay so there is so is so starting from height zero and go to high starting from height zero and go to high one high to high three up to one high to high three up to high in so total we have uh uh high in so total we have uh uh high end plus one so we have high n plus high end plus one so we have high n plus one points and the height zero is one points and the height zero is zero okay so you are given an integer zero okay so you are given an integer array so you are array so you are already right issue right it's a ray and already right issue right it's a ray and each element is integer each element is integer of length n uh where again i is the net of length n uh where again i is the net gain gain it means that at right that gain it means that at right that gain attitude the altitude will hit the point attitude the altitude will hit the point i i i plus one and return the highest of i plus one and return the highest of a point okay so again it's minus five a point okay so again it's minus five one five zero say one five zero say uh minus seven or negative seven so i uh minus seven or negative seven so i start from zero right start from zero right the node start from zero and add the node start from zero and add negative five so negative five and i add negative five so negative five and i add one negative four one negative four and uh plus one plus one because we add and uh plus one plus one because we add five got one we get at zero five got one we get at zero one and negative six and height is 1. one and negative six and height is 1. okay now this guy is okay now this guy is 0 okay so so now we see the idea is very 0 okay so so now we see the idea is very easy right the idea is that easy right the idea is that we just you know explanation just for we just you know explanation just for our explanation we just create a list of our explanation we just create a list of these these oh of this guy and we've tried to find a oh of this guy and we've tried to find a maximum of it maximum of it try to find the maximum of of this list try to find the maximum of of this list okay so the idea is that okay so the idea is that we know the length of the gain right so we know the length of the gain right so we create at least which is start on we create at least which is start on zero and the length of m plus one zero and the length of m plus one okay so uh so that means i i initial okay so uh so that means i i initial i initialize the list which is zero zero i initialize the list which is zero zero zero zero zero zero zero zero zero zero as this yeah for example if i use as this yeah for example if i use example one example one and i start from one and the length n and i start from one and the length n plus one i just plus one i just use the first guy added uh so i use the first guy added uh so i so the second guy the second guy is just so the second guy the second guy is just the first guy the first guy at the game the first guy in the game at the game the first guy in the game and the second guy just the previous guy and the second guy just the previous guy added the added the game right so basically at least i the game right so basically at least i the ice guy is the i minus one guy ice guy is the i minus one guy plus the gain i minus one so for example plus the gain i minus one so for example if i is one if i is one then means least one is the least zero then means least one is the least zero is zero zero is zero zero plus the again zero right so this plus the again zero right so this recursion formula will just give you the recursion formula will just give you the at least one so let's maybe print at least one so let's maybe print uh prints uh one example and around the uh prints uh one example and around the test code to let you guys see uh this test code to let you guys see uh this list list will exactly be this guy right exactly will exactly be this guy right exactly the same sorry the same sorry and then we finally return the max okay and then we finally return the max okay so this guy this will be just the answer so this guy this will be just the answer so since you guys know the trigger right so since you guys know the trigger right so so yeah the rest is distributed okay uh yeah the rest is distributed okay uh but i mean we can still we still solve but i mean we can still we still solve it right so it right so okay so i will see you guys in the next okay so i will see you guys in the next videos be sure to subscribe to my videos be sure to subscribe to my channel thanks | 2024-03-20 17:51:11 | 1,732 | Leetcode solving: 1732 Find the Highest Altitude |
|
TdA2K_N1rgY | hello and welcome to my channel so today let's look at the today's daily let's look at the today's daily challenge question challenge question lead code 130 surrounding the regions lead code 130 surrounding the regions given m times n matrix board containing given m times n matrix board containing x and all x and all oh capture all regions that are four oh capture all regions that are four surrounded by x surrounded by x origin is captured by flipping all o's origin is captured by flipping all o's into x and in that surrounding the into x and in that surrounding the region region so example is a so example is a first example uh this grader after the flip only the first the middle trick oh get uh converted to x so uh the old in the in the border will not be converted um um [Music] [Music] yeah it's also like a you uh it's yeah it's also like a you uh it's decided by four connect four directions decided by four connect four directions so this this oh and this so you should so this this oh and this so you should uh if you count the diagonal is kinetic uh if you count the diagonal is kinetic but they are not considered connected but they are not considered connected so uh uh we can we can we can actually start the we can actually start the start from the border and find the [Music] find the o in the border do bfs do bfs to find the to find the order connected oh fill and replace with a different value we replace those cells for example with the with the f uh to uh to first bub is a for the rest of all you first bub is a for the rest of all you actually can replace those odds actually can replace those odds uh to to x uh to to x and and the last step is uh then you can replace uh f with f to um to o again um um [Music] [Music] the process the process so yeah let me give this example i can so yeah let me give this example i can we can we can [Music] um um show you how to do that so like for show you how to do that so like for example there is o in the in the border example there is o in the in the border and there is o here and there is o here and also the o is connected to the but it's only connected to one this and then this one may be not connected so and and also there is o in the middle and also there is o in the middle like uh this one so so uh so we can firstly we find all the o's in the uh in the queue like in the in the border and now we put them in we put them into the queue and [Music] then we we find that with that we started expanding so we uh we expanded to then we go to the four direction and they expanded to the oh inside the because these two is connected so during the process we just change it and uh so this will be f and this will and uh so this will be f and this will be f be f and then we scan the and then we scan the border border again then we change order border border again then we change order o which would not have to to x o which would not have to to x so the last step is we so the last step is we we scan the border again and then we we scan the border again and then we change those values back to all change those values back to all so after after the so after after the this process it will be this process it will be uh uh the board when we want okay so let's the board when we want okay so let's start the writing the code so start the writing the code so uh we can actually have the uh we have the queue defined so we can actually add all the [Music] we can add all the coordinate of border roles also we want to define also we want to define as usual for the grid we want to define as usual for the grid we want to define a direction vector and also we want to as a global variable now we can go now we can go go scan into the border go scan into the border so there are only four so there are only four borders like we can other column board or n minus one this is one first column and n minus one this is one first column and the last column the last column is a is a is o uh now we need to add them to the [Music] actually we need to split this to um um [Music] similarly similarly we want to do the same for the we want to do the same for the for the row direction so we for the row direction so we that is we can actually we don't know how to do this i actually we don't know how to do this i think we can do another is we can do the think we can do another is we can do the bfs bfs we can we can we can we can create another function called bfs create another function called bfs and because this there is a like a and because this there is a like a disadvantage of doing this way is uh disadvantage of doing this way is uh maybe two cells are connected on the maybe two cells are connected on the on the border on the border so you actually add them so you actually add them both to the queue both to the queue um so i think that yeah we can so that uh we just do the bfs on invest we just do the bfs on invest in in a separate function in in a separate function um yeah so so here we just need to do bfs but we don't add to the queue um um a man as well yeah and then in the board also we want to define another function called uh this is checking if the this is checking if the coordinator is valid okay so let's add this uh um um and also we need to and also we need to as i mentioned that we need to change it then we can do the bffs then we can do the bffs to expand using our loop to expand using our loop so yeah yeah and also we we can now using the four and also we we can now using the four direction direction uh the array we we uh define the uh the array we we uh define the directory and then we get a directory and then we get a the next node expansion expansion so that here if if this node is uh if so that here if if this node is uh if it's not an area then it's uh it's not an area then it's uh another valid another valid coordinate continue coordinate continue if it is in area then we can we can add it to the queue i think we uh if it's not at all uh if it's not at all we actually also continue we actually also continue so so then it means it's ro and then we can ch then it means it's ro and then we can ch also change it to f and then so until the so until the this bfs is this bfs is uh completed we we added the connected uh completed we we added the connected cells cells to the and also we changed it to f to the and also we changed it to f so after this four so after this four so the border has been checked then we so the border has been checked then we we can do a loop and change all the o's to yeah actually also we can do the same yeah actually also we can do the same thing the same uh thing the same uh like the like the logic we mentioned that we want to logic we mentioned that we want to change all the change all the f f to o yeah and and then after this is done it oh it should be done oh it should be done so so another the time complexity is a time is [Music] over and as the the in the grid yeah that's actually the time of we generally get when doing the dfs also the space maybe uh the worst case is also old um yeah so it's the first example correct the okay okay yeah yeah so this concludes today's session uh so so this concludes today's session uh so thank you for watching see you next time | 2024-03-21 11:43:59 | 130 | Leetcode 130. Surrounded Regions (Daily Challenge 11/1/2021) |
|
jQv73r8Lbc4 | hello hello everyone this is leak code 141 link list cycle um given head which 141 link list cycle um given head which is the head of a link list determine if is the head of a link list determine if the link list has a cycle in it um the link list has a cycle in it um there's a cycle in a link list if there's a cycle in a link list if there's some node in the list that can there's some node in the list that can be reached Again by continuously foll be reached Again by continuously foll the next pointer so um yeah we follow the next pointer so um yeah we follow the next pointer for a specific note and the next pointer for a specific note and eventually if there is a cycle in the eventually if there is a cycle in the link list uh at one point one of the link list uh at one point one of the nodes one of the nodes uh next pointer nodes one of the nodes uh next pointer will will bring us back to a node we've will will bring us back to a node we've already already visited so in that case there is a cycle visited so in that case there is a cycle uh and basically to approach this uh and basically to approach this problem we're going to use the tortois problem we're going to use the tortois and hair algorithm which is a pointer and hair algorithm which is a pointer algorithm on more rly it's just a cycle algorithm on more rly it's just a cycle detection detection algorithm um which makes use of two algorithm um which makes use of two pointer so uh basically we we're going pointer so uh basically we we're going to have a a pointer at the start well to have a a pointer at the start well two pointers both they both point at the two pointers both they both point at the to the Head note at first and um one of to the Head note at first and um one of them is going to be a slow pointer and them is going to be a slow pointer and one is a fast pointer the slow pointer one is a fast pointer the slow pointer is going to basically move um to the is going to basically move um to the next node and then the fast pointer is next node and then the fast pointer is going to move to the next node and then going to move to the next node and then the next node right and the next node right and so basically one pointer is going to be so basically one pointer is going to be the slow pointer which just moves you the slow pointer which just moves you know uh one node it traverses one node know uh one node it traverses one node and then the pointer traverses two node and then the pointer traverses two node um every you know uh quote unquote turn um every you know uh quote unquote turn and So eventually if there is a link if and So eventually if there is a link if if there's a cycle in the link list if there's a cycle in the link list these two these two pointers the slow these two these two pointers the slow pointer and the fast pointer they will pointer and the fast pointer they will meet at some point if there is meet at some point if there is a uh cycle now if there's not a cycle a uh cycle now if there's not a cycle what's going to happen well if there's what's going to happen well if there's not a cycle then the fast pointer not a cycle then the fast pointer eventually is going to reach the end of eventually is going to reach the end of the link list right so we're going to the link list right so we're going to get we're going to reach a point get we're going to reach a point eventually where where um there's no eventually where where um there's no nodes that we nodes that we can uh Traverse any F we can't Traverse can uh Traverse any F we can't Traverse any further in the link list at some any further in the link list at some point uh if there is no cycle and that's point uh if there is no cycle and that's how we can basically find if there's a how we can basically find if there's a cycle or not is either these two nodes cycle or not is either these two nodes are going to are these two pointers I are going to are these two pointers I should say are going to meet eventually should say are going to meet eventually or they are going or they are going to um or the fast pointer eventually is to um or the fast pointer eventually is going to reach the end of the link list going to reach the end of the link list okay so we'll initialize our uh slow and okay so we'll initialize our uh slow and fast point winner both to the Head fast point winner both to the Head node and node and then essentially what we're going to say then essentially what we're going to say is while there is a fast node while the is while there is a fast node while the fast node fast node uh um exists uh um exists or uh fast. next or uh fast. next exists we are going to essentially first exists we are going to essentially first of all let's move the slow pointer um so of all let's move the slow pointer um so slow pointer is going to go to the next slow pointer is going to go to the next pointer and again the fast pointer is pointer and again the fast pointer is going to Traverse down two nodes okay um and at some point if they are equal we have to check right if if they're equal right if they meet then we return true cuz um there's a cycle in the list now if we exit this y Loop by the way sorry I have to move this here so we're still in the Y Loop um and if we exit the Y Loop that means we didn't return true so we that would be a case where we Traverse um through the link list and there's actually not a cycle in which okay okay yeah uh pretty simple uh this this this yeah uh pretty simple uh this this this like algorithm this toris and hair like algorithm this toris and hair algorithm it shows up on a few problems algorithm it shows up on a few problems um uh there there's more problems that um uh there there's more problems that deal with cycles and linkless and or deal with cycles and linkless and or deals with just with link lless problems deals with just with link lless problems um and you're gonna have to use uh this um and you're gonna have to use uh this algorithm so yeah I hope this helps um I algorithm so yeah I hope this helps um I don't think this problem's too bad it don't think this problem's too bad it especially it's kind of hard to come up especially it's kind of hard to come up with uh I think intuitively if it's your with uh I think intuitively if it's your first time you've come across this first time you've come across this algorithm but um eventually you are algorithm but um eventually you are going to run into problems where you going to run into problems where you have to use this again and have to use this again and um you know as long as you uh are aware um you know as long as you uh are aware of it now um shouldn't be uh shouldn't of it now um shouldn't be uh shouldn't be too hard to come up with a solution be too hard to come up with a solution next time you see a like a harder next time you see a like a harder problem that has to use a cycle or where problem that has to use a cycle or where you have to find a cycle in a link list you have to find a cycle in a link list for whatever reason okay anyways that's for whatever reason okay anyways that's it and uh I hope this it and uh I hope this helped | 2024-03-21 12:34:25 | 141 | LeetCode 141. Linked List Cycle (Python) |
|
dDQTlfWvzqE | Hello everyone welcome to my channel code sir with mike so today we are going to with mike so today we are going to do video number 32 of our strings playlist do video number 32 of our strings playlist ok and link number 1 47 this is a ok and link number 1 47 this is a question of medium easy range ok it question of medium easy range ok it is not very tough no g asked this question is not very tough no g asked this question is not very tough no g asked this question see what is the question, it says the name of the question is Minimum Number of Steps to Make Two Strings Anna Gram You are given two strings, two strings must be given, one S and one T, like look here, T is In one In one In one step you can choose any character of t and step you can choose any character of t and replace it with another character What it is saying is replace it with another character What it is saying is that in one step you that in one step you can pick any character of t and can pick any character of t and replace it with another character replace it with another character Return the minimum number Return the minimum number Return the minimum number an anagrammer, let me tell you what the meaning of an anagrammer is. An anagrammer contains the same characters with a different ordering. The count of characters will be exactly the same. Only the It goes It goes It goes like look at B.A.B. B.A.B like look at B.A.B. B.A.B is the anagram of A.B.B. What else is the anagram of A.B.B. What else can it be? B.B.A is not A. It can be anything can it be? B.B.A is not A. It can be anything but the number of characters should be same but the number of characters should be same and the same characters should be present in it. and the same characters should be present in it. Right, it has just been shuffled, Right, it has just been shuffled, so look here at T which is there. Now look at the so look here at T which is there. Now look at the anagrammar. If you look at A, then B anagrammar. If you look at A, then B which is there has come twice and A which is there has which is there has come twice and A which is there has come once but look here at T which is B. come once but look here at T which is B. A has come only once and A has A has come only once and A has come twice so the agram is there now otherwise come twice so the agram is there now otherwise you Y is saying that in how many minimum you Y is saying that in how many minimum steps can you make T an agram steps can you make T an agram of A then why is the answer one because if of A then why is the answer one because if you you you can convert A into B. It takes one step, this is your answer. Look, if you convert A into B, what does it become? A B B. Look, this is its agram, Look in this, the B which is there has Look in this, the B which is there has Look in this, the B which is there has come twice, A has come once and B has come once, in this also now B has come come twice, A has come once and B has come once, in this also now B has come twice and A has come once. Okay, twice and A has come once. Okay, so you have made t an agram of s and so you have made t an agram of s and you have taken one step. Okay, like this. you have taken one step. Okay, like this. you have taken one step. Okay, like this. convert the lead code into practice, it will take us five steps to make the agram of S lead code from practice. Look here, like here this character of 'P' and 'A' is not there. Okay, so Let me convert it into L Let me convert it into L Let me convert it into L because L is because L is not even here, right, whatever r is is not in s, not even here, right, whatever r is is not in s, so I convert r also. so I convert r also. What should I convert r into? I convert it into d. What should I convert r into? I convert it into d. Whatever is there is in s, Whatever is there is in s, no, okay, so let's convert a into no, okay, so let's convert a into something, let's do it in o, something, let's do it in o, okay, c is here, okay, a t, okay, c is here, okay, a t, whatever t is, aa is not above, right? whatever t is, aa is not above, right? whatever t is, aa is not above, right? converted into e then s is ready. If both of them match then there is one extra c here then convert it into e and if this e is ready then see a letters and write the rest as l double T C O D E is the lead code, so it takes a total of T C O D E is the lead code, so it takes a total of T C O D E is the lead code, so it takes a total of five steps to five steps to convert it into its agram, so the convert it into its agram, so the answer is five. Okay, so let's see answer is five. Okay, so let's see what is Intu. Intu is quite simple, but what is Intu. Intu is quite simple, but before that, once I before that, once I before that, once I what agram means. Agram means that let's say there is an s1, okay let's assume s or t. This is my a first string s is the second string Whatever Whatever Whatever characters are there in s and the number of times those characters appear should be same in t. Whatever characters are there in s should be in t characters are there in s should be in t and as many times as they are in s, they and as many times as they are in s, they should also be in t. This is clear. should also be in t. This is clear. should also be in t. This is clear. can be successful, he must have been successful only then he is clear even in anagrammar. Now coming to our entry part, look at this first small example and one or two more examples and we will see so that there is more clarity, then The question is, what is the meaning of ' The question is, what is the meaning of ' The question is, what is the meaning of ' s' to the kitty? s' to the kitty? So for Anagu, I had said that the So for Anagu, I had said that the characters in both should be exactly the same. It is characters in both should be exactly the same. It is not a problem if there is a fruitful result, so not a problem if there is a fruitful result, so first of all I find out first of all I find out how many characters are there in 's'. how many characters are there in 's'. how many characters are there in 's'. not 'B' which is 'A', first let's write ' A' which is there in 's' and has come once and 'B' which is there and which has come twice, both are fine and The one which is A has The one which is A has The one which is A has come twice, okay and the one who is B, has come twice, okay and the one who is B, has come once, come once, okay, so we have stored which okay, so we have stored which one has come how many times, okay, now one has come how many times, okay, now look, pay attention, I come to T look, pay attention, I come to T because look, T. because look, T. because look, T. so I came to T and asked T, T, which characters do you have? T said, I have A, but A has two, so I will see A is saying that I should have A is saying that I should have A is saying that I should have only one A will match this and what else and this one A will be converted into something else and what will be converted later Ok but right now T is not worried because he wanted an A, right, there is at least one So it's okay so there is no tension because at So it's okay so there is no tension because at So it's okay so there is no tension because at least one is there, what I am saying is least one is there, what I am saying is that the frequency of A is that the frequency of A is more in N or it is either equal or the more in N or it is either equal or the frequency of A is there in A frequency of A is there in A No tension because the frequency No tension because the frequency required should be at least that much, if it is more required should be at least that much, if it is more then it is a good thing, but this means that if it is more then it is a good thing, but this means that if it is more then it is a good thing, it should not be less, if it then it is a good thing, it should not be less, if it is less then we will have problems, is less then we will have problems, so here is the solution. so here is the solution. so here is the solution. thing, okay, so A is happy right now but B, but if I came, B said, brother, I have only one B, but A also needs two, okay, A also needs two. Meaning, how much operation will have to be flipped, now from where to get that flip done, look, here I write that it has two A's and it has one B, what is here, one A and two B's, so You see, You see, You see, okay B is one but I also want two, okay, that okay B is one but I also want two, okay, that means how many flips will have to be done, two means how many flips will have to be done, two means, one flip will have to be done, means, one flip will have to be done, I will have to hold one of the characters and convert it into B I will have to hold one of the characters and convert it into B so that here also two can come, so that here also two can come, okay, but you have to. okay, but you have to. okay, but you have to. your tension is with whom will you have to flip and how much will you have to flip? Forget about whom you will have to flip. He is not asking you a bit. You were just asked, brother, how much will you have to flip and how much will you have to replace the character? Well, look, he Well, look, he Well, look, he had one B but we need two B, so one had one B but we need two B, so one extra B would be needed, otherwise extra B would be needed, otherwise I have removed the same thing from here, what did I do, find out the I have removed the same thing from here, what did I do, find out the difference between the two, difference between the two, how many B are there in s, two, he has only one. how many B are there in s, two, he has only one. how many B are there in s, two, he has only one. one B and extra, that means one more flip is needed, that means we will have to do minimum one flip, we will have to do one flip, then who will you do one flip, that is not your tension in this t string, it will happen somewhere. No, if you look further, whom will you do, will you do this, he had two A's, so I converted this A into B, okay, there were two A's, one A was converted into B, that is your tension, no, you don't even have to see Okay, all you have to do is see Okay, all you have to do is see Okay, all you have to do is see how much B would need. There is only one B. But how much B would need. There is only one B. But one more B would be needed. One more B would be needed. one more B would be needed. One more B would be needed. Okay, so we looked at both the characters Okay, so we looked at both the characters and we found out that one and we found out that one extra flip would be needed. extra flip would be needed. extra flip would be needed. was one, it is clear, this is my only tension, how many flips will t need, here there was only one b, one more is needed, because t also I will catch any one character I will catch any one character I will catch any one character and flip him. Who will I catch? That and flip him. Who will I catch? That is not my tension. It is clear here but is not my tension. It is clear here but in this I am 100% sure that a in this I am 100% sure that a counter question will definitely come in your mind. Do you counter question will definitely come in your mind. Do you know what I just said here? know what I just said here? know what I just said here? one more, this poor guy wanted one more, so I said, ok, I want one more, no, I just want one more, neither is that one, I will try to flip some other character and I will do it, then you will Well, here we have found a Well, here we have found a Well, here we have found a character which can be flipped. Let's assume that it is not there, so that means you are saying that here it is not one, that is, there is only one A. that it is not there, so that means you are saying that here it is not one, that is, there is only one A. Well, if there is only one A, then brother, this is How many characters does it have in total? How many characters does it have in total? How many characters does it have in total? Three, its total characters are two. It Three, its total characters are two. It is not an agram, so don't worry about it. is not an agram, so don't worry about it. And this counter question is a good question. You can ask it in the interview. Okay, so what have I written here? How many A's does You can ask it in the interview. Okay, so what have I written here? How many A's does it have? it have? it have? flip this one to make B, then he would make it. Someone here has got A, this would become B. Okay, so I have cleared that counter question for you here too, This This This point may come in the interview. Okay, so let's dry run one more example. point may come in the interview. Okay, so let's dry run one more example. Then the code is nothing, it is a Then the code is nothing, it is a simple code, so let's see this example. simple code, so let's see this example. Now you have understood the main thing Now you have understood the main thing that any such character. that any such character. that any such character. frequency is more in s and less in t, then it is messed up, that is why it is messed up because look, here there were two, here there was one, so 2 - one extra, this one needs one extra and that was The same thing has to be done The same thing has to be done The same thing has to be done like look here A which is L, isn't it? Do like look here A which is L, isn't it? Do you see L here? you see L here? Yes, it is true that I found a character in S Yes, it is true that I found a character in S whose frequency is more than T. whose frequency is more than T. Here the frequency of L is one and here Here the frequency of L is one and here But the frequency of L is zero, okay, that means But the frequency of L is zero, okay, that means I will have to flip one character, I will have to flip one character, who has to do it in T, don't who has to do it in T, don't take tension, I already told you, okay, so take tension, I already told you, okay, so I added one in the answer because of this L, I added one in the answer because of this L, because the frequency of l here. because the frequency of l here. because the frequency of l here. okay, now look at e here, its frequency is three, here its frequency is only one, so this guy will need two more, right, e means 3 -1, that is two more, so one here, two will be added here. After that look at t, here t is 1, here also t is 1, nothing is needed, both are equal, what is fine, look at c, here is c1, here is c2, see, pay attention, here c is one and here c is two, you should not take tension because Here the frequency is more this time, is n't it? Here there are two frequencies, two C's and here there is only one C, so no problem, one and this one will match both and the remaining C of this one will Where we needed it is okay, Where we needed it is okay, Where we needed it is okay, okay then CC is also fine isn't it okay then CC is also fine isn't it because it is more in t, just less if the because it is more in t, just less if the frequency of t is, then the frequency of t is, then the frequency of the character in t will be less, only then we have to take tension frequency of the character in t will be less, only then we have to take tension like o here is one here. like o here is one here. like o here is one here. not there, so 1 - 0 One more must be required D Here there is one D here There is no D Okay so here one more must be required D Okay so see how much is done Na Plustwo The answer is The answer is The answer is no, so ultimately what is the frequency no, so ultimately what is the frequency of a of a character in s, which is if it is greater than the character in s, which is if it is greater than the frequency of character in t, then the frequency of character in t, then the difference will be the amount we need difference will be the amount we need in t, then the result is okay. in t, then the result is okay. in t, then the result is okay. result plus e is equal to frequency of that character in a s p Whatever frequency is there we will subtract the character in a s p Whatever frequency is there we will subtract the frequency of that frequency of that character in t Just keep adding in the result character in t Just keep adding in the result s Simple as that is quite simple and s Simple as that is quite simple and given in the question that given in the question that given in the question that English letters only, so we can use map to count the frequency but I will simply use an array of integers. Rows of size 26 to 25. What was this zero for? A is for B. Remember, whatever character was there, if you minus it from A, its correct index would come out, like what would be the index of A, my A is What will be the index What will be the index What will be the index b my a that is w so this is b and so on i have b my a that is w so this is b and so on i have already told you so i will already told you so i will use 26 size hey i will not use map i will not use map use 26 size hey i will not use map i will not use map till now so story to till now so story to code is very simple what did i say code is very simple what did i say code is very simple what did i say store the frequency, either first we will store the frequency of all the characters of A, we will take a map, or we will take a vector of A, what is its name of size 26, what should I give the count, I will give the The The The frequency of the characters is stored in it, frequency of the characters is stored in it, then for T we will take another one of size 26 then for T we will take another one of size 26 which will have the frequency of all the characters of T. which will have the frequency of all the characters of T. Okay, nothing to do after that, Okay, nothing to do after that, we just have to see that if the we just have to see that if the frequency of any character in A frequency of any character in A frequency of any character in A greater than height, here I told you here, then we just have to subtract and add to the result. Okay, so for both are of 26 size. Na frequency a is both of 26 Ps Ps Ps Okay, just what we had to see is that Okay, just what we had to see is that if the count under score a of aa, whichever if the count under score a of aa, whichever character is there, its frequency in this eye will be character is there, its frequency in this eye will be greater than the frequency of the count under scotty greater than the frequency of the count under scotty in jo i, okay, then in jo i, okay, then how much extra will we need to t for both of them. how much extra will we need to t for both of them. Minus 2. Whatever value is there in count under s. Minus whatever value is in cow scotty. A simple at value is in cow scotty. A simple at is exactly the same as told. Okay, that's the first way to is exactly the same as told. Okay, that's the first way to code. Okay, now ultimately see code. Okay, now ultimately see what you had to do. Ultimately you have to what you had to do. Ultimately you have to The difference has to be found for a given The difference has to be found for a given character. What did you character. What did you do? The frequency of that character in A do? The frequency of that character in A is equal to the frequency of that character in T, so you are finding the difference of both, so you are finding the difference of both, finding the difference of both, so you are finding the difference of both, right. right. right. No, you do not need to make two different maps, just make one map, no, I am saying make only one map of size 26 and store the difference in it, Now let me Now let me Now let me show you a dry run, so see show you a dry run, so see what example I have taken here, what example I have taken here, like look in A, if there is two B, then there is B, then you like look in A, if there is two B, then there is B, then you can correspond to B. Simply, if there is B in A, then do If it comes then do If it comes then do If it comes then do one more float, then it is okay, then if there is an A in S, then do a one more float, then it is okay, then if there is an A in S, then do a plus and here, this plus and here, this is okay for A. After that, if A comes in t, then make it minus, the is okay for A. After that, if A comes in t, then make it minus, the difference will keep coming out, and what difference will keep coming out, and what else in t, there will be a B. else in t, there will be a B. The The The rest are all zeros. Now look here, pay attention, rest are all zeros. Now look here, pay attention, what does -1 mean? It must have been what does -1 mean? It must have been less in S and more in T, less in S and more in T, so we did not have to consider that case. so we did not have to consider that case. I told you that I told you that if the frequency in S is if the frequency in S is if the frequency in S is less than T means the frequency from T to T, that is why we were adding it in the result. Here what negative means is that for sure its frequency in A must have been less, so So we will So we will So we will not consider the negative one whose not consider the negative one whose difference is positive, nor will we consider only that one difference is positive, nor will we consider only that one and why it came positive because the and why it came positive because the frequency of B must have been more in A frequency of B must have been more in A and we would need extra B in t, and we would need extra B in t, how much would be needed, we would need one, this was the how much would be needed, we would need one, this was the answer, our negative. answer, our negative. answer, our negative. positive ones only, that is, we will add only the positive ones, if it is clear, then just try coding in both the ways in Cps and Java code, you will get exactly the exact similar code. My Git Hub link will Okay, so let's Okay, so let's Okay, so let's code quickly, so let's code quickly, so let's code quickly, first of all, we will do it with our first approach code quickly, first of all, we will do it with our first approach in which we will have taken two maps. in which we will have taken two maps. Okay, first of all, let's find the length, then let's Okay, first of all, let's find the length, then let's take the first map. Map underscore is A26 take the first map. Map underscore is A26 size okay. size okay. size okay. frequency of the characters in A will be ap and t. What will happen in this? What will be the frequency of the characters in T? Okay, so let's fill the frequency of all i 0 Aa Le A Aa P P We will We will We will put the frequency of the character of A in A. Plus plus put the frequency of the character of A in A. Plus plus done but to access the index we are doing done but to access the index we are doing minus A. Okay A minus A. Okay A atty t of Aa's plus plus done. atty t of Aa's plus plus done. To access the frequency index we did minus. To access the frequency index we did minus. You will know all this ready okay int You will know all this ready okay int You will know all this ready okay int E 0 Now look pay attention for int A E 0 A A Lesson 206 A P P Okay now see I told you that if character's if app under s is any character its frequency s is if greater than that comes out i t means whatever t means whatever t means whatever was its frequency at t, then what I did was was its frequency at t, then what I did was result plus e is equal to two, I result plus e is equal to two, I took out the difference of the frequencies of these two, took out the difference of the frequencies of these two, minus t is clear till now, just minus t is clear till now, just what we have to do in the last is to return the result and let's what we have to do in the last is to return the result and let's see after running. see after running. see after running. cases, let's submit the IDs and see, cases, let's submit the IDs and see, after this we will try to solve it with a single map. after this we will try to solve it with a single map. Actually yes, we have solved it, Actually yes, we have solved it, it's okay. Now let's come to the one it's okay. Now let's come to the one map approach, I mean what I said. map approach, I mean what I said. That you have to extract only the difference, so That you have to extract only the difference, so take one map and store the difference in it, take one map and store the difference in it, okay, that means remove this entire map, just okay, that means remove this entire map, just take one map, int mp is of 26 size, take one map, int mp is of 26 size, put zero in it, ok and look in the app. put zero in it, ok and look in the app. put zero in it, ok and look in the app. in MP? Why is it doing minus minus so that the difference keeps coming out simultaneously? Is n't it the difference that keeps coming out simultaneously? Okay, now see, now you All you have to do is add if m All you have to do is add if m All you have to do is add if m p p of a if greater than zero then add the of a if greater than zero then add the result plus e m of a that is datchi and what is the time complex t. What is the time complex t of n because Are doing Are doing Are doing and space is complicated it would be rage in the comment section try to help out see you go in | 2024-03-21 00:19:24 | 1,347 | Minimum Number of Steps to Make Two Strings Anagram | Simple | Intuitive | Google | Leetcode 1347 |
|
Gm-tt6VjT4A | Hello Jai Hind today we will do a question the number of lit code is 290 the name is bud pattern number of lit code is 290 the name is bud pattern ok so in this question we have been given a pattern the ok so in this question we have been given a pattern the pattern is a b b a after that a string has been given me Cat is Dog. Cat is Dog. Cat is Dog. Okay, so we have to find out whether this Okay, so we have to find out whether this string Dog Cat Cat Dog is following this pattern or not. If it is following this pattern then we have to return true. If it is not following then we have to return true. If it is not following then we have to return true. If it is not following then we have to return true. okay, so now how do we know whether it is following the pattern or not, so look at whatever value is at the first position, here is A or if whatever means whatever If so, If so, If so, look carefully to see that there is the same value at the fourth position. look carefully to see that there is the same value at the fourth position. Okay, so whatever value is there at the first position in the string should be the same at the fourth position. value is there at the first position in the string should be the same at the fourth position. Okay, only then the pattern is matching. Okay, only then the pattern is matching. What we are doing is that we need the pattern. What we are doing is that we need the pattern. A B B A pattern is required, it means A B B A pattern is required, it means whatever is on the first position should be on the fourth position whatever is on the first position should be on the fourth position because there is A on the fourth position and because there is A on the fourth position and A on the first position. Okay, A on the first position. Okay, so now let's look at the second example, it so now let's look at the second example, it has B B A but look here at the first position. has B B A but look here at the first position. has B B A but look here at the first position. dog but there is no dog on the fourth position, then it is not matching, it will return false. Okay, so now let's see its time complexity. Before doing any question, what is the time complexity? So the time given by it is The length of the pattern The length of the pattern The length of the pattern is only 300, i.e. 300, so now we can is only 300, i.e. 300, so now we can apply any formula, that is, write any code, apply any formula, that is, write any code, n square n, n4 n square n, n4 n5, everything will work fine, but now we are n5, everything will work fine, but now we are explaining this question for interview purpose, explaining this question for interview purpose, if we assume if we assume if we assume equal to two, then how do we make it 6 to the power of 10, because if this lane of the pattern gives 6 to the power of 10, then we have to make it only in the big of n. Okay, It will take It will take It will take 10 to the power of 6. The lesson is equal to 10 to the 10 to the power of 6. The lesson is equal to 10 to the power of 6. So we need the solution of Big of A. We power of 6. So we need the solution of Big of A. We need the approach of Big of A. need the approach of Big of A. So now first of all let us tell you So now first of all let us tell you how we will make it normal. What will be our approach? how we will make it normal. What will be our approach? What will be the normal of this question? What will be the normal of this question? What will be the normal of this question? question is asked in an interview, if it is asked in an interview, it will not be easy, but it is easy, but it will not be easy, it will be of medium level, make sense of saying it is of medium level, pattern it and If F is added If F is added If F is added then A SQUA will not work. If F is to the then A SQUA will not work. If F is to the power of 10 then A SQUA will work. If F is to the power of power of 10 then A SQUA will work. If F is to the power of 10 then F is 10 then F is greater than F then only Big of A solution greater than F then only Big of A solution will work, not A SQUA. will work, not A SQUA. will work, not A SQUA. work okay, so first of all we are applying the approach, normal approach, brute force approach, so what we will do in the brute force approach is that this is a, we will map it to dog, a is equal to two, we do not write it here, No problem, we will No problem, we will No problem, we will map A to dog, okay, and B will be map A to dog, okay, and B will be mapped to cat, we will run a loop, we will run a mapped to cat, we will run a loop, we will run a loop, and while running the loop, loop, and while running the loop, what we will do is to match all the values, all the patterns, with what we will do is to match all the values, all the patterns, with this value, with the value of the string. this value, with the value of the string. this value, with the value of the string. enter the key values in pairs. Here is our key and here is our value. Okay, then we will run another form, after that we will check what values we have given for each key in the map. Were given two, so is there a dog here in our string or not? Assume that right now we have the position of our aa is ro, so when ro comes, then ro pe, we will first check what is ro pe, is In the map, we In the map, we In the map, we will check whether we have assigned a to our a, then we checked, we will check whether we have assigned a to our a, then we checked, we found out that for a found out that for a a, we have assigned a dog. When a, we have assigned a dog. When a is assigned to dog, then now a is assigned to dog, then now we will match in the string. we will match in the string. we will match in the string. is a dog in our string or not, we can create it in this way at the first position, so we are creating it by brute force approach, so first of all I need a map, so first let's create a map for the Okay, Okay, Okay, new is new is map, okay and what will we do with this string, we will convert this string into So the array of strings I need is string id trm dot space on y We need space on y We need Okay our array is done now what we will Okay our array is done now what we will do is we will run a for loop do is we will run a for loop why will we run a why will we run a for loop we will run because for loop we will run because we will run which is the value of a we will run which is the value of a we will run which is the value of a assign Dog for A, we can assign Cat for B. Okay, so we have to map, a equals dog, b equals cat, so now We will run the loop f int aa e We will run the loop f int aa e We will run the loop f int aa e 0 aa lesson pattern dot length ok a aa plus 0 aa lesson pattern dot length ok a aa plus ps we will ps we will check then we will check first what we do is we check then we will check first what we do is we take out the character so that take out the character so that we do not have any issue so that we do not have to write again and again we do not have any issue so that we do not have to write again and again pattern pattern dot this t so we dot this t so we dot this t so we pattern daughter at aa meaning which character at aa position now aa e g aa position what is which character so i position p aa is character then what will be the value of character c equal to c ea will be Okay, after that what we will do is we will also take out the string, let's take the string 1 equal to a aa whatever is the value now we will check if map what key of content do I want character key Hey character Why do we need the key Y? We need the character A in the map. We are giving A as the key. Neither is C equal to two. Now what is A? So whether we have A in the map or not, they will check the If it is there then do If it is there then do If it is there then do n't do anything. If it is not there then we will have to n't do anything. If it is not there then we will have to give a note. If it give a note. If it is not there then what do we have to do? Map Dot Put will the is not there then what do we have to do? Map Dot Put will the conductor go? Okay, this is our mapping done. conductor go? Okay, this is our mapping done. If I print it and show it then the And let's write something so that we can know And let's write something so that we can know our map. Now our map is ready. Look, we have given dog for A and cat for B. Okay, it is done. Now we will run a loop. Will there be Don't do it, what we have simply Don't do it, what we have simply Don't do it, what we have simply done is that we have run four loops from zero to zero, which done is that we have run four loops from zero to zero, which means left to right, I have run means left to right, I have run OK and have made the zero position match with this, OK and have made the zero position match with this, A is equal to B, A is equal to A is equal to B, A is equal to dog, we have mapped dog, we have mapped dog, we have mapped if map data content is there in the map, if we have a key named vector, see, let's get it drained once, first there is our map, which is nothing right now, it is empty, okay, here So So So we will say that when A was equal to 0, it is now zero, I have we will say that when A was equal to 0, it is now zero, I have zero, then it was zero, even then we were checking zero, then it was zero, even then we were checking that the character is equal to C, that the character is equal to C, we have put it in C, what have we put in C, we have put A in C, we have put it in C, what have we put in C, we have put A in C, now we have put A in C. now we have put A in C. now we have put A in C. pattern Dt K aa whatever character is there on our zero, put it in C, then put A in C. Okay, if we have put A in C, then in the string, we take a string and in which we put this value. Removing the dog this dog so I'm keeping the dog here okay so right now we have nothing in the map when a e was so right now we have nothing in the map when a e was 0 so we check if map d content key c now 0 so we check if map d content key c now what is character c c what is character c c what is character c c we check here whether we have a character in the map or not? Our map is not empty now, then a false will come here. If a false comes, then we should reverse the false because we are If the If the If the false co will become true i.e. when the if false co will become true i.e. when the if condition is true then the entry will be done under condition is true then the entry will be done under and what will it do in the map. What will put do? and what will it do in the map. What will put do? What will put do to c and s1? What is our What will put do to c and s1? What is our c c and what is ave? Dog is equal to map to dog. and what is ave? Dog is equal to map to dog. Will do the same thing on Y. A E dog is doing Y. Will do the same thing on Y. A E dog is doing Y. Then A will be equal. Now Then A will be equal. Now our A E dog has started. Now A will be our A E dog has started. Now A will be one. If I will be one then pattern dot caret I will one. If I will be one then pattern dot caret I will work. So what is the character at the first position. A work. So what is the character at the first position. A now now now pattern D aa is at the first position, what is B, then instead of A, C will become B. C is equal to B character, C is equal to B and what will we do on aa, what is array at aa array, what is cat at We are seeing that the We are seeing that the We are seeing that the first position is P CAT so we will write Y P CAT first position is P CAT so we will write Y P CAT so we need P CAT here. Okay, so we need P CAT here. Okay, now we have checked, now we have to loop check whether the now we have checked, now we have to loop check whether the map contains the content or not, if the character B is map contains the content or not, if the character B is in the map, then the map. in the map, then the map. in the map, then the map. is not there, it is not there, so put this and make it MAC in the key value pair, okay, this is our brute force, okay, now now we have mapped it, now What we have to do is What we have to do is What we have to do is matching means we have to check whether our matching means we have to check whether our pattern and string are matching otherwise pattern and string are matching otherwise we have to run the loop again so to run the we have to run the loop again so to run the loop again we loop again we have to write Y again pattern dat length end i plus have to write Y again pattern dat length end i plus plus now we again plus now we again plus now we again Control C Control and Okay, now we will check that if the array at i is our i position at our array's i position p then let me y then the pattern will not It will run on Y, it will It will run on Y, it will It will run on Y, it will run on map data character and we need ternary operator, we will character and we need ternary operator, we will tell that we are using ternary operator and here we will make false, okay, we will return false, okay, we will return tr on Y. Now look, first of all, we have understood tr on Y. Now look, first of all, we have understood what the first foreloop is doing. what the first foreloop is doing. what the first foreloop is doing. okay, now the second fural, what are we doing, we are going from zero to four, okay, going from zero to four, okay, B is B is B is A and what's in sting is dog is cat cat is A and what's in sting is dog is cat cat is dog okay so now we are checking dog okay so now we are checking first I took out the character first I took out the character here what is the character is A so I here what is the character is A so I put A in C put A in C put A in C put A in C put A in C put A in C now what I'm doing is that in the string we mapped the value which value went to A Which value went to A I'm extracting the value For B, For B, For B, we have kept dog and for B, we have kept cat. we have kept dog and for B, we have kept cat. Okay, keep cat for B, so now Okay, keep cat for B, so now what are we doing from here. Map D, get C, what are we doing from here. Map D, get C, what is the value of C. If it is A, then get the value of character A from the map, then it will come what is the value of C. If it is A, then get the value of character A from the map, then it will come here. here. here. okay, I understand that first of all we have to take the character from here, which character is it, then we have to extract the value of that character from the map, what value do we have for that character? Now we will check In this array, the string of the array which In this array, the string of the array which In this array, the string of the array which we had converted into an array, we had converted into an array, then the dog at the ith position of this array, whatever value we extracted value we extracted is matching with the map or not, where is s1, is matching with the map or not, where is s1, where is the map extracted from? where is the map extracted from? where is the map extracted from? then whatever the value of the map is, is that value matching or not? If it is matching then do nothing. If it is matching then do nothing. If it is not matching Okay, that's why we have used this Okay, that's why we have used this Okay, that's why we have used this pattern operator to see that if we do dot equals true then it will give true then we don't have to do anything. Return Falls are done in Return Falls or Else, work of only one, right, I don't think we work of only one, right, I don't think we can do the work of only one with Ton Rater, so can do the work of only one with Ton Rater, so we have put a note that when this fall comes, please we have put a note that when this fall comes, please give us True when True. give us True when True. give us True when True. false if it is matching if it is coming true then make it false so that it does not enter in f again f if if we talk about done then like let us assume that right now the value of i is zero aa ect is zero and character is equal to a and string aa is equal to dog okay okay now let us check what is the array i array at aa array at zero position what is the value of i what is the value of zero aa what is zero aa zero position What is dog rate zero? What is dog at zero position? Which dot is equal and what is the value of this also? Both dogs are equal. Yes true. When this is true then convert it to false. Operator this is true. Just came here dog Map Dot Get Map Dot Get Map Dot Get Character If one or both dog dog matches Character If one or both dog dog matches then it will be true. When the value will be true, then it will be true. When the value will be true, what will this ternary operator what will this ternary operator do? What will this ternary operator do? It will do? What will this ternary operator do? It will convert true to false. Simple thing, convert true to false. Simple thing, understand that true is false. understand that true is false. understand that true is false. if this loop will not run or if condition will not run again it has come back up again it has come up it has come up then what will happen aa plus plus will happen aa plus Now the value of Aa will Now the value of Aa will Now the value of Aa will become one. Now the value of Aa will become one. Now for Aa we will define the character. Now the value of Aa will become one. Now for Aa we will define the character. First what is the pattern dictor Aa Aaav position. By First what is the pattern dictor Aa Aaav position. By removing the A we will make B and by removing the A we will make B and by removing the dog. removing the dog. removing the dog. c then CAT will come then we will check whether the ID S1 is matching with our name or not. If it is matching then nothing, go ahead, not matching, do it first and Suppose at any time all matches are Suppose at any time all matches are Suppose at any time all matches are made, all matches are made, all matches are made, all matches are made, all matches are made, that is, from left to right from zero made, that is, from left to right from zero index to fourth index, if all is matched, it will be index to fourth index, if all is matched, it will be true every time, it will be true every time, it will be true every time, this is just an operation. true every time, this is just an operation. true every time, this is just an operation. converted to false, then if the condition is not executed even once, then return will not do anything. Return will not do anything, that is, it is matching all of us. When it is matching all of us, then what did we do in the end, we made it Because he is Because he is Because he is matching us all the time, if you don't match us matching us all the time, if you don't match us then he will immediately return false saying then he will immediately return false saying that he is not matching us, so now we will that he is not matching us, so now we will run it and run it and see. Okay, let us run it and see, so our three tests have been successful, When we submit, When we submit, When we submit, look at this, an look at this, an issue will come. Now tell me what issue has come. issue will come. Now tell me what issue has come. Look, tell me the Look, tell me the issue that has come is that when we had assigned A to Dog, issue that has come is that when we had assigned A to Dog, when we had assigned A to D, when we had assigned A to D, then why for B? then why for B? then why for B? what we are just doing is checking whether what we are just doing is checking whether B is in the map of map dot content, if B is in the map of map dot content, if B is not in the map, then B is not in the map, then what to put in the map, put C, put character B, what to put in the map, put C, put character B, and Dr. and Dr. and Dr. Hey, look at both the second positions. Just look at B and Dog. B and Dog. We are matching only one condition here, not if map contains C. If Is it true or not, if there is no B in the map, Is it true or not, if there is no B in the map, Is it true or not, if there is no B in the map, then put Dg in the map and put B, then put Dg in the map and put B, but this is not possible, according to our question, but this is not possible, according to our question, a key can have only one value, a a key can have only one value, a value can have only one key, a key can have only one key. value can have only one key, a key can have only one key. One value and one key, so One value and one key, so A for dog and B for dog, both are A for dog and B for dog, both are not possible, so we have to write a condition here. We have to not possible, so we have to write a condition here. We have to write a condition that write a condition that end end map dot contains contains value C and Y. Now we will value C and Y. Now we will working or not. Do all the three things. Now look, there will be another issue here, there is still one issue, you guys quickly guess what could be the issue. What What What is the issue? Now I am telling you the issue is that is the issue? Now I am telling you the issue is that look at this, it is stuck in this, it is stuck in look at this, it is stuck in this, it is stuck in this, it is stuck in this, this, it is stuck in this, end and not of mapped content end and not of mapped content value is fine, it is good, why will we take character in value, We will We will We will take the string, we are still stuck in this, take the string, we are still stuck in this, so now see what new problem will so now see what new problem will come, it will be successful, it has been successful, come, it will be successful, it has been successful, now we have another issue that the now we have another issue that the length of the pattern is only three and the length of the pattern is only three and the length of the string is four, said four. length of the string is four, said four. length of the string is four, said four. this also has to be written for the edge case. If pattern dot length is not equal to array dot pattern dot length is not equal to array dot length, we will have to simply return length, we will have to simply return false when it is not there, otherwise we will return it, then false when it is not there, otherwise we will return it, then this is our brute force, okay. this is our brute force, okay. this is our brute force, okay. accepted, our brute force is done, our brute force approach is done, this is what brute force approach is done, this is what you are showing us, so okay, we made this with brute force approach, okay, we made this with brute force approach, now we now we want, we are wondering where want, we are wondering where our our [Music] [Music] If our number is 300 less than equating If our number is 300 less than equating 10 to the power of 6 then this brute force is 10 to the power of 6 then this brute force is not going to work because 2n loops will run and will not going to work because 2n loops will run and will give a time limit in some cases. It is give a time limit in some cases. It is confirmed that the time limit is confirmed that the time limit is Given to the power of 10, given to the Given to the power of 10, given to the power of 10, 8, then will the time limit power of 10, 8, then will the time limit why don't we check it right now, we will check what we will do, we will update it, we will remove it from map dot get character, we are doing this thing, we are doing the same thing, Right Right Right here, we are going to put this in Else. here, we are going to put this in Else. Okay, nothing is wrong, in this we will put Else part of Else in this. What, what, what is going on, it is of What, what, what is going on, it is of no use to us, no use to us, we are working in the same loop, we are working in the same loop, first I will run it once and see if it is first I will run it once and see if it is correct or not, so there correct or not, so there should be no problem here, it is fine, it is fine. should be no problem here, it is fine, it is fine. should be no problem here, it is fine, it is fine. accepted okay what's the evidence where's the question where's the quen look here evidence where's the question where's the quen look here what we're doing is when A is what we're doing is when A is B is B is A is A is dog for Dog Dog Cat Cut Dog Okay, so when we are going left to right while Dog Dog Cat Cut Dog Okay, so when we are going left to right while running four loops, running four loops, we did not have A in the map, if A was not there, then we did not have A in the map, if A was not there, then put A, give a value to A, dog, put A, give a value to A, dog, then the value of A is one. then the value of A is one. then the value of A is one. B is not there in our map. If B is not there, then enter B, put the value for it. Now we move ahead, when it happens, we check whether it is there in the map or not and see if it is correct. If it is, then it will What we will do by coming in the form of S is What we will do by coming in the form of S is What we will do by coming in the form of S is that we will directly extract from the map that we will directly extract from the map which character for B we have given which character for B we have given earlier, we will first see that earlier we have given earlier, we will first see that earlier we have given C, we will see earlier we have C, we will see earlier we have given cat for B and we are matching right now. given cat for B and we are matching right now. Everything is matching for Aa E3. Everything is matching for Aa E3. What did we do till Aa Ictu? Till Aa E2 What did we do till Aa Ictu? Till Aa E2 we inserted B E V C to B E V Cat. we inserted B E V C to B E V Cat. When A A E 3 came then we checked whether the map dot When A A E 3 came then we checked whether the map dot content is B or not. For The map already has B, we are B, we are checking here that our new checking here that our new string is coming here. For E3, whether it string is coming here. For E3, whether it is the same value or not, we are is the same value or not, we are checking here whether it is the same value. checking here whether it is the same value. checking here whether it is the same value. not, what we have entered, let's check here whether it is the same value or not, if we check from the map, then we have done all the work here, so our work is going on in the same loop, that's it, thank you If you want to copy then see yours but If you want to copy then see yours but If you want to copy then see yours but do the dragon once yourself, this type of do the dragon once yourself, this type of question can come in the interview, ok then question can come in the interview, ok then thank you so much, ok bye bye Tata. | 2024-03-22 14:24:33 | 290 | Word Pattern 🔥| Leetcode 290 | String | Hashmap | JAVA. INTERVIEWER FAVOURITE QUESTION |
|
O5yxoFS_diY | [Music] hey guys hey guys welcome back to another video and today welcome back to another video and today we're going to be solving the lead code we're going to be solving the lead code question question add and search word data structure add and search word data structure design okay so we need to design design okay so we need to design a data structure which supports the a data structure which supports the following operations following operations we need to be able to add a word and we we need to be able to add a word and we need to be able to search for a word need to be able to search for a word and return a boolean value of whether and return a boolean value of whether the word exists or not the word exists or not so search word can search a literal word so search word can search a literal word or a regular expression so let's say we or a regular expression so let's say we have a dot right so have a dot right so what that means is that it can represent what that means is that it can represent any letter so if you have any letter so if you have a dot we first need to have a and then a dot we first need to have a and then any other letter any other letter so let's look at this example real quick so let's look at this example real quick so we added the word so we added the word bad then we added dad and then we have bad then we added dad and then we have mad mad whatever data structure we have contains whatever data structure we have contains these three words these three words and now we're gonna search whether these and now we're gonna search whether these words exist or not words exist or not so pad does not exist bad does exist so pad does not exist bad does exist and dot a d also exists and what that and dot a d also exists and what that means is means is some letter followed by a d in this case some letter followed by a d in this case we have dad we have we have dad we have bad and matt they all follow that and bad and matt they all follow that and same for same for b dot dot we have b and then two other b dot dot we have b and then two other letters we don't care what those other letters we don't care what those other letters are letters are okay and you may assume that all words okay and you may assume that all words are consists of are consists of lowercase letters a through c okay so in lowercase letters a through c okay so in order to solve this question we're going order to solve this question we're going to be using a data structure called a to be using a data structure called a try try so before we go ahead uh let's try to so before we go ahead uh let's try to explain what a try explain what a try is and how we can use this in this is and how we can use this in this situation all right situation all right so we have a try which is t-r-i-e not so we have a try which is t-r-i-e not t-r-y t-r-y so it's a tree-based data structure so it's a tree-based data structure which is which is the most efficient way in order to the most efficient way in order to store strings and it has a lookup time store strings and it has a lookup time so if you want to look for a word so if you want to look for a word it's going to be big o of l where l it's going to be big o of l where l stands for the maximum length of the stands for the maximum length of the string string right so it's the most efficient right so it's the most efficient structure we can use structure we can use to solve this question so in order to to solve this question so in order to understand understand how this works let's look at a quick how this works let's look at a quick example by example by adding a few words so i'm just going to adding a few words so i'm just going to write a few words and we're going to add write a few words and we're going to add that to that to our try okay so over here i have our try okay so over here i have five words one two three four yeah so i five words one two three four yeah so i have them the have them the boy back and stop okay so boy back and stop okay so let's see how we can add this in let's see how we can add this in a data structure so for every try we're a data structure so for every try we're going to have going to have something which kind of represents a something which kind of represents a master master root so this root is not going to hold root so this root is not going to hold any value any value but it's just kind of there as a place but it's just kind of there as a place we're going to think of it as a master we're going to think of it as a master root which holds everything root which holds everything so now what we're going to do is let's so now what we're going to do is let's say we want to add the first word which say we want to add the first word which is is them we're going to break it up into its them we're going to break it up into its letters letters so first we're going to add t so first we're going to add t then we're going to add h then we're going to add h and we're going to add e and we're going and we're going to add e and we're going to to add m and each add m and each node in a try it's going to have node in a try it's going to have a boolean value attached to it and this a boolean value attached to it and this boolean value boolean value is going to say whether it's an end of is going to say whether it's an end of the word the word or not so what i mean by that is so or not so what i mean by that is so we have t over here it's going to have a we have t over here it's going to have a boolean value of boolean value of false because it's not the end of the false because it's not the end of the word yet word yet h is going to be false e is going to be h is going to be false e is going to be false but once we reach to false but once we reach to m we're going to have a value of true m we're going to have a value of true what that means is the word is just what that means is the word is just what that signifies is that the word what that signifies is that the word ends at the letter ends at the letter m so now we have the letter so we have m so now we have the letter so we have the word them the word them in our try so now let's try to add the in our try so now let's try to add the word the word the so in order to do that the first step is so in order to do that the first step is we're going to go to our master root we're going to go to our master root and see if any of its children have t and see if any of its children have t and t already exists then we want to see and t already exists then we want to see if it has an if it has an h h also exists and h h also exists and it also has e so we already have the it also has e so we already have the over here over here so in order to so we could do one of two so in order to so we could do one of two things things we could make another tree all together we could make another tree all together but that's just going to take up extra but that's just going to take up extra unnecessary space so all we're going to unnecessary space so all we're going to do is do is this over here has a boolean value of this over here has a boolean value of false instead now we're going to change false instead now we're going to change that to that to true and what that means is we have true and what that means is we have a word which is t h e the and we also a word which is t h e the and we also have a word t have a word t h e m them so we considered both the h e m them so we considered both the words in this case words in this case so now let's do the word boy so we're so now let's do the word boy so we're gonna make a new gonna make a new uh branch so it's gonna have the child b uh branch so it's gonna have the child b and we're gonna have o and then we're and we're gonna have o and then we're gonna have gonna have y so we have boy and now we want to add y so we have boy and now we want to add the word the word back so we're going to go to a master back so we're going to go to a master root we already have b root we already have b but b does not have a child node of a but b does not have a child node of a so we're going to add that node so we're so we're going to add that node so we're going to add a over here going to add a over here then we're going to add a c then we're then we're going to add a c then we're going to add a k going to add a k and again i forgot to write it but at and again i forgot to write it but at the ending so these two are going to the ending so these two are going to have the boolean value of true to have the boolean value of true to signify signify that that's the end of the word and that that's the end of the word and finally we want to add the word stop so finally we want to add the word stop so we're going to add we're going to add a child node over here and then you get a child node over here and then you get the point s-t-o-n-p the point s-t-o-n-p so pretty simple and this is going to be so pretty simple and this is going to be the data structure that we want to the data structure that we want to implement and we're going to do so by implement and we're going to do so by using the python dictionary using the python dictionary and now let's just quickly go over how and now let's just quickly go over how will we search for an element will we search for an element and it's pretty simple let's say we want and it's pretty simple let's say we want to look for the element stop to look for the element stop we're going to go to a master root we're we're going to go to a master root we're going to check if going to check if any of his children have the first any of his children have the first letter of the word letter of the word so if there's the s we're gonna go so so if there's the s we're gonna go so then we're gonna change our root note to then we're gonna change our root note to s so now our root note is s s so now our root note is s now we're gonna look for the next letter now we're gonna look for the next letter we're gonna look for t and then we're we're gonna look for t and then we're gonna go to t gonna go to t but so now let's just take an example but so now let's just take an example let's say we're looking for the word let's say we're looking for the word back right we already have it so we're back right we already have it so we're going to go to the b going to go to the b b becomes our root note but like we saw b becomes our root note but like we saw in our example there can be regular in our example there can be regular expressions used so let's say we have b expressions used so let's say we have b dot c k so that means we can have b dot c k so that means we can have b anything and then c k so what we're anything and then c k so what we're going to do is we're going to go to b going to do is we're going to go to b and since there's a dot it can represent and since there's a dot it can represent any letter any letter so we're going to add a and so we're going to add a and o as our parent nodes so first let's say o as our parent nodes so first let's say we go to o we go to o then we then we're going to check for a then we then we're going to check for a c which does not exist so we're going to c which does not exist so we're going to cross this out and then we're going to cross this out and then we're going to go back to our a go back to our a and a c exists and so does a k and a c exists and so does a k so when we have a dot we're going to so when we have a dot we're going to include all of its children nodes include all of its children nodes and we're going to use a stack in order and we're going to use a stack in order to do that to do that all right so let's take a look at the all right so let's take a look at the code and see how that looks like code and see how that looks like so i'm just going to go over and explain so i'm just going to go over and explain the code instead of writing it line by the code instead of writing it line by line since it's a little long line since it's a little long okay so first what i did is i created a okay so first what i did is i created a class called the trinode class called the trinode and this is going to be used to and this is going to be used to represent our try node represent our try node and we're going to initialize it with and we're going to initialize it with self.children self.children and this is going to be an empty and this is going to be an empty dictionary which is going to hold its dictionary which is going to hold its children notes children notes then we're going to have a boolean value then we're going to have a boolean value for is for is end and it's going to be set to false end and it's going to be set to false but if the it is the ending of a word but if the it is the ending of a word we're going to change this value to true we're going to change this value to true so now let's go into our word dictionary so now let's go into our word dictionary class and we're going to initialize it class and we're going to initialize it by calling our root so self.root and by calling our root so self.root and it's going to be it's going to be a trinode object okay and now let's go a trinode object okay and now let's go to to our add root method so over here we're our add root method so over here we're going to have going to have a node and think of this as our current a node and think of this as our current node node so we're going to start off at the root so we're going to start off at the root at at our master root that's going to be our our master root that's going to be our current starting point current starting point so that's going to be the node and now so that's going to be the node and now we're going to iterate through we're going to iterate through each of the letters or characters inside each of the letters or characters inside of our word of our word so we're going to do that with the for so we're going to do that with the for loop and now we're going to check loop and now we're going to check if that character already exists if that character already exists as a children node as a child node as a children node as a child node inside of whatever inside of whatever our root node is so if it our root node is so if it does exist so in this case it does exist does exist so in this case it does exist we're going to make that node we're going to make that node as our current node but if it does not as our current node but if it does not exist what we're going to do is exist what we're going to do is we're first going to add that character we're first going to add that character as one of the children as one of the children and then we're going to make it our and then we're going to make it our current node current node okay and then this is going to keep okay and then this is going to keep going into our for loop going into our for loop and once we reach the last character and and once we reach the last character and we're done with our for loop we're done with our for loop we're going to make whatever that last we're going to make whatever that last node is node is we're going to make its is end value to we're going to make its is end value to be true be true because that the last letter is the because that the last letter is the ending of the word ending of the word okay so now let's go into our search okay so now let's go into our search method method so over here we need to remember that so over here we need to remember that return of the word is in a data return of the word is in a data structure a word structure a word could so we could have a dot character could so we could have a dot character which represents which represents any letter so in order to do this we're any letter so in order to do this we're going to have a stack going to have a stack and in our stack we're going to and in our stack we're going to initialize it with the tuple value initialize it with the tuple value and which is going to first hold the and which is going to first hold the node so in this case we're going to node so in this case we're going to start off with our root node start off with our root node as usual we're starting off with our as usual we're starting off with our root node and then we're going to give root node and then we're going to give it the word it the word and we get the word from the function and we get the word from the function over here okay over here okay and now we're going to go inside of a and now we're going to go inside of a while loop and we're going gonna stay while loop and we're going gonna stay inside of this while loop inside of this while loop until our we have something in our stack until our we have something in our stack until our stack is not until our stack is not empty and each time we iterate through empty and each time we iterate through this loop this loop we're gonna pop out whatever we have we're gonna pop out whatever we have inside there inside there so we're gonna do stack dot pop and over so we're gonna do stack dot pop and over here we're gonna get the node here we're gonna get the node so the first thing is the node over here so the first thing is the node over here and then we're gonna get the word that and then we're gonna get the word that we're looking for we're looking for so i'll just skip this part over here so i'll just skip this part over here and we'll come back to it so now let's and we'll come back to it so now let's go to this statement here go to this statement here over here we're looking at the first over here we're looking at the first letter of our letter of our note and we're checking if that exists note and we're checking if that exists in as one of our children notes in as one of our children notes so if word at whatever is at the zeroth so if word at whatever is at the zeroth element the first letter element the first letter is in node.children then in that case is in node.children then in that case we're going to take a temporary variable we're going to take a temporary variable and we're going to set it equal to that and we're going to set it equal to that node node right and we're going to then add that right and we're going to then add that to to our stack so we're going to be adding a our stack so we're going to be adding a tuple value tuple value we're going to be adding the temporary we're going to be adding the temporary variable and we're going to add the word variable and we're going to add the word now we've already found the first letter now we've already found the first letter so we're going to add everything from so we're going to add everything from the the first index to the ending so to be more first index to the ending so to be more clear we found the zeroth index clear we found the zeroth index and now we're going to take everything and now we're going to take everything from the first index and all the way to from the first index and all the way to the ending the ending okay and now we have one more statement okay and now we have one more statement which checks if we have a dot which checks if we have a dot and in the case that we have a dot we're and in the case that we have a dot we're going to add going to add all of the children notes and this is all of the children notes and this is what the for loop does what the for loop does it iterates through all of its children it iterates through all of its children notes and it notes and it keeps adding them to the stack so we're keeps adding them to the stack so we're going to add going to add all of the children notes to the stack all of the children notes to the stack and we're going to keep popping them and we're going to keep popping them out and keep checking for them now let's out and keep checking for them now let's go back to go back to this if statement that we had in the this if statement that we had in the beginning so beginning so over here we're checking if the word over here we're checking if the word even exists even exists and the reason for that is each time we and the reason for that is each time we go into either of these go into either of these loops we're going to come to a point loops we're going to come to a point where we're going to where we're going to have less and less letters and at a have less and less letters and at a point we're going to point we're going to only return the last letter or we're only return the last letter or we're going to come to a point where we do not going to come to a point where we do not return anything because return anything because each time we're looking at the zeroth each time we're looking at the zeroth index and once we reach the ending we're index and once we reach the ending we're not going to return anything not going to return anything and in that case that means that we've and in that case that means that we've reached the ending of our reached the ending of our word and that could and now we need to word and that could and now we need to check if that is check if that is actually the ending of the word that actually the ending of the word that we're looking for and the way we can we're looking for and the way we can check that check that is we can look for its is and boolean is we can look for its is and boolean value value and if that value is true we know that and if that value is true we know that it's the ending of the word it's the ending of the word so if no dot is n and in that case we're so if no dot is n and in that case we're going to return true going to return true and if none of these case so if we do and if none of these case so if we do not end up going inside of this not end up going inside of this if statement or even if we do and it is if statement or even if we do and it is not node.send not node.send then in that case that means that we did then in that case that means that we did not find the word not find the word and then we're going to return false and then we're going to return false outside of our while loop outside of our while loop so let's submit this real quick and as you can see our code did get accepted and finally do let me know if you have any questions or if you have any better solution to solve this and thanks a lot for watching guys and do let me know what you thought about the video bye | 2024-03-22 10:29:03 | 211 | Add and Search Word - Data structure design | Leet code 211 | Theory explained + Python code |
|
hUBa5GPllo4 | The festival, today we will solve the question, the name of that question is Indian game, chicken name of that question is Indian game, chicken animals, it is a very interesting question animals, it is a very interesting question and very meaningful question, it is and very meaningful question, it is captured and imprisoned in the photo of the captured and imprisoned in the photo of the subscribe, subscribe, so here we put it in the form of one so here we put it in the form of one and this position is last. and this position is last. and this position is last. and Williams Knight was initially in position and Williams Knight was initially in position in the top left room and must fight this book through in the top left room and must fight this book through turns into rescuers turns into rescuers princess and which is our new take which is our new taste pie is princess and which is our new take which is our new taste pie is standing here and standing here and He wants to save this princess, it is okay He wants to save this princess, it is okay that such a team has played a lot of night shelter that such a team has played a lot of night shelter in this edition, this point is represented by in this edition, this point is represented by positive and when you see now in any game, we positive and when you see now in any game, we go, we get nice lines, first of all, go, we get nice lines, first of all, your husband is in life and you are in the game. your husband is in life and you are in the game. your husband is in life and you are in the game. may get power off in between also or our fiber may be less and you should have at least one match with us so that you can save whoever you want to save, so the same is This soldier who is This soldier who is This soldier who is standing here, always keep some initial standing here, always keep some initial life in mind and you have to save the princess located on it, I have one at any point, health I have one at any point, health points 220 and absolutely points 220 and absolutely digest instantly. Now look at any point at any digest instantly. Now look at any point at any point. point. point. gone, Ajay has the sea. Room Guide Pediment Represented by Negative Anti. Surely, some people look at you like this. These negative numbers were telling that the If If If he wants to then he will have to fight with Hindi MNS and then he wants to then he will have to fight with Hindi MNS and then move ahead, so it is quite interesting, move ahead, so it is quite interesting, no question exam, as yes means no question exam, as yes means we have to start from here, then we have to start from here, then save the prince and interesting save the prince and interesting tears, Nike shoes health upon entering, should I enter another tears, Nike shoes health upon entering, should I enter another room? room? room? increase the white health and going to the room of tongue will either be empty or there will be some power off in them which will either increase our health and then you will get power. Chunri Spring Sad is the Possible, now what you have to do is to Possible, now what you have to do is to Possible, now what you have to do is to reach the princess as quickly as possible. The reach the princess as quickly as possible. The chicken may decide to move only the chicken may decide to move only the light board and download these inches of tape because the light board and download these inches of tape because the prince has one side so small, okay, only to the prince has one side so small, okay, only to the right and will only right and will only go downwards and go downwards and go downwards and means there is a need to start from here so that here 250 hours and temperature means if you can get it in some form temperature means if you can get it in some form then I can be a little or then I can be a little or can you get anyone that can you get anyone that subscribe then it subscribe then it will be a question statement piece jewellery. will be a question statement piece jewellery. will be a question statement piece jewellery. then we are the givers here. Okay, this is the then we are the givers here. Okay, this is the exam on pimples which was given to us on the lift, exam on pimples which was given to us on the lift, here is the smooth one and the answer to it is here is the smooth one and the answer to it is our seventh. Now how can you see, I am here, my soldier, who has to be saved, we are standing here. Our princess captured here in this channel is fine, now save some minimum health extension health of this soldier, meaning he should be here. Hey Jab Jab, I gave you a game, right, meaning you have this school, 9 inches Here this is a princess and you have to Here this is a princess and you have to Here this is a princess and you have to save the prince, so at least how many save the prince, so at least how many can you save in this, there is one in this, you can you save in this, there is one in this, you can save, so I accepted that by the time we can save, so I accepted that by the time we come here, Chunat's life is like a come here, Chunat's life is like a bird, so bird, so now we can at now we can at least least least got it first in power, got it, so it got it first in power, got it, so it had power in it, out of that - 1, so now it can be said from here, look, if he decided, then he can do it in height, so If I can get up, then I got If I can get up, then I got If I can get up, then I got him more rights, then he got more kudis, him more rights, then he got more kudis, here his power has reduced by another - 3, here his power has reduced by another - 3, of course, then I moved him further right, of course, then I moved him further right, so see, now his power has increased so see, now his power has increased and here he and here he and here he which increased its power. Okay, now I took it further down and its power increased further. Okay, now finally I reached the place where the princess is imprisoned, it is called our princess So if he is slow then he will have to fight, if he has to So if he is slow then he will have to fight, if he has to So if he is slow then he will have to fight, if he has to fight, then his power will be many - he fight, then his power will be many - he has become white and if I total all these then has become white and if I total all these then Yoga - Pick. Okay, now what will happen now, Yoga - Pick. Okay, now what will happen now, wherever the soldier has reached here, wherever the soldier has reached here, he will have to give this princess. he will have to give this princess. he will have to give this princess. then at least he should have an oven, if not an oven, there should be work in Indian Health. So let's say that the knight had gone out with some extension health. Okay, on the way he also got power off. I found something in my mind due to which. Whatever power she had, it has been bought to some extent, that means look here, whatever by-power she has, she can also get it and from the power she has left, it can be long and how much should be left in the end, at least the power of It It It should be safe and sound, okay, so this mark here should be safe and sound, okay, so this mark here is laxative is laxative a six - what is six here - a six - what is six here - this is the power that has been spent this is the power that has been spent because it has been spent in reaching from this year to this year, because it has been spent in reaching from this year to this year, chicken and chicken and Rather, we have at least some Rather, we have at least some health here, which is that at the health here, which is that at the end of this night, end of this night, how much will this one chicken be consumed, it is how much will this one chicken be consumed, it is absolutely true that absolutely true that it is 9:00 in the morning, right, we have at it is 9:00 in the morning, right, we have at least a second to it. least a second to it. least a second to it. so that he can save this princess and secondly he can also have infinity. If he goes with these final powers then he will save her. Okay, so I thought that the question statement is a layer here, I am trying to explain it once more. I would like to say that Monsoon, we have only one salary and there is some tan stop in it. Okay, so here this is our soldier and here is our princess pier. Okay, so you here, here is the mark of leg set and For this, at least how much For this, at least how much For this, at least how much health does she need? Now as if there is an health does she need? Now as if there is an entry in her room, what can happen to her, entry in her room, what can happen to her, either she can have a power game or she either she can have a power game or she can go crazy, so see here her power has been launched, there is can go crazy, so see here her power has been launched, there is tension and this. tension and this. tension and this. here we made it equal to one because at least whatever power is required, whatever power should be left, how many policies should be made to save the princess, then what is the minimum initial requirement, what is the level, it is definitely there, so This was our problem This was our problem This was our problem statement. Okay, now we will see how to statement. Okay, now we will see how to do it do it and I will share one more thing and I will share one more thing before explaining the problem. Suppose here it is before explaining the problem. Suppose here it is called princess and here we have power stop called princess and here we have power stop we have Munchkin Knight okay we have Munchkin Knight okay so now you so now you so now you Because here what will happen is that its bake Because here what will happen is that its bake power will increase. Okay, so power will increase. Okay, so in this case you will mix one ray, in this case you will mix one ray, why at least how much of it is needed so that you why at least how much of it is needed so that you can save. can save. Okay, so these were our new ones and they have Okay, so these were our new ones and they have some ex. some ex. some ex. he started walking, so now he will start from this year, okay, he will be here, so he started walking, now give him a pass from here, either he is walking here or he should Okay, so we are Okay, so we are Okay, so we are going towards the right first. Okay, now we have reached here, so from here, he should either go this way or from here, he should either go this way or where is he going to go down, so we just went to the night, okay If we go outside this prison, we have reached If we go outside this prison, we have reached If we go outside this prison, we have reached here, we have here, we have reached outside the prison, here we have moved ahead, then reached outside the prison, here we have moved ahead, then we will do something very big from here, now you will say that this above means that we have now you will say that this above means that we have accepted that accepted that accepted that one at this point then he should have a lot of help only then he will be able to save the princess oh when he is so you are okay and you had sons okay okay that you have money that you have money How much money will you need, you will How much money will you need, you will need more money than Dada, so need more money than Dada, so why is it that whenever it is night, he came out of our tandem and he does why is it that whenever it is night, he came out of our tandem and he does not even know his destination, not even know his destination, then how much minimum energy will he need, maximum then how much minimum energy will he need, maximum energy? energy? energy? we have made the maximum return here, it is okay, it has happened, now look at the chickpeas from here to there, if you put it from here, now it is his, what option does he have, now he only has the Okay, Okay, Okay, now where will he go from here, now where will he go from here, he would go to the right, but what is he would go to the right, but what is our turn here, life is not the only thing, Warden our turn here, life is not the only thing, Warden will go outside since birth, so here he will will go outside since birth, so here he will need maximum initial help. need maximum initial help. Okay, now where should we go from here? Okay, now where should we go from here? Okay, now where should we go from here? and what has he got, he has got a princess here, he has a princess here, okay, I am a princess here and if we accept that your problems are only this much, okay here we And you have to save this prince, And you have to save this prince, And you have to save this prince, okay, at okay, at least how high is your health, your least how high is your health, your minimum health should be one, okay, so I have minimum health should be one, okay, so I have accepted here, on this channel, I have seen that accepted here, on this channel, I have seen that whichever knight has at least this or that health. Torch should be switched off and should be avoided absolutely and that we had accepted the uniform policy of our night's nation help, so one by one Aplus that by equal to one will be I 1 teaspoon note granite's initial help denotes Roy's deleting this Hey bye this is 24 oil from this Luck only note side and see previous answer Here friend you can be power or what can happen can be oppression Okay so now here I have given us what I have given 1 And at least below how much health should And at least below how much health should And at least below how much health should his bandh be saved, only then he can his bandh be saved, only then he can save the principal or it is activated or save the principal or it is activated or fixed with us, fixed with us, okay, so here, okay, so here, how many how many units should be there for his pension help? Hey, when we have so much units should be there for his pension help? Hey, when we have so much This is the problem, there is so much problem and if the knight has to This is the problem, there is so much problem and if the knight has to save the springs sitting here save the springs sitting here then at least he will have six health but he will go then at least he will have six health but he will go so that he can save this prince properly, so that he can save this prince properly, so what is our so what is our education knowledge required here education knowledge required here that Abu from here I had vitamin Ajay and how much health did he return with, 6 health but it was okay that he returned, now look at us at least the value of our thinking means when we are on this channel, Value Value Value is is education education and bike, from here we mean skin problem, if this problem has happened then tell that this problem has become only this much, it is okay that this problem has become only this much, it is okay and this will take some health of our night, so at and this will take some health of our night, so at least how much help will he get from here. least how much help will he get from here. Since Yogi is in this world, he would need at least five health so that he can save the one who is a princess here. Okay, so see, if we Okay, so see, if we take him from there to here, he take him from there to here, he got the power of power, then five plus one for him here. got the power of power, then five plus one for him here. got the power of power, then five plus one for him here. how much did it become, she became alert and when she freed herself from it, she got life, then she used only this pipe in her power, ten-five, what did she do with the power she had, from her health, she took this Used it to take away life and Used it to take away life and Used it to take away life and in the end, how much help does it have, child mind, in the end, how much help does it have, child mind, child, child, why did I arrest the princess? Okay, why did I arrest the princess? Okay, so our initial help here is so our initial help here is how many wars are there now, how many wars are there now, what will we do for amazing positive, let's see now see. what will we do for amazing positive, let's see now see. Now what do we go back from here, from here Now what do we go back from here, from here we got five and from here we have we got five and from here we have increased the maximum volume, so this message has been increased the maximum volume, so this message has been minimized, out of this, we have hit the minimum file, that minimized, out of this, we have hit the minimum file, that is, where whatever help he has given to is, where whatever help he has given to many celebs of the child, how much will be the smoothness of the files. many celebs of the child, how much will be the smoothness of the files. So now we are one Nepal so Will give, absolutely good, okay, now he can't go down from here, so who will go down even once, okay, so he went down from here, now from here it can be said, from here, he can go right, of We have already We have already We have already gone and we know that to go to this cell, gone and we know that to go to this cell, if we go to this oil, then if we go to this oil, then we will need at least five initial we will need at least five initial helps, then we will simply helps, then we will simply return the face here. Absolutely, return the face here. Absolutely, see the world. see the world. see the world. and then now we went below, if from here we can go here, we can go here, we can go right, but we know about this, here the prince should go and We need We need We need help, we need six, so help, we need six, so what did we take from here to what did we take from here to tell the answer, here we need city for six, we went below A and checked because there we went below A and checked because there was a call left below it, so it was on the floor. was a call left below it, so it was on the floor. was a call left below it, so it was on the floor. outer came out and what happens when it comes out we need maximum hills okay so now look you need at least initial help so on one side is coming here maximum and on one side now now you are here you are here you are here say if your problem was not only that here is sour food and power and here is the princess and you are miles tow and you are taking something obscene then what is the It should be stopped, it should be It should be stopped, it should be It should be stopped, it should be made, because look made, because look here, what is the condition of our what is the condition of our power of military and whatever power of military and whatever help we have, how much is it, help we have, how much is it, you are a doctor of one night, Ours will be - 54, we should have at Ours will be - 54, we should have at Ours will be - 54, we should have at least minimum initial health to least minimum initial health to save the knight's prince - 1304, then my note will die, so I - 1304, then my note will die, so I - can you take it, can't you at all, so why am can you take it, can't you at all, so why am I here? I here? I here? Om Shaam, when my problem is only this much, then what should be my one, take at then what should be my one, take at least one question about the health of the state, that least one question about the health of the state, that means it should be okay, then I will do it means it should be okay, then I will do it from here, okay, On one side we need white heads, On one side we need white heads, On one side we need white heads, ok, and on one side we have one and here is our dimple, so out of these two, we will fry. Now you will say why are we taking minimum here, This is our bread, it's okay, now we are leaving from here This is our bread, it's okay, now we are leaving from here and like this, go here to the prince, promote and like this, go here to the prince, promote it, something of yours it, something of yours and a sensor update is being detected in it, it is okay and a sensor update is being detected in it, it is okay and you are leaving from here, go here and and you are leaving from here, go here and save the princess. save the princess. save the princess. help here, okay, now I am saying that you need at least minimum health one to save this princess, okay, and whatever action of ours is smaller than a mobile, and I are one. and I are one. and I are one. will say that why are we taking the minimum here? When we have reached here in about one and we have reached here in one too, then what is the meaning of taking the minimum here? Even in India, we are Even in India, we are Even in India, we are not able to access these air services not able to access these air services and if I start my point and if I start my point here then see if despite this virus, here then see if despite this virus, we are able to reach there at least in health and we are able to reach there at least in health and in this too, at least X-ray is also available. in this too, at least X-ray is also available. Where are we able to reach with less health then Where are we able to reach with less health then X is equal by but here it is X is equal by but here it is not so and we not so and we need at least one health to save this princess so what will we need at least one health to save this princess so what will we take, we will take From where From where From where we need minimum hairs, from where we need we need minimum hairs, from where we need minimum initial health minimum initial health milk, so we have taken one, it is milk, so we have taken one, it is making here, so we have taken one, so making here, so we have taken one, so Express Express 8 - Tass is equal to one neck oil introduction, neither 8 - Tass is equal to one neck oil introduction, neither all the p all the p Energy is one of his salary messages, whatever amount of Energy is one of his salary messages, whatever amount of energy he can take from power off or energy he can take from power off or whatever amount of energy he can access, if whatever amount of energy he can access, if we look at all of them, his pension should be health 11:00, we look at all of them, his pension should be health 11:00, medical here, so medical here, so what have we given it from here, label what have we given it from here, label what have we given it from here, label okay, now look at this point, hmm, okay, at this point, when we went to the right, how much energy did we have left, you got saved and when we went down, how much energy did we have, the level is So here we are, at least among these two, where are you in health? So, accessibility has been achieved, that is, if I am on this channel, then I will need at least five help. Five will be needed so that I can Okay, now we're here on Okay, now we're here on Okay, now we're here on Spain okay that if I go to the right you're my that if I go to the right you're my five energy that baby if I go to the right five energy that baby if I go to the right and if I go down and if I go down and if I go down see how much we will save, so we went here, okay, from here, we went like this, from here, we got into the forest, from here, we went further down, when we went to the right, from here we always got monkeys, When we give it, then When we give it, then When we give it, then from here we have got the maximum, so one. Now let from here we have got the maximum, so one. Now let me explain back to the point, here me explain back to the point, here we have a power and it should be used to save this earth because it should be minimum so that is why we have here. why we have here. why we have here. that the power it is getting here is okay that the power it is getting here is okay and at least how much health should have been saved, and at least how much health should have been saved, fish is needed. Okay, so where should a Meera fish is needed. Okay, so where should a Meera phone go, that means nation help. phone go, that means nation help. phone go, that means nation help. least how much forest can be there, only then we can save the princess, what have we got from here, we have got it, of course, now look what is here, 8 - the pipe is fine and with its help, how much should have been If he If he If he see me here, when I want to be on the two, I am on this one, it's okay, I am on this one, it's okay, I know if I go down, I know if I go down, what time will my life come, what time will my life come, A six will be left, it's okay if I go to the right. A six will be left, it's okay if I go to the right. A six will be left, it's okay if I go to the right. I go there, I will have five lives, so if I start from here, then minimum minimum nor if that that when he starts moving from here with Civil Lines, then when he starts moving from here with Civil Lines, then neither neither neither then how much life is left for him? If he goes to this group, then how much will his life be? When he goes here, he will lose his power. He will get power He will get power He will get power off, his life will be this much, it will off, his life will be this much, it will be fine and when he goes here, he will have to be fine and when he goes here, he will have to fight with the domain, so out of the fight with the domain, so out of the total energy he has, he has total energy he has, he has spent at least five energies and at the end he has spent at least five energies and at the end he has one energy left. one energy left. one energy left. remains alive so here the and tell me and tell me that you I think you must have understood here that you I think you must have understood here that I have that I have kissed health equal to 16 121 here kissed health equal to 16 121 here maximum curator maximum curator maximum curator expression will be shared in many stoves. Before looking at one more thing, here the date of our 'A' overlapped, all these problems also came due to which If If If we have already visited, then look at it again as secure and if we have already visited, then look at it again as secure and if our parameters are changing, then our parameters are changing, then here we are changing only the columns to here we are changing only the columns to move ahead and if we are not changing anything else, move ahead and if we are not changing anything else, then we can tell the things here. then we can tell the things here. What will our DP become here? Here we Ritu What will our DP become here? Here we Ritu Dipper said whatever changing parameters according to the Dipper said whatever changing parameters according to the changes parameters and whatever we have changes parameters and whatever we have in the column is okay, now we look at its boot so I said that here these so I said that here these Rohit 120 for these Rohit 120 for these Qualified heroine or set a meaning of Qualified heroine or set a meaning of stupidity and banani. See, I have made a to-do list for you. I have made it a friend's digest of the mind and a share digest. Why have I made this because at the most, that night should be kept If we have to reach then we are If we have to reach then we are If we have to reach then we are fools, how much contract do we have fools, how much contract do we have with the laborers of the districts, it is clear that we have to do it, okay, with the laborers of the districts, it is clear that we have to do it, okay, I I am India and where I called a rescue function am India and where I called a rescue function in which I sent what I sent to our in which I sent what I sent to our Qureshi Arup, gave the volume again Qureshi Arup, gave the volume again and daughter. and daughter. and daughter. look where we can go, if we can go to the right, then I have created one of these websites and have called the reception. To go to the right, what will happen to the right? And And And sent to the duty, it is okay sent to the duty, it is okay that now it may be moving in chloride and may that now it may be moving in chloride and may not even come out at our destination not even come out at our destination then how should we see it. If my room has then how should we see it. If my room has become greater than the physical two-year dot size, is it okay become greater than the physical two-year dot size, is it okay or is our fall or is our fall great reluctant? great reluctant? great reluctant? that last week here when camor came that last week here when camor came out of our ton, what does he out of our ton, what does he need, he wants more and more energy, so need, he wants more and more energy, so I returned from here, he I returned from here, he came on the road, it is fine and this hair is now zero. came on the road, it is fine and this hair is now zero. Only and apart from that, it can be said that it can go down, okay, so now I have 1 inch extra here and 1 inch extra here and this will get minimum ho the this will get minimum ho the right for download with four days note right for download with four days note is available. is available. Pull this one and delete it, which follows the minimum Pull this one and delete it, which follows the minimum balance which will go down in that knight's balance which will go down in that knight's place or place or we may have cases, meaning meaning that witch lord is that witch lord is a block of plots, that idiot a block of plots, that idiot will go up the mountain with the clock, meaning with will go up the mountain with the clock, meaning with will go up the mountain with the clock, meaning with look here also, go here and look and on both sides, he needed so much help, he needed to play with the bunny, okay, that's why I wrote it here, then we will put it here, we will fold it like this, it means that She is and here is the princess. At She is and here is the princess. At She is and here is the princess. At least she needs a like least she needs a like so that she can be a I can save the princess okay what can you do now *Let's make the result what can you do now *Let's make the result okay President Minor okay President Minor Why not, we will make this corner from inch, we will Why not, we will make this corner from inch, we will make initial health and initial equal to how much it will make initial health and initial equal to how much it will say, say, whatever is our HI, from the whatever is our HI, from the lock which is presented, lock which is presented, how much energy will it get there or how much energy will be consumed by it - we will do it only how much energy will be consumed by it - we will do it only then our then our then our here, so whom does this expression delete, so now what can happen is that now whatever his initial health effects will get inclined towards me, what will happen in negative, will he be able to kill, so at least how much We need a ribbon, it is ok, otherwise what can happen, the more successful it is, the more successful it is, and if we have any problem, it is already and if we have any problem, it is already calculated, a little more probe, calculated, a little more probe, hall notice will be Tweet - 6, then from there hall notice will be Tweet - 6, then from there we will return the BP off. we will return the BP off. we will return the BP off. flowers are the only place where Ma'am is ki Bollywood It happened that our answer is coming right then it was our answer is coming right then it was from simple comfort that this Manjan Giver is not a difficult thing from simple comfort that this Manjan Giver is not a difficult thing which we only had to see that if it is in which we only had to see that if it is in this this this now we just had to see that if he now we just had to see that if he wants to save this princess, at least wants to save this princess, at least his health should be 1954 so that he his health should be 1954 so that he can save the prince, which of these we used can save the prince, which of these we used and and and you understand the question players, if you have any doubt related to this question, please write in the comment section, please write in the comment section, we will definitely answer. Thank you so we will definitely answer. Thank you so much and if you liked the video. much and if you liked the video. much and if you liked the video. please like and share this video and do | 2024-03-21 14:10:56 | 174 | Dungeon Game || Leetcode 174 |
|
42_nvSsPA_s | hi everyone my name is course again today i'm trying to solve the uh september liquid challenge well now the problem is number we character in the game so basically what is that you are playing a game that contain multiple character and each character has a two properties that is attack and defense so you are given the two integer added properties for properties i there is a two component that is attack and the defense it represent the add character of that value so a character is said to be weak if any other character has both attack and the defense value is strictly greater than the other character attacks and difference value so more formally that when the attacks of attack value of j is greater than attack value of i and the defense value of j is greater than uh defense value of i in that case that will be the weak character in this game so we'll have to return the number of character has been present in that total game so fast i'll dry run on the then after i'll try to make that coding interpretation so first i will try to check that 1 5 10 4 and 4 3 1 5 1 5 10 4 so basically what i'll do that i will so basically what i'll do that i will make a custom shot basically custom sort make a custom shot basically custom sort because uh there will be two cases here because uh there will be two cases here basically uh basically uh basically there is the this is the basically there is the this is the attack condition uh attack value and attack condition uh attack value and this is the this is the uh difference volume uh difference volume that is there so when that is the i is that is there so when that is the i is greater than j in that case there is greater than j in that case there is also i and that is suppose that j so if also i and that is suppose that j so if there is a greater than that so in that there is a greater than that so in that case that will be uh computed as the case that will be uh computed as the uh weak character so that is why we will uh weak character so that is why we will have to check that have to check that uh making a custom shape so cast in the uh making a custom shape so cast in the custom shot basically i will run there custom shot basically i will run there basically basically according to the according to the greater value of the attack character greater value of the attack character that is 10 4 that is 10 4 and and 4 4 3 3 and 1 and 5. so what happened that and 1 and 5. so what happened that so basically if i'll do that there will so basically if i'll do that there will be no required to check that there will be no required to check that there will be no required to check that that will be no required to check that that will be the automatically because that is the be the automatically because that is the greater the greater value there greater the greater value there that is the greater value that is the greater value that is the greater value in each case when i have been going to the down case basically from the height i have been iterating to the end so at that condition we'll have to check that we'll have to check that i am taking a variable that is supposed as a temp so that is minus infinity so when the value has been passing through there when there is a that is the value will be passing through that in that case in that case it means that when the value is the if temporary value is greater than the the current value that's the pointer so what is that the properties of i and the there is a one basically so what happened that in that case whatever that that will be that uh the minus that is also taking as an account basically in that case basically when that is the value will be the greater than that in that case the value will be updated into there but otherwise case otherwise case when when the that value is greater than that that is the condition where it's fulfilling the i is greater than that attack of i is greater than attack of j and the difference of i is greater than a difference of j so in that case i will update it or increment the answer value by 1 and after that when the traversal has been all or completed then after that i so basically so basically there's the custom there's the custom short function there will be required to short function there will be required to do that so in that case i do the custom do that so in that case i do the custom short so in that case the time short so in that case the time complexity will be order of n log n complexity will be order of n log n where n is the where n is the uh uh length of that total array and the space length of that total array and the space complexity will be complexity will be i'm not taking any extra space so i'm not taking any extra space so basically the order of one is the space basically the order of one is the space complexity for that case and time complexity for that case and time complexity here for the n log n and this complexity here for the n log n and this is the order of one case is the order of one case so so uh uh first of all i'll have to repeat that first of all i'll have to repeat that condition one more time 10 4 4 3 and 1 5 condition one more time 10 4 4 3 and 1 5 what happened that basically basically what happened that basically basically that is the decreasing order so attack that is the decreasing order so attack is already greater than the previous one is already greater than the previous one i mean that next value not previous so i mean that next value not previous so when there is a column here the already when there is a column here the already previous one is greater than that previous one is greater than that if if the previous value if the minimum the previous value if the minimum condition value minimum value what the condition value minimum value what the minimum value will be updated there if minimum value will be updated there if the minimum value is greater than the the minimum value is greater than the current current the the defense value greater than the divisible defense value greater than the divisible it means that that is fulfilling the it means that that is fulfilling the criteria of the weak character so in criteria of the weak character so in that case i have been increasing the uh that case i have been increasing the uh the answer variable there and otherwise the answer variable there and otherwise case that will be updated into the temp case that will be updated into the temp variable variable so that is how i am trying to implement so that is how i am trying to implement my logic so right now i am trying to my logic so right now i am trying to implement my logic as a coding implement my logic as a coding interpretation interpretation so basically first i'm making the custom so basically first i'm making the custom shot shot so so static integer and percent and and first we'll have to check that the logic first we'll have to check that the logic if if if um a of 0 is equals to a of 0 is equals to b of 0 in that case i will return the b of 0 in that case i will return the a of 1 less than a of 1 less than b of 1 that will be the shorting order right and checking there that is what is happening that that is not uh to be the mentioning there so what is happening that return there as a return there as a i of 0 is greater than b of 0 so that i of 0 is greater than b of 0 so that will be the upgrading as a will be the upgrading as a the greater format yeah so first i'll short that area basically properties properties properties obtained obtained and and the cmp the cmp now my sorting will be done i'll have to now my sorting will be done i'll have to check that as in the temporary variable check that as in the temporary variable what is that what is that that is that is mean infinity i mean that mean inch sorry that's now that's now completing this so for completing this so for auto p of the properties that will return the vector basically part is so after that if my p now i mean that uh the temporary variable i mean hold on i mean hold on uh what's the logic there basically what is the value yeah that's the logic behind hold on i'm updating that if that value okay okay yeah got it okay okay yeah got it when when tmp is greater than tmp is greater than i mean that less than sorry not greater i mean that less than sorry not greater than than so p of so p of 1 and after that that is a temporary 1 and after that that is a temporary variable will be become p1 variable will be become p1 otherwise otherwise otherwise case that the answer value otherwise case that the answer value will be incrementing there okay will be incrementing there okay i'll have to also i'll have to also initialize the value there initialize the value there and after that all the traversal has and after that all the traversal has been done then after that i would return been done then after that i would return the answer so let me check that my logic the answer so let me check that my logic is correct or not when that is goes to there when that is goes to there is basically is basically that will have to do that it is going on that is when a both of them has been fulfilling their criteria when there is a fulfilling of that criteria it means that that is the a1 and the b1 and otherwise case that will be the age 0 and the greater than b0 okay that has been already fulfilling and then after that properties begin properties in an integer mean and the answer will be there and after that the when first wallet check that first wallet check that suppose suppose both case both case the properties are there that the value the properties are there that the value will be and that is accepted there and that is accepted there but what happened it's giving me one more than that okay first we'll have to check that which is the value has been greater than there suppose we'll have to check that the reverse logic there the value has been less than that in the value has been less than that in that case i will be the updating there that case i will be the updating there and otherwise case that will be updating and otherwise case that will be updating into their temporary is equal to p of 1 into their temporary is equal to p of 1 so that will be the case for there so so that will be the case for there so let me check that i think that will be let me check that i think that will be the correct for there that is accepting for this so right now yeah it's got accepted yeah it's got accepted thank you so much thank you so much [Music] | 2024-03-25 12:30:19 | 1,996 | 1996. The Number of Weak Characters in the Game September Day - 9 |
|
4O7baTU2ZeQ | hey what's up guys uh this is sean here so this time uh lead code 1851 so this time uh lead code 1851 minimum interval to include each query minimum interval to include each query all right so this one is another query all right so this one is another query problem right okay so you're given this problem right okay so you're given this time you're given like a 2d time you're given like a 2d integer array intervals you know where integer array intervals you know where the intervals have like the intervals have like has a left and right and describing the has a left and right and describing the starting point starting point the starting point and the the ending the starting point and the the ending point point and the size of the interval is it's of and the size of the interval is it's of course is the is this course is the is this and then you're also given like integer and then you're also given like integer array of array of you're given like a k queries right and you're given like a k queries right and for each query there's only one element for each query there's only one element right which means that you know we want to find the smallest interval such that you know the query number is inside that interval if there's no such interval exist and we simply set the answer to -1 right so for example we have this four intervals we have one this four and then the queries we have is two four two three four five so for query two here right how many uh candidates how many intervals available candidates we have here we have we have two right we have this one four and among those kind of two intervals uh and among those kind of two intervals uh we choose the one who has the uh the we choose the one who has the uh the smallest intervals smallest intervals which is this two four because because which is this two four because because this one four minus one plus one this one four minus one plus one is is four right this one is three is is four right this one is three that's why you know this one is also that's why you know this one is also four this one is one right four this one is one right this is the the size that's why we have this is the the size that's why we have three three and then for three same same thing since and then for three same same thing since three are also inside three are also inside these two intervals and we also get these two intervals and we also get three here and then for four three here and then for four right uh so four okay so four is also in uh so now it's four is as you guys can see four is inside all four intervals and and this this one is the smallest one that's why we return one here and for but in terms of five right when it comes to five five actually only uh in uh is in this one interval which is three to six that's why we so that's the the description for this so that's the the description for this problem you know problem you know again right for this kind of query again right for this kind of query problems you know and problems you know and usually the constraints is of a usually the constraints is of a pre-standard 10 to the power of five pre-standard 10 to the power of five which means that we cannot for each of which means that we cannot for each of the queries the queries we cannot have that luxury you know you we cannot have that luxury you know you know know to scan all the intervals to scan all the intervals right because that will obviously be a n right because that will obviously be a n square time complexity square time complexity and which will lead a tle that's why for and which will lead a tle that's why for this kind of like this kind of like k query problems we always need to sort k query problems we always need to sort this query this query one way or the other and then we also one way or the other and then we also gonna have to sort gonna have to sort the source data here so that the source data here so that we don't have to consider basically we don't have to consider basically check the same check the same element repeatedly element repeatedly for the same for different queries here okay and for this problem i for this problem actually is even simpler because you know first the queries only has one element which means that we there's we only have one options we either we just sorted right and then we have to consider right how can we uh code make uh write the code so that we don't have to these intervals multiple times so for this problem you know i think so for this problem you know i think it's it's also kind of it's it's also kind of kind of straightforward you know uh we kind of straightforward you know uh we see we just also need to sort these see we just also need to sort these intervals intervals by its starting time okay which is the by its starting time okay which is the natural sorting natural sorting order here and if we do that order here and if we do that okay so okay so every time you know we have like every time you know we have like intervals intervals you know let's say we have a query and you know let's say we have a query and we have intervals let's say we have we have intervals let's say we have intervals like intervals like 1 to 4 right 1 to 4 right and this is a sorting order basically and this is a sorting order basically and we have one at this interval and the and we have one at this interval and the query is two query is two so the query is two and we just need to so the query is two and we just need to check check if this connect if this uh starting time if this connect if this uh starting time is either equal smaller than 2. if that's the case we know okay so this interval might i mean not necessarily right might include include this so that we can uh check this interval so that we can uh check this interval right right and if this one doesn't and if this one doesn't satisfy this these two can do doesn't satisfy this these two can do doesn't include this courage include this courage we can simply ignore this one we can simply ignore this one and we don't have to uh consider this and we don't have to uh consider this one again one again when we process another query let's say when we process another query let's say for example three for example three or four or five and why is that because since the later since the rise of queries are all bigger right so which means that you know if right so which means that you know if this interval doesn't include this interval doesn't include will not include two which means that will not include two which means that you know uh the only you know uh the only if this one doesn't include two maybe it if this one doesn't include two maybe it means that you know this one means that you know this one uh probably it's gonna be a uh uh probably it's gonna be a uh one one one one right or zero one one one one one right or zero one right this is the only two options that right this is the only two options that will not include this one will not include this one since are using this kind of like since are using this kind of like starting time right to include starting time right to include at starting time to sort these intervals at starting time to sort these intervals and if if this intervals cannot include and if if this intervals cannot include two here we can we don't we will we two here we can we don't we will we we're not going to check that for the we're not going to check that for the for the 3 because 3 is greater than 2. for the 3 because 3 is greater than 2. if it cannot include 2 if it cannot include 2 it would not if they would definitely it would not if they would definitely not won't not won't include 3. that's why you know include 3. that's why you know by doing this the sorting here you know by doing this the sorting here you know for each of the for each of the intervals we only need to check them intervals we only need to check them once once okay so that's the first step and the okay so that's the first step and the second step is that is this you know second step is that is this you know since we're only checking the left here since we're only checking the left here you know there's also a right you know there's also a right and for right i think it's pretty and for right i think it's pretty it's pretty straightforward you know it's pretty straightforward you know every time you know we also check every time you know we also check if the right is like is greater if the right is like is greater equal greater than than this two if it equal greater than than this two if it is and then we know okay so this is and then we know okay so this intervals can cover the current query intervals can cover the current query right and but that but that's not the right and but that but that's not the end of the story end of the story because since we're removing this kind because since we're removing this kind of a queries of a queries uh one by one you know the candidates uh one by one you know the candidates right the candidates might change because by moving into three or five or four you know the sum of the candidates intervals could could be uh could become invalid because it could be moved outside it could be can it may not be able to include this current query here right and the last thing is that no even all the candidates are valid candidates we still want to find smallest intervals among all those kind of candidates right so that's why you know after we're figuring out these sortings we we need a second we need another solution to efficiently to uh to remove the the invalid candidates from the candidates list and to also uh quickly get the smallest intervals right right so that we need like a data right so that we need like a data structure because we simply cannot do structure because we simply cannot do like a linear scan because that's what like a linear scan because that's what that beats the that beats the the entire like purpose of this sorting the entire like purpose of this sorting and then it will go back to this n and then it will go back to this n square time complexity square time complexity so what we can do in python is that you so what we can do in python is that you know we can use a priority queue know we can use a priority queue and why is that so first this priority and why is that so first this priority queue queue can always give us like the smallest can always give us like the smallest intervals in all one time intervals in all one time right basically the main reason we right basically the main reason we should should we choose the priority queue is that if we choose the priority queue is that if we if we put we if we put the first element in this particular to the first element in this particular to be the size be the size of the of the valid uh of the of the valid uh intervals right and then this particular intervals right and then this particular will will naturally give us the the smallest naturally give us the the smallest interval right interval right and okay so this so this then the and okay so this so this then the smallest interval smallest interval problem is is solved the second one is problem is is solved the second one is the last the last problem we want to solve is that how can problem we want to solve is that how can we remove we remove the uh the invalid intervals once we the uh the invalid intervals once we move to a move to a to a new query right to a new query right and how can we solve that this this one and how can we solve that this this one is a little bit tricky actually is a little bit tricky actually so what we can do is that you know in so what we can do is that you know in the product queue right when we the product queue right when we insert these candidates into the insert these candidates into the priority queue priority queue besides the size itself we can also besides the size itself we can also insert this right insert this right into the right value along with the size into the right value along with the size and the reason being is that you know if we have this right value along with the the candidate the intervals you know every time when we have like a new queries here we can always check if the priority queue 0 1 this one is smaller than this query remember this this product q zero remember this this product q zero is always pointing to the smallest is always pointing to the smallest intervals at the moment intervals at the moment and we only care about the smallest and we only care about the smallest intervals and if this one intervals and if this one is smaller than the numbers here you is smaller than the numbers here you know it means that you know okay so the know it means that you know okay so the current current smallest intervals becomes invalid smallest intervals becomes invalid so that we have to pop we have to do a hip-hop for the current priority and if the card so if this one if the the smallest one is still within the range of numbers then we know okay so the the current smallest intervals doesn't change you know even though in the product queue you know there are like some direct sum like intervals have already uh become invalid but since it will not affect the current the smallest intervals all we care is that you know if the all we care is that you know if the current smallest one current smallest one the current smallest interval will be the current smallest interval will be affected by uh affected by uh by having this kind of like interval the by having this kind of like interval the sorry but having the car sorry but having the car a new query cool yeah and that's all the uh the things we need to be cons to consider here and then we can start coding them right so again for this course right since we're going to get the answers for the queries we always need to add the uh the index onto the index along with the under the the number itself right for i uh dot number in the enumerate uh course right and then we sort right sort second one we also store the intervals right by the by the starting time and we have n gonna be the length of intervals right and then we have the answer it's going to be the uh starting with minus one and then the okay and then we have the j equals to okay and then we have the j equals to zero zero like which is pointing to the the like which is pointing to the the unprocessed unprocessed right i'm processing intervals and then right i'm processing intervals and then we have a product q we have a product q right to store the uh available right no to give us the the smallest uh as small as the size smallest interval size right okay so now for the nums and in i increase all right so this i'm not using all right so this i'm not using enumerate so this is like original index enumerate so this is like original index right so first we we check right while j smaller than n and the intervals right intervals which is the starting time of the which is the starting time of the current intervals is current intervals is within the the nums this this means that within the the nums this this means that you know you know the current one the current interval the current one the current interval interval could interval could be at a candidate right could be a be at a candidate right could be a might include the card number might include the card number so this one i'll just do this one since so this one i'll just do this one since the intervals the intervals it's pretty long here you know so we it's pretty long here you know so we have left and right for the current one have left and right for the current one and if the r is either equal it's and if the r is either equal it's greater than the greater than the number then we know okay so this number then we know okay so this intervals intervals this interval will include the current this interval will include the current number that's why we simply number that's why we simply push it into the product queue right push it into the product queue right that's because that's going to be that's because that's going to be our candidates and like i said the key the element we're pushing in into it the the main the main key is like the size of the the intervals and we also need like the uh the right the r the right value to help us to remove the invalid ones right and then we of course we do a j j plus basically we check if basically we check if interval j right include right num include right num right all right so here you know if j okay so i'll leave it here so what i'm trying to say is that you know so we we only need to check this j once right only need to check intervals j once right because it can it will either include or right because the uh you know the right because the uh you know the current the number is current the number is is always increasing and you know if the is always increasing and you know if the current intervals will not include this current intervals will not include this number you know a bigger number number you know a bigger number would definitely would definitely not be would definitely would definitely not be included in the same included in the same interval right that's why we can always interval right that's why we can always increasing this j here increasing this j here and cool so and after that you know and cool so and after that you know we will you know remove right the intervals intervals right which will intervals right which will affect the smallest affect the smallest size right that's why we do product size right that's why we do product queue queue and the priority q.0.1 right and the priority q.0.1 right is smaller than number which means that is smaller than number which means that okay so this one okay so this one the card number will affect our our the card number will affect our our smallest smallest value that's when we need to pop value that's when we need to pop right prodigy okay right prodigy okay and after that you know we simply update and after that you know we simply update the answer right if the product q is not the answer right if the product q is not empty empty right then we know okay we have at least right then we know okay we have at least some smallest some smallest size for us for this current query size for us for this current query which is the particular.0.0 okay which is the particular.0.0 okay and then we simply return the answer in and then we simply return the answer in the end that's it okay there you go right okay there you go right so it passed and so it passed and so time complexity right um there are they're both like uh same uh not like same like uh not like same like 10 to the power of five that's why we 10 to the power of five that's why we have have um unlock n right um unlock n right to sort and then here is also like to sort and then here is also like n and this is one and then we have n and this is one and then we have like priority q push and pop like priority q push and pop this is also only push and pop once yeah this is also only push and pop once yeah so here's so here's also unlocked yeah so yeah basically also unlocked yeah so yeah basically this is the unlock and this is the unlock and solution here yeah solution here yeah and space complexity of course is n and space complexity of course is n right so we only have like queries and right so we only have like queries and the answers the answers and also the priority queue space um yeah i think that's it right i mean um yeah i think that's it right i mean another another query k another another query k queries problems you know i think we queries problems you know i think we have already find like a pattern for have already find like a pattern for this one uh we always sort this one uh we always sort both the queries and and the source one both the queries and and the source one way or the other way or the other so that we only need for each of the so that we only need for each of the source uh source uh item we only need to consider them once item we only need to consider them once okay and after that uh based on okay and after that uh based on for this one you know based on the the for this one you know based on the the requirements requirements we have to somehow to find use another we have to somehow to find use another data structure data structure to help us achieve both to help us achieve both uh achieve to find the smallest size of uh achieve to find the smallest size of intervals intervals and to remove the invalid and to remove the invalid intervals efficiently that's why we use intervals efficiently that's why we use the priority queue here the priority queue here because particular will give us 01 time because particular will give us 01 time of the of the smallest size to find the of the of the smallest size to find the smallest smallest size and then the log n time to remove size and then the log n time to remove the the invalid intervals i think that's pretty much it is right and cool thank you for watching this video guys and stay tuned | 2024-03-25 10:40:12 | 1,851 | LeetCode 1851. Minimum Interval to Include Each Query |
|
lu_MPfoA9IY | hey guys welcome today we're going to be taking a welcome today we're going to be taking a look at the minimum Windows substring look at the minimum Windows substring question on lead code question on lead code now this question consists of taking two now this question consists of taking two strings one called s and one called T strings one called s and one called T and trying to find the minimum window in and trying to find the minimum window in s the minimum substring in s that s the minimum substring in s that contains all of the letters in t contains all of the letters in t and if we can't find any such window any and if we can't find any such window any such substring that contains all of the such substring that contains all of the letters in t we're just going to return letters in t we're just going to return an empty string an empty string uh the one interesting point that's uh the one interesting point that's highlighted in bold here is that the T highlighted in bold here is that the T can include duplicates can include duplicates so if there are multiple repeating so if there are multiple repeating characters inside T we have to find the characters inside T we have to find the same number of characters in s same number of characters in s before we can consider it a valid window before we can consider it a valid window now let's take a look at a couple of now let's take a look at a couple of examples examples what I would like to mention before we what I would like to mention before we do that is that this is a perfect do that is that this is a perfect candidate for the sliding window candidate for the sliding window technique which I'll get into in a bit technique which I'll get into in a bit but essentially if we're trying to look but essentially if we're trying to look at the input set and we're trying to at the input set and we're trying to optimize a sub range in the input set optimize a sub range in the input set just like we are with s we're trying to just like we are with s we're trying to optimize the sub-range in X then the optimize the sub-range in X then the sliding window technique might be sliding window technique might be something that could be helpful something that could be helpful uh and what we're going to do first uh and what we're going to do first however is just take a look at a couple however is just take a look at a couple of examples of examples so here we have S is equal to one a b so here we have S is equal to one a b one two three and c and we have t equals one two three and c and we have t equals one two three one two three now this one is pretty straightforward now this one is pretty straightforward we can see that we can see that T can be found in s right here T can be found in s right here as it it as it looks like in T it's as it it as it looks like in T it's found directly in s same order found directly in s same order plopped it right in the middle plopped it right in the middle but we should also note that there are but we should also note that there are other substrings that contain all of the other substrings that contain all of the letters in t but some other characters letters in t but some other characters for example b123 b123c you get the idea there are a few more than a few substrings that contain all of the letters in t with an S but what's so special about that first one that we highlighted is that it's the smallest one and there can't be a smaller one than that because that is the number of the characters that are in t are uh three we can't get smaller than that without losing one so that's what we're looking for we're looking uh for the smallest that we can possibly make it uh substring an s that contains all of the letters in t taking a look at a bit more complicated of an example we have one two three again as T and then a as sorry s is a bit more complicated it has a 1 b 2 c 3 d 1 2 and you can see that one two three is spread out in a couple of different variations inside s but we can still spot sort of pretty easily that there's a one two three here all right and now there's actually another one here two three one remember it doesn't have to be in the exact same order that it shows up in t for it to be valid are there any other oh there's one more um um now there are other substrings in s that now there are other substrings in s that contain all of the letters in t but contain all of the letters in t but they're bigger than the ones that I've they're bigger than the ones that I've highlighted here so I won't uh I won't highlighted here so I won't uh I won't look at those uh and out of the ones look at those uh and out of the ones that I've highlighted that I've highlighted the purple one is the smallest 3D one the purple one is the smallest 3D one two with four characters and then the two with four characters and then the other two both have five characters other two both have five characters so this might give you a clearer picture so this might give you a clearer picture of what we're looking for maybe some of of what we're looking for maybe some of the complexities in the problem the complexities in the problem um where T can be found in a different um where T can be found in a different order spanned across other characters order spanned across other characters that aren't in T and there can be a that aren't in T and there can be a couple different variations of it that couple different variations of it that are found what we're and out of those are found what we're and out of those very out of all the ones that we find very out of all the ones that we find we're looking for the one that is the we're looking for the one that is the minimum minimum now let's take a look at a final example now let's take a look at a final example here here let's say t is one two three four and S let's say t is one two three four and S is a b one two three c d e f is a b one two three c d e f uh now we can see that there's a four in uh now we can see that there's a four in t but there's no four in s and so right t but there's no four in s and so right away we know that this pattern T can away we know that this pattern T can never be found in s and so here we would never be found in s and so here we would just return an empty string all right so out of the examples that we saw let's try to come up with a Brute Force approach that gets Us close to an efficient algorithm uh and we can always start with Brute Force and optimize later this is a well tested battle tested strategy for programming interviews if an efficient solution isn't immediately clear to you always always think about what could be the Brute Force approach so what is the Brute Force approach that returns us the minimum window substring in s that has all the letters in t namely in this example it would return 3D one two and in the example above it would return one two three so take a minute pause the video try to come up with an algorithm a series of steps uh maybe some code or thoughts of a Brute Force approach it doesn't have to be optimized a Brute Force approach that returns us the minimum window substring in s that contains all the all right welcome back all right welcome back now let's think about what the problem now let's think about what the problem is asking so the problem is asking us is asking so the problem is asking us for the minimum window substring it's for the minimum window substring it's asking for a substring in s asking for a substring in s so our solution so our solution is one of the substrings of s is one of the substrings of s a truly Brute Force approach would be to a truly Brute Force approach would be to generate all of the substrings of s generate all of the substrings of s and narrow it down filter those until we and narrow it down filter those until we get our get our our solution the one that fits our our solution the one that fits our criteria of being the minimum window criteria of being the minimum window substring of s that contains all the substring of s that contains all the letters of a t letters of a t how would that look like let's take a how would that look like let's take a look at an example where s is equal to a look at an example where s is equal to a b one two three C and T is equal to one b one two three C and T is equal to one two three so if we generate all of the substrings of a b one two three C it would look a little something like this and out of these substrings we want to narrow it down so we identify the minimum window substring of s that contains all the letters in t so first off let's just identify the ones that have all the letters in t of T in s in these substrings so the the ones that have one two three within them just go ahead and mark them with a thumbs up and the rest enough so out of the ones that we marked with a thumbs up we only want one and that is the one that is at the minimum and so we can see that this is the so that is the Brute Force approach so that is the Brute Force approach where we generate all the possible where we generate all the possible solutions all the substrate all the solutions all the substrate all the possible substrings and out of those possible substrings and out of those substrings we try to narrow down until substrings we try to narrow down until we get one solution we get one solution um that fits and matches our criteria um that fits and matches our criteria um and so um and so this works but it's quite inefficient this works but it's quite inefficient we'll get into why in a bit let's come we'll get into why in a bit let's come up with a time complexity here the time up with a time complexity here the time complexity is dominated by the search complexity is dominated by the search for substrings the computation of for substrings the computation of substrings fs and I say the length of s substrings fs and I say the length of s is n then it would be o of N squared and is n then it would be o of N squared and this is because the computation of this is because the computation of substrings takes about uh the sum of substrings takes about uh the sum of want and the natural sum that's how long want and the natural sum that's how long it takes to compute the number of all of it takes to compute the number of all of the substrings of a given string the substrings of a given string um it would and that gives us a Big O um it would and that gives us a Big O worst case time complexity of O of N worst case time complexity of O of N squared why is this inefficient what is the Brute Force approach doing that is over computing well it's searching substrings that could never be a valid substring it could never be the minimum window substring for example here we see that it continues generating substrings after eight it sees that ab12 is a substring that goes ab1 a b a and then a but it should have stopped at ab12 because anything any substring of ab12 will never be valid it can never contain something it doesn't already have it can't find that three so that will never be valid so what we want to do is look through the substrings the windows in s in a way that we're not over Computing we're not Computing substrings we're not Computing windows that can never be valid and this is where the sliding window approach all right so the sliding window all right so the sliding window technique is useful when we have a technique is useful when we have a question that's asking for an optimal question that's asking for an optimal sub range and in the input set sub range and in the input set and in this question the input set we and in this question the input set we have is s and we're looking for the have is s and we're looking for the optimal sub ranges and the minimum optimal sub ranges and the minimum window substring that matches our window substring that matches our constraints of having all the letters in constraints of having all the letters in t so the sliding window technique is a t so the sliding window technique is a good candidate for a template problem good candidate for a template problem solving uh technique here solving uh technique here um what it'll involve is we'll keep um what it'll involve is we'll keep track of a window using a left and a track of a window using a left and a right pointer a left pointer pointing to right pointer a left pointer pointing to the beginning of the window and a right the beginning of the window and a right pointer pointing to the end of the pointer pointing to the end of the window go through an example to work it window go through an example to work it all out all out so let's say a I'm sorry s is a 1 b 2 c so let's say a I'm sorry s is a 1 b 2 c 3 D1 2 and T is one two three 3 D1 2 and T is one two three uh then let's create a window on it uh then let's create a window on it and let's say and let's say that it that it initially the window is initialized initially the window is initialized where both the left and the right Point where both the left and the right Point are pointing at the same thing the same are pointing at the same thing the same element uh which is the first element a element uh which is the first element a what we want to do is we want to expand what we want to do is we want to expand the right pointer up by one until this the right pointer up by one until this window contains window contains all of the letters from C until this all of the letters from C until this window is valid according to our window is valid according to our constraints constraints so so it previously was a now it's A1 we've it previously was a now it's A1 we've expanded the right corner up by one expanded the right corner up by one we're going to do that again because we're going to do that again because it's still not valid so we have a1b and it's still not valid so we have a1b and again once more because it's still not again once more because it's still not valid A1 B2 valid A1 B2 and so on until the window becomes valid and so on until the window becomes valid and that'll happen here so we have A1 B2 and that'll happen here so we have A1 B2 C3 we've expanded the right pointer C3 we've expanded the right pointer until the window has become valid and until the window has become valid and when we get to a valid window every time when we get to a valid window every time we want to check the length of it to see we want to check the length of it to see if it is below our candidate for the if it is below our candidate for the minimum window so the length of this is minimum window so the length of this is six and this is the minimum that we've six and this is the minimum that we've seen so far seen so far so we'll record that so we'll record that and as you can see here in the next step and as you can see here in the next step we contract the window so when we have we contract the window so when we have an invalid window we expand the window an invalid window we expand the window by moving the right pointer up by one by moving the right pointer up by one but once we have a valid window we but once we have a valid window we contract it by moving the left pointer contract it by moving the left pointer up by one and so the window becomes up by one and so the window becomes smaller smaller and the reason we do that is so we can and the reason we do that is so we can find the minimum window we keep find the minimum window we keep Contracting the left pointer and we keep Contracting the left pointer and we keep moving the left pointer up by one and moving the left pointer up by one and Contracting the window until the window Contracting the window until the window no longer is valid according to our no longer is valid according to our constraint until it no longer has all of constraint until it no longer has all of the letters from c letters from T the letters from c letters from T contained within it doesn't have one two contained within it doesn't have one two three so uh if we move the left pointer three so uh if we move the left pointer up by one initially it's still valid and up by one initially it's still valid and we since it's valid we record the length we since it's valid we record the length of the valid window it's five it's less of the valid window it's five it's less than our current one so this becomes our than our current one so this becomes our new candidate for the minimum window new candidate for the minimum window substring that contains all the letters substring that contains all the letters from T and we contract one more time from T and we contract one more time moving the left pointer up by one and we moving the left pointer up by one and we can see that it's not valid anymore it can see that it's not valid anymore it doesn't have a one in it anymore and so doesn't have a one in it anymore and so it doesn't have all the letters from T it doesn't have all the letters from T within it within it uh what does that mean for us in our uh what does that mean for us in our algorithm using the sliding window algorithm using the sliding window Technique we expand the window expanding Technique we expand the window expanding the window means moving the right the window means moving the right pointer up by one so we do that pointer up by one so we do that now it contains d now it contains d still not valid because it's still still not valid because it's still missing that one and if we move it to missing that one and if we move it to the right one more time we can see that the right one more time we can see that it has now become valid and so we record it has now become valid and so we record the length it's six and since it's a the length it's six and since it's a valid window valid window we contract it by moving the left we contract it by moving the left pointer up by one and so the left pointer up by one and so the left pointer moves up by one pointer moves up by one and we get another valid window and we get another valid window um this window has five as the length um this window has five as the length it's uh the same size the last minimum it's uh the same size the last minimum candidate so we don't it doesn't really candidate so we don't it doesn't really help us help us um we continue by Contracting the window um we continue by Contracting the window one more time one more time by moving the left pointer up at one and by moving the left pointer up at one and we can see that it no longer is valid it we can see that it no longer is valid it doesn't have two within it it's missing doesn't have two within it it's missing the two the two so uh since it's invalid we'll expand so uh since it's invalid we'll expand the right pointer up by one the right pointer up by one when the right pointer is expanded by when the right pointer is expanded by one uh we see that it has become valid one uh we see that it has become valid it contains all the letters from T three it contains all the letters from T three D one two we record the length here it's D one two we record the length here it's four oh this is our new minimum so our four oh this is our new minimum so our new minimum window new minimum window um and um and since it's valid we want to contract the since it's valid we want to contract the window by moving the left pointer up by window by moving the left pointer up by one one moving that up it because it no longer moving that up it because it no longer is valid and uh we are done at this is valid and uh we are done at this point because we can't move the right point because we can't move the right pointer up by one and moving the left pointer up by one and moving the left pointer up by one uh would decrease the pointer up by one uh would decrease the window size so that it is smaller than window size so that it is smaller than our desired length therefore uh we can our desired length therefore uh we can exit the algorithm and look at our exit the algorithm and look at our candidates candidates and pick the minimum one which is four and pick the minimum one which is four in return and so at the minimum in return and so at the minimum candidate and at the minimum window candidate and at the minimum window substring is three D one two substring is three D one two and that's what we return using the and that's what we return using the sliding window technique so hey guys let's get into the coding portion of this algorithm that we just saw and initially what we want to do is just break out the cases where s is empty or t is empty so we get that out of the way and we only have to deal with the non-empty cases uh what happens if s is empty not s and python well then we won't be able to find any uh pattern T within it so we would return empty in that case but we'd also return empty and when T is empty because then by default we find it in NES so we'd always return the empty string when either as or t or empty so that gets the empty cases out of the way now we can move on to the actual sliding window technique and for that we have to define a couple of variables first if I'm being frequency of T freak T and freak T will use the counter class in Python to generate an object that has the unique characters of T map to the frequency of their occurrences so if there are three characters for example uh Three A's in t then this object would be a mapped to three and so on and so forth for all the other unique characters another another variable that we'd like to keep track of that will help us implement the sliding window algorithm will be the frequency of the characters in Windows long name but this it also tracks frequency of characters but it's only the frequency of the characters that are in our window and this will be an ongoing count that will subtract and add to when the window increases in size and contracts in size remember the sliding window technique has a left and right pointer that keeps track of a window that we use essentially to search the input string and find our optimal uh set or answer the minimum window substring and in order to do that in order to find the answer we need to keep track of another variable and this one will be called num underscore missing and this will be equal to the frequency of the characters of T it's this the num missing is the number of characters that we currently are missing from our window for uh and and when numb missing is zero we are missing zero characters from our current window um and so our window is valid so the importance of this variable is that it helps us keep track of whether or not we okay moving on another variable that okay moving on another variable that we'd like to keep track of is obviously we'd like to keep track of is obviously our answer variable our answer variable our answer variable our answer variable will be a tuple it'll hold two values will be a tuple it'll hold two values one being the left so you can say one being the left so you can say initially this is negative infinity and initially this is negative infinity and the right which is positive Infinity will return will return s at answer zero s at answer zero to answer one and it's only if we're able to find a minimum window so if answer is negative infinity or Infinity for any one of those two values then we'd actually have we haven't found a valid window and also would return uh empty in that case and in order to do that we'll just do a foreign so now we have all of the variables defined to run sliding window and the main bits of sliding window rely on two pointers a left pointer that will initialize to zero and a right pointer that will actually use a for Loop to increment and it'll start at zero and go to the length of s we'll keep track of a variable called character that is equal to what's inside s and we also want to update this and we also want to update this frequency of characters that it's in our frequency of characters that it's in our current window current window so characters in our current window we so characters in our current window we want to update the frequency of want to update the frequency of character by one character by one to do that we can just do a to do that we can just do a frequency.get character and give it a frequency.get character and give it a default value of zero and add one what this allows us to do is to check well we first check if the character is interesting to us and it's interesting if it occurs in T So character is in frequency of t then we want to do another check on it we want to check if we've encountered this character the number of times that it occurs in t if we've encountered this character in our current window if we've encountered the encounter this character um the amount of times that it occurs in t then that then we don't have to look for this character anymore then we can decrement that numb missing variable by one because we have one less character to look for remember that starts at the number of unique characters in T and when that reaches zero that means that we have found the required number of characters for all of the unique characters in t when them missing a zero and that means we have a valid window so that's why that variable is important and that's why we have these other variables that are keeping track of the frequencies occurrences in our current window and their total occurrences so if the frequency of the characters in the current one if the frequency of the character in the current window is equal and we can decrement the num missing by and we can decrement the num missing by one one and while num missing is zero so if and while num missing is zero so if the window is valid the window is valid that's why I'm not missing a zero and that's why I'm not missing a zero and the left is still less than or equal to the left is still less than or equal to right because we're going to want to right because we're going to want to increment left here increment left here because we're Contracting so since the window is valid uh we want to contract the window but before we can track the window we're going to need to check if the current valid window is a little less in length than the window that we have in our answer variable so our answer variable so if I say right it's track left is less than answer one then we can say answer is equal to left then we can say answer is equal to left right right the length the length of the current valid window is less of the current valid window is less then the answer that we've been keeping then the answer that we've been keeping track of so far track of so far and initially any length will be any and initially any length will be any length of any valid window will be length of any valid window will be greater it would be less greater it would be less than than we want to update our answer than than we want to update our answer and after we've updated our answer and after we've updated our answer we want to contract the window and uh we want to contract the window and uh see if we still have a valid window if see if we still have a valid window if not missing is still zero and that can not missing is still zero and that can if we do we keep on doing that until if we do we keep on doing that until we've minimized the current window we've minimized the current window and so we get the minimum version of and so we get the minimum version of this valid window to check our answer this valid window to check our answer against against until the window is no longer valid at until the window is no longer valid at which point we'll continue looking for a which point we'll continue looking for a valid window valid window um so we have other very another um so we have other very another character that is we're going to check character that is we're going to check if it's interesting to us it's character if it's interesting to us it's character at left currently so we'll check at the at left currently so we'll check at the left left and if and if the we well first we want to decrement the we well first we want to decrement the frequency of the occurrences of this the frequency of the occurrences of this character by one and then we want to check again if this character is interesting to us it's interesting if it occurs in t great and if the frequency of occurrences of this character is less than the number of times that it 2 2 add 1 to them missing because now we add 1 to them missing because now we have less than number of required have less than number of required characters characters for this particular character we have for this particular character we have less than the number we need for for us less than the number we need for for us to Encompass all of the occurrences that to Encompass all of the occurrences that it has in T and so our missing no it has in T and so our missing no missing variable goes up by one missing variable goes up by one um um it is no longer a valid window it is no longer a valid window and we also move left up by one and that's it let's try hitting submit boom thank you for watching guys hit like And thank you for watching guys hit like And subscribe if you learned anything from subscribe if you learned anything from the material the material please give a comment if you have any please give a comment if you have any feedback thanks feedback thanks and have a wonderful day | 2024-03-20 11:44:09 | 76 | Minimum Window Substring - Sliding Window - Leetcode 76 - Python |
|
WSYEn7UQxgs | hello guys I hope you are all doing well and this video we'll be solving the lead and this video we'll be solving the lead code problem find the town judge so code problem find the town judge so let's get started so the problem is that let's get started so the problem is that you have a list of people in the town you have a list of people in the town and the task is that you need to find and the task is that you need to find out who is the judge in this town so out who is the judge in this town so before we solve this problem let's break before we solve this problem let's break this problem into pieces so we can this problem into pieces so we can quickly solve it using only the details quickly solve it using only the details that they give us the first information that they give us the first information that we have is the town judge is that we have is the town judge is someone who trusts nobody and is trusted someone who trusts nobody and is trusted by everyone else the second affirmation by everyone else the second affirmation that they give us is that we have earned that they give us is that we have earned people in the town and the third people in the town and the third information is that we have a list of information is that we have a list of trust relationship and this list trust relationship and this list represents a pair of integers the first represents a pair of integers the first integer is the one who trusts the second integer is the one who trusts the second integer represents the person who is integer represents the person who is trust so to solve this problem we're trust so to solve this problem we're going to use just a simple accounting going to use just a simple accounting algorithm we're going to create an array algorithm we're going to create an array to keep track of the number of persons to keep track of the number of persons who trusts and the number of person who who trusts and the number of person who is trusted by others and one of the key is trusted by others and one of the key to solve this problem is that inside all to solve this problem is that inside all those people and we need to find that at those people and we need to find that at the end the numbers of people who trust the end the numbers of people who trust the town judge must be equal to n minus the town judge must be equal to n minus 1 means the end people 1 means the end people -1 and the minus one represent the one -1 and the minus one represent the one who is trusted by people means the town who is trusted by people means the town judge so let's say we have three people judge so let's say we have three people and this input list of trust first we and this input list of trust first we create an array that have the same create an array that have the same length of n people and set his value to length of n people and set his value to be zero then we need to Traverse the be zero then we need to Traverse the list of tourists relationship and for list of tourists relationship and for each pair integer we decrease the trust each pair integer we decrease the trust count of the first person by one and count of the first person by one and increase the trust count of the second increase the trust count of the second person by one for example for the first person by one for example for the first integer inside the list is one which integer inside the list is one which represents the person who trusts so represents the person who trusts so we're gonna decrease his value by one we're gonna decrease his value by one inside the array that we created before inside the array that we created before then the second integer is the person then the second integer is the person who other trusts so we're gonna add one who other trusts so we're gonna add one to it inside the array then we move to to it inside the array then we move to the next pair of integers the first the next pair of integers the first integer is two so we put minus one integer is two so we put minus one inside the array and a new index because inside the array and a new index because it's a new person and the second person it's a new person and the second person is the same person who people trust so is the same person who people trust so we increase his value as inside the we increase his value as inside the array by one so after the loop finishes array by one so after the loop finishes we Loop another chime over the end we Loop another chime over the end people and we use the index of this people and we use the index of this current Loop to Traverse the array that current Loop to Traverse the array that we made before and as I explained to you we made before and as I explained to you guys before that the key to solve this guys before that the key to solve this problem is that we need to find that at problem is that we need to find that at the end the numbers must be equal to the the end the numbers must be equal to the town judge so that's why we Traverse the town judge so that's why we Traverse the array to find any element whose value is array to find any element whose value is equal to n minus one I mean this person equal to n minus one I mean this person is trusted by n people minus the town is trusted by n people minus the town judge so if there is a no such person judge so if there is a no such person will return will return -1 so there is other test case for -1 so there is other test case for example where the person one trust example where the person one trust person two and person two trusts nobody person two and person two trusts nobody so here the person too is the judge also so here the person too is the judge also when there is only one person and he when there is only one person and he trusts nobody so we can say that he's trusts nobody so we can say that he's the judge and the output should be one the judge and the output should be one so you can create as many as you can to so you can create as many as you can to test the age cases that's it guys so test the age cases that's it guys so let's jump at code in the solution first let's jump at code in the solution first we initialize an array trust counter of we initialize an array trust counter of size n and we set his value to be zero size n and we set his value to be zero then we Loop over the trust array and then we Loop over the trust array and for each list software integer we for each list software integer we decrease the trust sculpture of the decrease the trust sculpture of the first person by one and we increase the first person by one and we increase the trust counter of the second person by trust counter of the second person by one then we initialize another for Loop that Loop over the end person and we use his index to Traverse the truss counter to check if one of its value are equal to n minus one if true we return the index plus 1 which represents the person who is trusted by n minus 1 people and trust nobody finally we'll return -1 if there is no such person who can be trusted so the time complexity for the solution is oftenware n is the number of people in the town or we can say because we are iterating throughout the trust sculpture that have the size of N and the space complexity is often because we're great in our rate there are structures to keep track of each person inside the list that's it guys thanks for watching see | 2024-03-25 14:50:28 | 997 | Find the Town Judge - LeetCode 997 - Coding Interview Questions |
|
QouU2jF7exs | welcome to august 26th leco challenge verify pre-order serialization of binary verify pre-order serialization of binary tree tree one way to sterilize bearing binary one way to sterilize bearing binary trees to use pre-order traversal when we trees to use pre-order traversal when we encounter a non-none node encounter a non-none node we record a node's value if a null node we record a node's value if a null node if it's an all node we record a sentence if it's an all node we record a sentence value such as the string pound value such as the string pound so for example this binary uh tree here so for example this binary uh tree here um um of the bubble binder should be of the bubble binder should be serialized as the following string so serialized as the following string so notice the strings uh comma separated notice the strings uh comma separated value and we have pound signs and value and we have pound signs and numbers in there as well numbers in there as well but they're all strings where a pound but they're all strings where a pound represents the null node given the represents the null node given the string of comma separate value pre-order string of comma separate value pre-order return true if it is a correct pre-order return true if it is a correct pre-order traversal serialization of the binary traversal serialization of the binary tree tree it was guaranteed that each comma it was guaranteed that each comma separate value in a string must be separate value in a string must be either an integer or the character pound either an integer or the character pound or hash or hash represent the null pointer representing represent the null pointer representing the null pointer the null pointer you may assume that the input format is you may assume that the input format is always valid for example it can never always valid for example it can never contain two concept commas such as comma contain two concept commas such as comma comma comma no you're not allowed to reconstruct the no you're not allowed to reconstruct the tree tree so uh we're given this pre-order uh so uh we're given this pre-order uh string array and it returns true because string array and it returns true because that's the tree that up here that's the tree that up here that we're given so that that is in um that we're given so that that is in um pre-order traversal so it is the pre-order traversal so it is the serialization of that of that binary serialization of that of that binary tree tree however this is false it's pretty however this is false it's pretty obvious because uh obvious because uh you can't have one then no that's not a you can't have one then no that's not a pre-order traversal binary tree pre-order traversal binary tree and likewise you have nine fold by no and likewise you have nine fold by no null one that's not pre-ordered null one that's not pre-ordered traversal trading traversal trading so the pre-order length so the pre-order length is one to that and four pre-order is one to that and four pre-order consists of energy between zero to consists of energy between zero to hundred and hundred and except by a comma and it has hash signs except by a comma and it has hash signs in it in it so basically um so basically um you just given a string and you want to you just given a string and you want to verify whether it's a serialization or verify whether it's a serialization or pre-order binary tree that's pretty much pre-order binary tree that's pretty much it so pre-order traversal meaning that it so pre-order traversal meaning that um um you would keep track of the numbers you would keep track of the numbers uh traveling like that so if it's a uh traveling like that so if it's a period traversal you would count the period traversal you would count the numbers first it'll be nine three four numbers first it'll be nine three four followed by one four by two and followed followed by one four by two and followed by by 6 6 and the pound sign represents a null and the pound sign represents a null node so for instance node so for instance um 9 3 4 and then the house it's supposed to have two more null nodes at the bottom but those are not so every pound pound going all the way to one pound pound going to six pound pound and that's it six pound pound and that's it so that's the um so that's the um that's how we do pro traversal that's how we do pro traversal so starting from this you count the so starting from this you count the number first and then you go down then number first and then you go down then you count the null nodes as well you count the null nodes as well so in order to do this i'm gonna do a um so in order to do this i'm gonna do a um what you could do is actually a reverse what you could do is actually a reverse traversal so just go backwards and kind traversal so just go backwards and kind of analyze whether it's uh of analyze whether it's uh it's valid or not and using a stack to it's valid or not and using a stack to keep track of the uh keep track of the uh the string the string so let's do that let's see if that works so let's do that let's see if that works so stack i'm going to make that empty make a stack and then now we are going to parse up the pre-order string because we don't want this just comma separated value we just want the number of values in there um we're going to reassign it actually um we're going to reassign it actually just called just called pre-order pre-order dot split dot split via the comma all right that seems like sentence and then we'll do a for loop in there to iterate through each element inside the uh the values inside the the pre-order split value so for uh each index in the range of the length of uh you want uh you want minus one we want to reverse minus one we want to reverse traverse it traverse it traverse it in reverse traverse it in reverse go backwards by one and then if the pre-order uh value at i is not equal to the then what we want to do is uh check see then what we want to do is uh check see if the stack is less than one so if the if the stack is less than one so if the length stack length stack is less than two i should say that we is less than two i should say that we want to return false because uh want to return false because uh that's not a valid pre-order traversal that's not a valid pre-order traversal of the binary tree of the binary tree otherwise otherwise we would we would we would want to uh stack pop from the we would want to uh stack pop from the stack stack right right um um [Music] [Music] we'll pop from the stack we'll pop from the stack twice twice twice twice because um if the length of stack is because um if the length of stack is less than two that means that it's two less than two that means that it's two they need each empty node here has two they need each empty node here has two null values and the only way it could be null values and the only way it could be one is if it has a branch like this so one is if it has a branch like this so you'll pop the stack twice pen pen we are going to append the pre-order we are going to append the pre-order traversal at index i all right next we want to return a boolean return a boolean such that the length of the stack let's check to see this right awesome accepted so i pretty much made awesome accepted so i pretty much made to stack universes in reverse we to stack universes in reverse we traverse it in reverse order and then we traverse it in reverse order and then we just just if we check to see the line if the value if we check to see the line if the value at the next i is equal to pound if so at the next i is equal to pound if so we're going to check to see if the stack we're going to check to see if the stack size is less than two if it is you can't size is less than two if it is you can't have that because it's not an end a leaf have that because it's not an end a leaf node node therefore we pop it twice and then we therefore we pop it twice and then we append the um append the um the index back to the stack and then we the index back to the stack and then we basically do the we repeat the for loop basically do the we repeat the for loop right until we see the stack and we right until we see the stack and we returned true only if uh returned true only if uh length of stack is equal to one that length of stack is equal to one that means that this means that this that means there's always going to be that means there's always going to be one value inside the stack because we're one value inside the stack because we're traversing in reverse order traversing in reverse order all right and time complexity is big o all right and time complexity is big o of big o of n where n is the length of the uh space complexity is uh uh space complexity is uh this big of endless wall is the size of this big of endless wall is the size of the stack right we could do this the stack right we could do this recursively too but recursively too but i guess iteration works well all right i guess iteration works well all right that's it have a great day guys | 2024-03-24 10:41:30 | 331 | August 26/2021 LeetCode Challenge: Verify Preorder Serialization of a Binary Tree |
|
Lq1hbOWH-dU | Hello everyone Welcome to my channel here I solve Lead Code problems and channel here I solve Lead Code problems and today an interesting task is the daily today an interesting task is the daily Challenge task number Challenge task number 787 the cheapest flight with no more 787 the cheapest flight with no more than k stops average level we are given than k stops average level we are given N cities N cities connected by a certain number of connected by a certain number of planes we are given an array of flights in planes we are given an array of flights in in which Each element of the array consists in which Each element of the array consists of three parts, this is the city of departure, the city of of three parts, this is the city of departure, the city of arrival, and arrival, and also the price, also the price, we also have the maximum number of we also have the maximum number of stops that we can make, we stops that we can make, we need to return the cheapest flight option in which we can make no flight option in which we can make no more than more than stops, if we cannot get to the stops, if we cannot get to the to stops Let's to stops Let's to stops Let's solve this. This is quite an interesting solve this. This is quite an interesting problem and there problem and there is a good technique that can be is a good technique that can be worked out in this problem. There are worked out in this problem. There are two main two main components. The first is that components. The first is that we need to transform we need to transform the array, that is, we see that the array the array, that is, we see that the array consists of such a flat one, we can say consists of such a flat one, we can say structures, that is, Each element of the array is structures, that is, Each element of the array is also an array of three also an array of three elements. In the future, to solve the elements. In the future, to solve the problem, it is convenient for us that this problem, it is convenient for us that this array should be not just an array of array should be not just an array of arrays, but a dictionary whose keys would be arrays, but a dictionary whose keys would be destinations destinations in Which city can we fly from a certain this immediately here this immediately here this immediately here standard technique, that is, what we need, that is, we will have some kind of dictionary. That is, for example, let’s look at so here it’s better to look at example D. That is, from city zero we can fly to city o and to city 2 and each flight costs respectively city about 100 to city 2,500 that is, we transform transform our list so that the result is such that our list so that the result is such that our key is city zero and our key is city zero and the value is an array And in each there is an array of city and price That is, there will be two tuples like this, the first one will be the city destination price is 100 and also for city 2 the price is 500 That is, this is one key. That is, this means that from city zero we can fly to city 1 and 2, that is, in the future, using such a dictionary, we can easily find the city to which we can get, and then there we will check this along the cheat chain Our first stage Let's write it down right here and then move on to the second stage which I will show graphically, that is, we will create a dictionary pass and define it as Def dict, that is, we will use the default dict function with the value with the value lead lead creates a dictionary in such a way that if creates a dictionary in such a way that if We access the We access the dictionary using a key that is not in the dictionary, then the dictionary using a key that is not in the dictionary, then the default value for default value for this type is returned, that is, for the sheet type an this type is returned, that is, for the sheet type an empty list is returned, empty list is returned, this will simplify this will simplify the writing a little, then we go through all the the writing a little, then we go through all the elements flights, it consists of three elements, three elements are From to and let's write frm - this is let's write frm - this is let's write frm - this is From to and Price in the list of flights and write pufs with the key From into our dictionary, that is, for each city we write where we can fly to, add append, that is, due to the fact that we used the default dict function, append append append list even if the key may not be in the dictionary, that is, we call and Each element consists of two elements and PR is all the first stage is ready Now we have a dictionary of all flights Let's see graphically what we can do, again for simplicity, let's what we what we what we have, we have zero o and d and the arrows have, we have zero o and d and the arrows indicate where we can indicate where we can fly, that is, in this way a ra fly, that is, in this way a ra can fly can fly with one stop, with one stop, what will we do here, we will what will we do here, we will use the so-called use the so-called breadth-first search, that is, what does this mean for us breadth-first search, that is, what does this mean for us breadth-first search, that is, what does this mean for us will be a certain queue, this is a list with a key, that is, with the departure city, that is, by default it is zero, so inside there will also be a tuple of two values, departure city and price, that is, that is, we start from zero and the price is zero since we are in this city and then we we add all the cities from which we can fly from this city, that is, we take the current city zero, we can fly to city 1,2 Prices are 100 and 500 100, respectively. That is, there That is, there are two stages, that is, first of all are two stages, that is, first of all we need to check we need to check that that that we can fly to, this is 1 ID that this city is not a destination city, that is, one is not a destination city, while two are a destination city, so for two we write the result 500, that is, 500 is so far the we can we can we can fly to the city 2 blue ones indicate that we have processed this Now we have processed these two after we have processed that is, we have processed point zero, we have processed it, we remove it from the list at the next stage, updated points d are added to the list with the price for which we can fly to this city, that is, to city one we can 100, to city 100, to city 2 we can fly in 500, so we reduce k by one, that is, we reduce it like this, that is, zero, that is, we used one transfer, we reduced it, that is, after we made one transfer, we can one action for our two one action for our two one action for our two elements available action is a flight elements available action is a flight from city one to city 2, that is, we use city 2 to increase the current distance 100, add the cost of the flight here, too, 100 is also blue. That is, it turns out that now you can fly to city 2 for 200 and also we also blue. That is, it turns out that now you can fly to city 2 for 200 and also we also blue. That is, it turns out that now you can fly to city 2 for 200 and also we this is our result and we see that this result is better than the previous one, that is, we write that the result is smaller and we add to our final smaller and we add to our final result to not final And in our result to not final And in our turn, that is, now turn, that is, now there is a city 200 and for point two we no longer have 200 and for point two we no longer have an option where we can an option where we can advance and we have everything. We advance and we have everything. We used everything before and got better than used everything before and got better than 200, that is, it’s like a General solution 200, that is, it’s like a General solution Let’s now implement it, that is, what is Let’s now implement it, that is, what is needed here, we need a result needed here, we need a result needed here, we need a result begin with, what will we enter? As a result, that is, we need some number that will be the default and minimal. To begin with, we can enter a minimal. To begin with, we can enter a number number such as plus infinity, it is written such as plus infinity, it is written in Python in this way t from the line inf in Python in this way t from the line inf so not in but so not in but inf inf inf some result, it will be less than infinity. Let's immediately write down the answer as it will look like in the answer. We will return the result if it is unequal to our mi1, which is what we need next. Next, we need mi1, which is what we need next. Next, we need our queue queue this will be a dictionary in which by default it is located, that is, Our departure city and price, but that is, it is here This is the place, that is, we start from this place, we will also need an additional variable C this is the dictionary Sin - this is a dictionary in which the and price - This is the lowest and price - This is the lowest and price - This is the lowest price to get to this city, we price to get to this city, we need this to need this to optimize flights to cities and optimize flights to cities and avoid cyclical transitions, that is, avoid cyclical transitions, that is, roughly speaking, if we have roughly speaking, if we have many available moves. That is, for example, many available moves. That is, for example, in example one, we can get from the zero in example one, we can get from the zero city to the first one city to the first one city to the first one second city then again to the zero city, that is, to avoid this, we will initially write down that we can get to the zero city for zero sous, but also after flying to the first city and then to the second we will not fly back to the zero city since the overall result will be worse than the original one which we saved in the variable Sin, that is, by default we write in Sin our original city and the value is zero, that is, we are in NM and the front before it is free, is the search for width, that is, we work in a loop as long as there is Q this this this K is greater than or equal to K is greater than or equal to zero, that is, that is, externally there will be zero, that is, that is, externally there will be two nested cycles and in each cycle we two nested cycles and in each cycle we go through, as it were, from that is, again, if go through, as it were, from that is, again, if you look here and here, this is the first you look here and here, this is the first layer, the second layer, the third layer, the second layer, the third layer, and inside each layer we go through layer, and inside each layer we go through each each each is, in the first layer there is one element elements inside each layer, we elements inside each layer, we reduce reduce also initiate an empty dictionary, an empty list, which we will finally transfer to our main list loop for now, that is, here loop for now, that is, here loop for now, that is, here check the layer, that is, in the zero layer it is one element, in the first layer there are two elements and we extract the current value, the current value consists of two elements. That is, if we sing on how we initiated this is the city, the resource and the price, let's write the resource price like this, Well, let's say price Let Well, let's say price Let Well, let's say price Let it be like this No not Pray Let's Total resources Total extract the element from Q using the pop method now we check pop method now we check that so no here here we don't check here we that so no here here we don't check here we look where we can get look where we can get that is we we we check the dictionary pass that is we we we check the dictionary pass it consists of two it consists of two components and PR in the dictionary we pass and check the city CPC now what can we have here that is to begin with Let's look at the price of the city that is the cost of the is an increase in its price and the previous amount and now if the city is equal to the city where we need that is that update the result to the result, write the minimum From the current Price, the next thing we need is we Price, the next thing we need is we need to need to add the value to a new layer, but only add the value to a new layer, but only if we either have not been to this if we either have not been to this city. That is, Sin is empty or our city. That is, Sin is empty or our result is better than the result is better than the previous one. That is, if of this or the second option is that Pray is less than Sin, that is, there were no soaps, or the current price is better in this ra and also add an element to the queue, again two components are Price Price So let's see what the idea is, this is probably the whole solution Let's run send the whole decision so we see send the whole decision so we see that it is efficient in terms of that it is efficient in terms of memory time such a solution, and here one memory time such a solution, and here one of the main keys to an effective solution of the main keys to an effective solution is the use of changes Syn, that is, is the use of changes Syn, that is, without without it we would have performed much more it we would have performed much more unnecessary actions and our decision would have been unnecessary actions and our decision would have been accepted on this for today all thanks accepted on this for today all thanks for your attention full solution as always for your attention full solution as always Look at the link in the description of the video Look at the link in the description of the video see you tomorrow Bye | 2024-03-21 16:52:20 | 787 | LeetCode 787 Cheapest Flights Within K Stops - python |
|
MzdzJuvzmS4 | welcome to june's lego challenge today's problem is pascal's triangle problem is pascal's triangle given integer num rows we turn the first given integer num rows we turn the first num rows of pascal's triangle num rows of pascal's triangle in pascal's triangle each number is the in pascal's triangle each number is the sum of the two numbers directly above it sum of the two numbers directly above it you can see how it looks in real time you can see how it looks in real time notice how the ones at the edges left notice how the ones at the edges left and right are always going to be one and right are always going to be one it's only the ones in the middle that we it's only the ones in the middle that we care about those are going to just care about those are going to just look up and add the first and second one look up and add the first and second one right above it right above it now how do we code that out well the now how do we code that out well the first thing to think is first thing to think is we don't want to really think about this we don't want to really think about this as a triangle it's more like a matrix as a triangle it's more like a matrix and what we'll do is for each number in and what we'll do is for each number in the middle the middle we're going to just look above the list we're going to just look above the list above us above us and add like starting with let's say and add like starting with let's say this is zero we'll say zero this is zero we'll say zero or i say this is one so say one or i say this is one so say one plus one minus zero and here well this plus one minus zero and here well this one would end but one would end but like for instance this one would look at like for instance this one would look at two two and two minus one so it would add the and two minus one so it would add the ones above one and two ones above one and two and add it together so we don't really and add it together so we don't really don't need to complicate this let's just don't need to complicate this let's just do it iteratively do it iteratively and what we'll do is first initialize and what we'll do is first initialize our output to be a our output to be a list of list with one at top because we list of list with one at top because we know that's our base know that's our base case now we'll say four case now we'll say four let's say row and range of starting at let's say row and range of starting at the second the second all the way to num rows plus one all the way to num rows plus one and this will make it a little bit and this will make it a little bit easier to calculate the column now we'll easier to calculate the column now we'll first initialize first initialize a a list a a list and have one for the left side first now and have one for the left side first now we'll say four column in range of what we'll say four column in range of what starting at one all the way to r starting at one all the way to r but we have to subtract one from the row but we have to subtract one from the row right right and we'll add let's see temp append and we'll add let's see temp append we're going to look above us we're going to look above us the very last output thing we added with the very last output thing we added with c c plus output minus one plus output minus one c minus one finally at the very end c minus one finally at the very end we're going to also add one to enclose we're going to also add one to enclose it it and then make sure to add that to our and then make sure to add that to our output output now this should work let's return our now this should work let's return our output after we're finished output after we're finished let's test that out okay so that looks like it's working and accept it so what's the time and accept it so what's the time complexity it's going to be n squared or complexity it's going to be n squared or num row squared because we have to do num row squared because we have to do this nested for loop i don't really see this nested for loop i don't really see how that's avoidable how that's avoidable you can certainly clean this up to make you can certainly clean this up to make it look nicer or you can even do it it look nicer or you can even do it recursively but recursively but i really don't think there's any reason i really don't think there's any reason to over complicate it just do it to over complicate it just do it straightforward and yeah it looks like it works so alright thanks for watching my channel remember do not trust me | 2024-03-21 10:59:30 | 118 | Leetcode - Pascal's Triangle (Python) |
|
sUtUgMW2kMY | going to do video number 28 of my channel. Okay and I suggest you again that I am making a separate playlist. Listen very carefully in which I will have both concepts and questions related to dynamic framing. This playlist contains only questions. Ok so main 1964 it is a very good question, it will seem hard but it will make it easy for you. Ok, the question will become quite easy if you understand it well. Just understand the ok question number. Find D longest valid optical course. Aate position. Ok it is by What is the question? What is the question? What is the question? Okay, Okay, look at what is said in the question that look at what is said in the question that you will be given a vector named status, you will be given a vector named status, where I means that he has where I means that he has jobs at rectangle position. Okay, what is his height? It is jobs at rectangle position. Okay, what is his height? It is clear to you till now. clear to you till now. clear to you till now. you have to remove what they see right what should be your result you have you find D longest of circle course in obstacles true date ok true date you choose other number of obstacles between zero nine inclusive look and second point what you mast D Course You Must Pat D D Course You Must Pat D D Course You Must Pat D Choose Opticals In D Se Order In Choose Opticals In D Se Order In Obstacles Ever Give And Se Height S The Obstacles Ever Give And Se Height S The Optical Immediately Before It Is G So It Is Optical Immediately Before It Is G So It Is Very Difficult Lines It Is Very Very Difficult Lines It Is Very Simple Let's Understand It With The Help Of This Example Simple Let's Understand It With The Help Of This Example Okay Okay Okay very simple given in two questions that it should give you optical, right, zero one to three of each index, okay, so now see what he is saying, like mother, now stand here, okay, You can erect it, it will You can erect it, it will You can erect it, it will depend on whatever depend on whatever opticals are there nearby, okay, whatever opticals are there nearby, okay, whatever opticals are there nearby, if they are equal to this one, then you can pick them up and put them here, okay, let me you can pick them up and put them here, okay, let me see the example, see the example, what do you mean? what do you mean? what do you mean? can put smaller than you, one was one and this is the can put smaller than you, one was one and this is the second one, second one, okay, similarly, if I come to this 3, then I have okay, similarly, if I come to this 3, then I have seen how many seen how many elements are there before it, which are the colors one, which is elements are there before it, which are the colors one, which is Lee dene equals tu three hai tu hai, which is li Lee dene equals tu three hai tu hai, which is li dene = 3, so I can include these two also, so I have dene = 3, so I can include these two also, so I have put one, I have put tu put one, I have put tu and these three will put themselves, it and these three will put themselves, it will be okay, so here I will include all three. will be okay, so here I will include all three. So you are seeing how much you can take here, So you are seeing how much you can take here, two is written here, two is written here, how much you two is written here, two is written here, how much you can take is three or look, three is written here, it can take is three or look, three is written here, it comes here, okay now look, I am standing here, comes here, okay now look, I am standing here, before that let's see, there is one, which is Lee. before that let's see, there is one, which is Lee. before that let's see, there is one, which is Lee. equal tu hai which is li Give equal tu hai three which is is something before it otherwise this is something before it otherwise this poor fellow will go alone, here poor fellow will go alone, here its length will always be one of the first element its length will always be one of the first element because there is nothing behind it, okay because there is nothing behind it, okay because there is nothing behind it, okay is clear till now, then you understand how to build it. Okay, so see, let's try to understand how to build your solution. Okay, so right now you are a little scared. Earlier, I told you that mother is late. If you are standing here, then You are looking for which are the You are looking for which are the You are looking for which are the elements before this which are smaller than this, elements before this which are smaller than this, okay, those which are smaller than this i.e. look, there is okay, those which are smaller than this i.e. look, there is one, you are okay and and the longer all these one, you are okay and and the longer all these sequences are found, the better it is, right sequences are found, the better it is, right here? here? here? and three itself has become an element, so see, we are getting a long sub sequence, one is three, or if we look at it, if I am lying here, I am standing here, I am standing on you. So, who all are smaller than you? Look on the left side of you. One is small, you are small, three are not small, so we got the lowest one, one is you, who is the tallest, what is the size of the tallest, three is ok, the If there was three, then you are paying attention, If there was three, then you are paying attention, If there was three, then you are paying attention, what is it what is it actually? Actually, there is no longest increasing actually? Actually, there is no longest increasing sequence. Those who have sequence. Those who have read the longest increasing sequence, they must be understanding what read the longest increasing sequence, they must be understanding what I am saying. Six is I am saying. Six is okay, okay, all the sequences are okay so let's see. all the sequences are okay so let's see. all the sequences are okay so let's see. us know what it is asking at each point, it is asking us that brother, tell me the longest increasing sub sequence that is going to happen at this point, okay, it is going to end at this point and here it But he is saying that it But he is saying that it But he is saying that it can also be equal like see what is the longest increasing sub sequence ending at this point what is the longest increasing sub sequence ending at this point 1 2 2 its length is 3 right it should be increasing 1 2 2 its length is 3 right it should be increasing or it should be equal then see 1 2 or it should be equal then see 1 2 and 2 are equal. and 2 are equal. 1 2 3. If asked from this point, it's 1 2. If we 1 2 3. If asked from this point, it's 1 2. If we go by this point, it's self-made. Okay, so actually he is asking us. Okay, so let's reduce it now, that is, asking us. Okay, so let's reduce it now, that is, what does it mean that I what does it mean that I write the length of the longest increasing sub-sequence at the point, that will be my answer and it should write the length of the longest increasing sub-sequence at the point, that will be my answer and it should also be correct, so let's do one less, also be correct, so let's do one less, we will not recall we will not recall what we used to do in the sequence, okay then what we used to do in the sequence, okay then look at the list, first understand people, then this look at the list, first understand people, then this question is also very difficult. question is also very difficult. question is also very difficult. I said that it is not hard, it is easy, if you know it well, then take mother in it. To understand, I have taken this example and to make alloys from bottom up, If you have If you have If you have n't read then there is no problem, I will tell you n't read then there is no problem, I will tell you what we used to what we used to do to make it from the bottom, we used to take a simple waiter, okay do to make it from the bottom, we used to take a simple waiter, okay and its length is taken, how much is one, two, three, zero, one, two, three, and its length is taken, how much is one, two, three, zero, one, two, three, four, five, okay, it No because look, now we need sub sequence, one itself No because look, now we need sub sequence, one itself No because look, now we need sub sequence, one itself is also a subsequence, so what is is also a subsequence, so what is its length, one is also 14, what is its length, one is also 14, what is itself a subsequence, 46, what is sub itself a subsequence, 46, what is sub sequence, 42 is itself a subsequence, sequence, 42 is itself a subsequence, so brother, one can see the length. so brother, one can see the length. Now how do we find the longest, we will see how to Now how do we find the longest, we will see how to find this longest, so what find this longest, so what I did in the beginning is, I I did in the beginning is, I took a vector named T, okay and I am saying took a vector named T, okay and I am saying that the length of all is one only, okay and that the length of all is one only, okay and define the state. define the state. define the state. what should I say, if the state is defined, then half the solution is yours. Do you know what will happen brother, longest increasing sub sequence ending comes index, I ok, longest increasing sub sequence ending comes What is it, I have What is it, I have What is it, I have understood till now, now look pay understood till now, now look pay attention, I started the index here, okay, the index has come, no, sorry, the index has come here, I have to file for this, okay, so what will I do, I will see that All the elements before the rectangle element All the elements before the rectangle element All the elements before the rectangle element What is there in IPL Here all the What is there in IPL Here all the elements before it Which one is elements before it Which one is smaller than this So there is smaller than this So there is no element before it Right Where no element before it Right Where is there any element before it Right Brother i.e. is there any element before it Right Brother i.e. is there any element before it Right Brother i.e. mean that the longest increasing sequence ending at zero index is billed to be one only and obviously there will be only one, I can see there is nothing before it, so the I can see there is nothing before it, so the answer is one, so the length is of answer is one, so the length is of zero. zero. zero. okay, I came here, now I okay, I came here, now I will see what is right, brother, there is will see what is right, brother, there is four in Namas here, okay and four in Namas here, okay and how many elements are visible before four, whatever how many elements are visible before four, whatever elements are visible. elements are visible. elements are visible. who all are there who are smaller than this. Okay, so what will I do? Which index am I on now? I am currently on one eight index, so I start K from zero. I start G from zero. Okay, so that means with this force, first I will go to all the elements one by one, so first I came to one, it was 0. I am asking, brother, I am asking the element with zero thindex, are you the small one, the The element will say yes The element will say yes The element will say yes because I am one, one take it as 4, because I am one, one take it as 4, what does it mean, one take it 4s, so what what does it mean, one take it 4s, so what happens that increasing can be formed, only after one, happens that increasing can be formed, only after one, four will come, four will come, increasing can be formed, so I will increasing can be formed, so I will say one, no brother. say one, no brother. say one, no brother. and what was the longest increasing sequence, then zero will say coldly that brother, the one that ended in me was the longest seeds, its length was one, okay and the four which is It is sitting, it can be appended on this It is sitting, it can be appended on this It is sitting, it can be appended on this because this is one, this is one, so because this is one, this is one, so it is smaller than four, so brother, on this it is smaller than four, so brother, on this and the next one is on zero and and the next one is on zero and which was the longest subsequence itself, this was one, which was the longest subsequence itself, this was one, okay him. okay him. okay him. brother 03 What is the longest requins on you brother 03 What is the longest requins on you will say if there is one, then what will happen, you will become will say if there is one, then what will happen, you will become okay and already what is there in T of one, if one is okay then one is big or one and or okay then one is big or one and or okay then one is big or one and or this T of I bigger or where is K now? There is a right on it, it can be added because it is smaller than bigger then what will happen is this T what is my one and DJ If If If you want to make it bigger among the two, then I will update it, you want to make it bigger among the two, then I will update it, okay, you may be feeling a okay, you may be feeling a little confused right now, go ahead, let's little confused right now, go ahead, let's expand the diary further and it will be expand the diary further and it will be clear, okay, okay, I had clear, okay, okay, I had started it. started it. started it. till zero, after that it will become equal to i, ok, so now look at t of i, what has happened to me, understand that carefully, the value of t of one is tu, meaning what happened that. value of t of one is tu, meaning what happened that. length of the longest increasing sub sequence ending at index number one length of the longest increasing sub sequence ending at index number one is tu and that is also correct. Who is that? One comma four is increasing is also right and its length is tu so 10. Our answer here is tu. Now my index is here My index is here, now My index is here, now My index is here, now what I said again is that I what I said again is that I will start from K and where is the index on Tu, Na is on A, will start from K and where is the index on Tu, Na is on A, whatever is on 2, I will compare whatever is on 2, I will compare that the element on Jeth is that the element on Jeth is correct and the element on which is correct and the element on which is correct and the element on which is one small then six can be appended to the longest sequence ending at one. Right then I will ask on one that brother, what are your long sessions, then he will say, You will be You will be You will be done and there is already one value here done and there is already one value here so I can update it, you have got a big so I can update it, you have got a big one, okay, it's great, now I am one, okay, it's great, now I am here, okay, is this on the small one, so I will ask the one, brother, What is the longest increasing What is the longest increasing What is the longest increasing subsequence ending, brother will say, it ends in me, it subsequence ending, brother will say, it ends in me, it is okay and maybe right, if you make it plus one three then it cannot flood further and because < has to be continued till i only, now the value of tuffy is 3, What happened is that there must have been What happened is that there must have been What happened is that there must have been many sub-sequences ending at the second index, many sub-sequences ending at the second index, but which is the largest increasing sub- but which is the largest increasing sub- sequence, it is three in length and sequence, it is three in length and who it is, you must have seen it too, 1/46, okay, who it is, you must have seen it too, 1/46, okay, who would know this very well, if who would know this very well, if you you you Now let's move ahead. Now let's move ahead. Okay, it will start from here and I will compare. Okay, then I will compare. If the winner is okay, then I will ask brother, the one that will end on victory So I will check that the element on K is So I will check that the element on K is okay so increasing sub sequence can be formed then you will go to a so this and by the way you then you will go to a so this and by the way you are a big value so I have cated it and done are a big value so I have cated it and done okay now this is further flooded give okay now this is further flooded give four four li banega look at the value of t of three, you are fine, what does it mean that the longest allen ending in the third index can only be two and you see the right thing is by Look, these two which are on index number three are Look, these two which are on index number three are Look, these two which are on index number three are fine, they are coming to an end, fine and our answer is also you. Look, there is a 2 here, that is, we are making it absolutely correct. Okay, if you see, it must have been understood to When I will proceed here, okay, When I will proceed here, okay, When I will proceed here, okay, then come again, I will start from here. then come again, I will start from here. Whom is I pointing to? What is the fourth index? Is Whom is I pointing to? What is the fourth index? Is one < 3, is it one < 3, is it smaller than the element one? Yes, it is smaller than one, then it is three, which means it So I So I will look at the length of the longest increasing sub sequence ending on K. It is one. I can add one to it. This three which is one element can be added. Okay, so I will add this, so how much will it be, This one is small, so I This one is small, so I This one is small, so I will update it here. Okay, then when the will update it here. Okay, then when the element came here, what is three, this is messed up. 4 < 3 is not there, this is also not six, give But when it But when it But when it comes to 2 < 3, yes, then what do I do? comes to 2 < 3, yes, then what do I do? Jeth and which is the longest ending on this index, then the length of the longest ending on this index was through, if we convert it to three, It is clear till now, it will come till this point, okay, now clear till now, it will come till this point, okay, now look at one thing, the one ending on this index is going to look at one thing, the one ending on this index is going to end on the fourth index, the end on the fourth index, the length of the longest increasing sequence is length of the longest increasing sequence is three, I am saying three and that is correct, it will be only three, three, I am saying three and that is correct, it will be only three, see this one, see this one, you you you index number five, now find out ok guys, its code is very simple, isn't it, see how simple it will be, if i is doing its move, enter i = 0, give n i Plus ok, after that what I was saying is Plus ok, after that what I was saying is Plus ok, after that what I was saying is starting from 4j = 0 k plus will be plus starting from 4j = 0 k plus will be plus ok and when was I doing ok and when was I doing when the name off k if the when the name off k if the name was getting smaller clearly but remember this time name was getting smaller clearly but remember this time not smaller. not smaller. not smaller. that Equal Tu Bhi Chalega is ok, so what was I doing, I was updating the T of I, it may be included, it may have been cleared till now and what should I do, lastly this T is battery. This is my answer, please send us the result only, then it actually passes or not, okay, after that we will go to optimal, so let's submit it from the court and see, then you are able to pass, the and what I said. and what I said. and what I said. of and t, keep the length one because each keep the length one because each element itself is a sub sequence, its element itself is a sub sequence, its length is one, okay, now start updating, you, after what I said that you we you, after what I said that you we you, after what I said that you we go to each element from zero to i, whichever element is smaller or equal, they can be made into a longest increasing vegetable. Okay, F is the name can be made into a longest increasing vegetable. Okay, F is the name equal to the number of i. Okay, so equal to the number of i. Okay, so what will I say, what will be T and I. what will I say, what will be T and I. what will I say, what will be T and I. maximum of T5 which will be already value will be Rakhi means the value which will be on LIS Aate Index I is already either that or the maximum which I will get now means I will ask K that brother, DJ, DJ, DJ, why did we add plus one in that now because the vein of why did we add plus one in that now because the vein of IB can now be included, it is okay to return T okay to return T and here also there will be LISS, let's try it later and it remains to be seen and it remains to be seen but it is okay but it is okay but let us go to the optimal story. but let us go to the optimal story. but let us go to the optimal story. do something so that it becomes optimal. Abstract content is very high. Okay, so let's see how we can optimize it. Now look at the optimal solution. First understand its essence. Okay, how will it come to mind that the meaning should be taken forward with this approach. Okay, so I have taken an example. Look at this example carefully. Here, if I tell you to find the longest increasing sub- sequence and show it, then you must be seeing that one is greater than one, four is greater than four, six is It is visible that It is visible that It is visible that you are bigger than 11. You are bigger than three. Five is visible to you. Okay, you must be seeing you are bigger than 11. You are bigger than three. Five is visible to you. Okay, you must be seeing so just remove this 5. Okay, now let's assume that one is ok. Now let's assume that there is an element. Okay, okay now I have to find out what is the longest common longest increasing sequence ending in this fifth index, exactly which contenders are visible, you are seeing these two contenders, one is visible. Look, it is visible that brother in which five will be added, pay attention to one thing, five cannot be added here right because it [Music] I don't know the difference from which person There is a difference from the last one There is a difference from the last one because when I had to bring five, what did I see? After every sub sequence, I went and saw how the last one is, here the last one was six, give a greater five, that is why five cannot be appended here. Right and here whenever the subsequence is near, then see here yesterday the last band of this subsequence is the last band which is smaller than five isn't it smaller than five date this three is okay so hence it will be appended to this We will get the bigger one, but whom did I prefer, brother, the one whose but whom did I prefer, brother, the one whose last element is shorter, okay, so last element is shorter, okay, so friend, friend, what information do I need, do I need the information that brother takes mother, someone one is this one, this one is this. whose ending element is the smallest whose ending element is the smallest ending element is three ending element is three Okay so this time know what I will do Length used to be length but now what is more important to me is that I have to know the length of the longest increasing sequence It means It means It means here, was it six or three, I here, was it six or three, I mean, I will prefer the smallest one. mean, I will prefer the smallest one. Okay, so tell me what will happen this time, Okay, so tell me what will happen this time, define the state, see how I will do it, what was the sub signal, I plus one, zero Subsequence Subsequence Subsequence means its maximum is i plus one okay its length is i plus one and know the ending element what is that is When I came to know about retirement from, I thought that When I came to know about retirement from, I thought that if I had told you directly that brother, define this state, if I had told you directly that brother, define this state, then you would not have understood then you would not have understood how this thing would have come in our mind. how this thing would have come in our mind. From this example, it would have been clear to you From this example, it would have been clear to you that brother, it should be even. that brother, it should be even. that brother, it should be even. its length is also 3, first of all there are three but but which is the one whose ending element is the smallest, so I want the information of the ending element, so here the length of i = length is y+1 and the ending element is x, If yes, then what will be the benefit of it, let's see. If yes, then what will be the benefit of it, let's see. If yes, then what will be the benefit of it, let's see. Okay, so to Okay, so to understand this, let's take an understand this, let's take an example. Okay, we have example. Okay, we have taken this example and right now our taken this example and right now our vector of aliens is empty because right now we have vector of aliens is empty because right now we have not included any India in it, okay then more. not included any India in it, okay then more. What I mean by fitting you again is that What I mean by fitting you again is that i + 1 is the length of the sub sequence and what is the i + 1 is the length of the sub sequence and what is the ending element of the sub sequence. Okay, ending element of the sub sequence. Okay, what is the ending element so and you what is the ending element so and you remember here when I told you remember here when I told you that ending. that ending. that ending. six, here there is three, okay, so now who is smaller is three and who is bigger than 5, okay, so I had placed 5 here, okay and It was It was It was because it is given in the question because it is given in the question that it can be equal, if you cycle is fine that it can be equal, if you cycle is fine then it can be three, it can also be equal, like mother takes, now I have come and am standing here, okay, so what would I like, Whose end is the Whose end is the Whose end is the ending element whose indicative element is less than one or ending element whose indicative element is less than one or equal to one, you are fine and due to the material, I will see more brother which is the ending element which is equal to one or either take, okay then see, right now my whole Right, what will I do, now look at Right, what will I do, now look at Right, what will I do, now look at where I am, is it at zero? Okay, so what will where I am, is it at zero? Okay, so what will I do now? Simply I do now? Simply tell me here, brother, there will be one here, now understand tell me here, brother, there will be one here, now understand what is the meaning of one here, okay first the what is the meaning of one here, okay first the brother, then his. brother, then his. brother, then his. happened brother, the length of all this sequence is happened brother, the length of all this sequence is one, what is the meaning of zero plus one, one, what is the meaning of zero plus one, zero zero plus one and its ending element is one, which was plus one and its ending element is one, which was this banda, you are the this banda, you are the sequence and what is simple. clear is clear clear is clear and one thing is not paying this to the forest on which index and one thing is not paying this to the forest on which index happens that i + 1 is its length, zero plus one is its length i.e. one and its ending element is one. Okay, so I also write here in the result, which index is it brother? Here the index is kept at zero element. So what will I do here? What will be the result of half of the index? This is zero, neither It It It will be right and will be right and 0 means again I am telling that brother 0 means again I am telling that brother 0 + 1 is its length, it is the index 0 + 1 is its length, it is the index of sub sequence and sending helmet is one, okay let's go okay of sub sequence and sending helmet is one, okay let's go okay don't take tension okay further don't take tension okay further I came here but I came here but okay now okay now okay now that which brother is the brother, there can be many sub-sequences, I have to find the one who can take four or equal, you are right and it should be bigger too, that is right, so The one The one The one ending element is needed, the sub sequence is ending element is needed, the sub sequence is needed whose end force is equal, needed whose end force is equal, either it is smaller, it is ok, then who is that brother, right either it is smaller, it is ok, then who is that brother, right now I see only one guy in my life now I see only one guy in my life who is just smaller than four, give equal, who is just smaller than four, give equal, you are right. you are right. you are right. can be here, after this, four can be here, after this, I will make four here and it will be appended here, next is one, till now it is clear, till now it is clear, now think for yourself which one. now think for yourself which one. now think for yourself which one. Okay, so what is the length. The length of all this sequence is two. So, this index that has come here, make it one, that is, it will go to two, It is clear till now, go ahead, ok, now It is clear till now, go ahead, ok, now It is clear till now, go ahead, ok, now look, we will do the same thing again, which is the look, we will do the same thing again, which is the subsequence subsequence which is less than 6 and either is equal, then there is also one, there is a subsequence whose ending element is one subsequence whose ending element is one and one more subsequence is equal to two. But think about which one you will choose. Whom will you choose? This is such a subsequence, what is its length? 1 + 1 2. All these will be Okay, so what will you do? You will append this. Okay, if you band it, then six will come here. Okay, append this. Okay, if you band it, then six will come here. Okay, and which index is A? and which index is A? and which index is A? index the fruit will come, on the index that three, that is the length of the sub sequence and three, that is the length of the sub sequence and what is the length of what is the length of that sub sequence, okay and its last band is that sub sequence, okay and its last band is six, that is what is written here, it is six, that is what is written here, it is okay and who would have written it here? okay and who would have written it here? Brother, last Sunday, which Brother, last Sunday, which index is it, that is, index is it, that is, what will be its height, how much will be the length from all the coins, it will be what will be its height, how much will be the length from all the coins, it will be 3, it will be 2 + 3, so here I have written three, it is clear till now, look at this clear till now, look at this very important part now. very important part now. very important part now. what will I do, I want such an element, I want such a sequence whose ending element is less or equal, you are ok, then let's see, is one, that is, yes one, is four, that is not four, if not, four is So, you can't take that one, you So, you can't take that one, you So, you can't take that one, you can take one, okay, now pay attention to one thing, can take one, okay, now pay attention to one thing, this is coming from Jehovah every time, this is coming from Jehovah every time, okay, so you can hit simple binary search, okay, so you can hit simple binary search, either you will do it tomorrow or either you will do it tomorrow or what will you do, now what I wanted to find is that you what will you do, now what I wanted to find is that you Se just le den or equal tu or aisa Se just le den or equal tu or aisa maa ke chalo pay attention to index one already I have an element four, what does it mean index hua means what is the length of the sequence is two and what is the ending element is kar and You must be seeing that whose ending element is going to be tu, its length is also going to be two because that is its index one, right now, it is an obvious thing, what did I tell you that which one will I choose, if it is shorter then will you If you become something, then If you become something, then If you become something, then brother, if something happens to you, then on index 1, I will not give you the pulse, brother, if something happens to you, then on index 1, I will not give you the pulse, I will remove it, okay, what did I do, it I will remove it, okay, what did I do, it came here, neither, I have given you the pulse, it is came here, neither, I have given you the pulse, it is okay here, because the one which is smaller, I okay here, because the one which is smaller, I will prefer this one in the future. will prefer this one in the future. index is clear till here, index is clear till here, how many which index did I get, index how many which index did I get, index got one, okay, meaning what is the length, one got one, okay, meaning what is the length, one plus one is you, so here I have plus one is you, so here I have given you, okay till here, it is clear, now I have come. given you, okay till here, it is clear, now I have come. given you, okay till here, it is clear, now I have come. came here ok, now let's see, take out the element just bigger than three of three, okay now if you drive this one, it will be more clear, okay take out the element bigger than three, 10, that is, who is bound on you three Brother Brother Brother six hai to IDEX ke a jaayega tu aaya six hai to IDEX ke a jaayega tu aaya hoga ok what does it mean that hoga ok what does it mean that IDEX tu aaya but already a banda IDEX tu aaya but already a banda is present ok what does it mean is present ok what does it mean that there is a sub sequence whose length that there is a sub sequence whose length is na to tu plus one i.e. 3 also means its length is 3, which means one comma, 2, 3. Which one will you choose, so I removed it and gave three pulses. The shorter you choose, the better it is, right for the future, this is what I understood, this was the most important part, so IDEX, you Tha na to tu plus one date is three the Tha na to tu plus one date is three the Tha na to tu plus one date is three the answer is answer is ok and here who will be those three guys ok and here who will be those three guys this one and you and three there is this one and you and three there is nothing to do with 12 just append five in the last Will A automatically go to Will A automatically go to Will A automatically go to three A, meaning three A, meaning what happened brother, this sub sequence has landed, what happened brother, this sub sequence has landed, okay and I know which is the sub sequence, the ending is on five and before that which will be 3, you will be How will be the code of one two three five, it will be very How will be the code of one two three five, it will be very similar to that, okay, clarification, what is the meaning of this equal two x, is it telling that I plus one is the sub sequence He will He will He will understand that you have to understand that you have to write the story point. Okay, what did I say that I will take the vector of Rajasthan and its statement has told you what is the meaning of Aliens of I = I will move forward on my own sequel, you are Okay, I will take out IDEX, OK, I will take out IDEX, Okay, I will take out IDEX, OK, I will take out IDEX, if I come to know that if I come to know that IDEX, which is ideal, is IDEX, which is ideal, is of LIS and I have not found this equal, I have not found of LIS and I have not found this equal, I have not found anyone just all of them. anyone just all of them. anyone just all of them. are small, so what did I say, just push back, no, all of them are small, okay, and if it is no, all of them are small, okay, and if it is not so, I have got it, then what do I not so, I have got it, then what do I do, I was giving it to the guy in DS. do, I was giving it to the guy in DS. Right, the current one will return the off cycles, the result is ok, so actually the state was the face part and it got cleared and you have dried it and done it well, the biggest thing was to drive this, this If you have done this, then you have understood the questions. If you have done this, then you have understood the questions. If you have done this, then you have understood the questions. Okay, I will find this and a vector of eight results. I will find the bigger element. Okay, you can also write your binary search. from the current substerl. It is okay and we will mine it to get the index because mine it to get the index because mine it to get the index because add optical psycho in IDEX ok and what we used to put in the result puts the length of sequence in the result I put my history plus one ok | 2024-03-25 13:27:06 | 1,964 | Find the Longest Valid Obstacle Course at Each Position | META | Leetcode-1964 | Live Coding |
|
TUC1H9R6Dw8 | code three five zero 350 intersection of two arrays two all right so there's two arrays two all right so there's another version for this one we've another version for this one we've already done it go back and check into already done it go back and check into my videos my videos um so given two integers arrays nums one um so given two integers arrays nums one and nums to return an array of their and nums to return an array of their intersection each element in the result intersection each element in the result must appear as many times as it shows in must appear as many times as it shows in both arrays and you must return the both arrays and you must return the results in any order so this one will results in any order so this one will include duplicates so we're not going to include duplicates so we're not going to be using hash set which eliminates be using hash set which eliminates duplicates duplicates and so if you're given like for instance and so if you're given like for instance array number one one two two one and array number one one two two one and then Arena two two then you're gonna end then Arena two two then you're gonna end up with the output should be two two up with the output should be two two okay let's get into it okay let's get into it so basically the first thing I'm gonna so basically the first thing I'm gonna do we're going to start by sorting the do we're going to start by sorting the arrays and then the next thing we're arrays and then the next thing we're just gonna create these two pointers just gonna create these two pointers pointer I and J pointer I and J and another thing this we're gonna and another thing this we're gonna create our list which will be storing create our list which will be storing the um it's gonna be storing the the um it's gonna be storing the elements the elements uh which are elements the elements uh which are basically like the intercepted elements basically like the intercepted elements the ones which are in the intersection the ones which are in the intersection okay okay and then yes so the here uh what's gonna and then yes so the here uh what's gonna What's Happening Here is that we are What's Happening Here is that we are taking the pointer and we are checking taking the pointer and we are checking if it's less than than the length of the if it's less than than the length of the first array and the pointer J as well first array and the pointer J as well checking if it's less than checking if it's less than um um the the the second Arena too so basically which the second Arena too so basically which I can point our I less than num1 I can point our I less than num1 dot length and pointer J less than num2 dot length and pointer J less than num2 dot length so if this condition is dot length so if this condition is if this condition is met we're gonna if this condition is met we're gonna keep on repeating the process which is keep on repeating the process which is inside our while loop and then inside inside our while loop and then inside here the while loop we are comparing the here the while loop we are comparing the two elements this is where we're two elements this is where we're basically checking if the elements there basically checking if the elements there is any sort of intersection so if is any sort of intersection so if pointer num at index pointer I is equal pointer num at index pointer I is equal to num2 at index Point J then we're to num2 at index Point J then we're going to add that element element which going to add that element element which is a basic instant it's it's exists in is a basic instant it's it's exists in each of those arrays basically that's each of those arrays basically that's what it means so we're gonna just add it what it means so we're gonna just add it there and then after we do that we're there and then after we do that we're gonna increment basically both pointers gonna increment basically both pointers J and then yeah uh we're gonna go back here and then we're gonna do the same thing check if it's the same else if it's not if if this cont is complete this condition fails if the address no intersection then we're gonna check we're gonna say nums one quarter I if it's less than num 2.0 J then we're gonna increment I else we're going to increment J and here's the front part guys here we're just taking the inter we are basically going to be uh building our intersection basically we're gonna put all the elements which are common in both arrays so we just create this for Loop for each Loop and then we are incrementing at K and telling me that the element here to here and we'll be turning it at the end and there we go I will see you guys in the there we go I will see you guys in the next video please don't forget to next video please don't forget to subscribe | 2024-03-24 11:16:17 | 350 | Intersection of Two Arrays II Leetcode 350 Java Solution[NEW] |
|
wVR2FbDWvqU | hello everyone so in this video let us talk about the problem from lead code talk about the problem from lead code it's a medium problem the problem name it's a medium problem the problem name is design a circular DQ so you actually is design a circular DQ so you actually have to design a double ended queue that have to design a double ended queue that is a DQ you have to implement these is a DQ you have to implement these functions so if you know about Q then functions so if you know about Q then it's just an extended version of a queue it's just an extended version of a queue in queue we'll insert from one end and in queue we'll insert from one end and take out from another end if I just draw take out from another end if I just draw it out so accused data structure in it out so accused data structure in which you can assume that this is a pipe which you can assume that this is a pipe you insert elements on the very back you insert elements on the very back okay and you can only insert like pop it okay and you can only insert like pop it out or take it out from the very start out or take it out from the very start so let's say if you insert one element so let's say if you insert one element that is this so that let's say the that is this so that let's say the element is one then you can only insert element is one then you can only insert the next element after it so let's say the next element after it so let's say two then three so that's a queue okay two then three so that's a queue okay like whenever you like to go to buy like whenever you like to go to buy something from a shop there's a queue so something from a shop there's a queue so you like you get in the back and you you like you get in the back and you only start taking off another very only start taking off another very friend but that DQ is a special type of friend but that DQ is a special type of queue in which you can like you can queue in which you can like you can insert from the back or pop from the insert from the back or pop from the black as well as well as you can insert black as well as well as you can insert from the front and pop on the front so from the front and pop on the front so you can do all of these operations on a you can do all of these operations on a double ended queue so double ended queue double ended queue so double ended queue so that is called a DQ this is d so that is called a DQ this is d we have to implement that and so the we have to implement that and so the different functions regarding DQ is that different functions regarding DQ is that you can insert pop insert pop on back you can insert pop insert pop on back front you can find out the size whether front you can find out the size whether it is empty or not but there is a hard it is empty or not but there is a hard limit in this DQ that it should be only limit in this DQ that it should be only consisting of key elements the total consisting of key elements the total elements at any moment of time in the elements at any moment of time in the queue should be less than equal to K queue should be less than equal to K that's over the thing now there are that's over the thing now there are different function let's say insert different function let's say insert front of the DQ so if it can be inserted front of the DQ so if it can be inserted such that the total end should not be such that the total end should not be greater than k then you can insert the greater than k then you can insert the element as well as return true but if it element as well as return true but if it is not possible to insert in the DQ then is not possible to insert in the DQ then return false similarly inserted the last return false similarly inserted the last delete from the like back by deleting it delete from the like back by deleting it means that like removing or popping out means that like removing or popping out so delete from the front delete from the so delete from the front delete from the end if you are able to read it or you end if you are able to read it or you can check it out if there are some can check it out if there are some elements in the DQ at least then only elements in the DQ at least then only you can remove what elements if you can you can remove what elements if you can remove from the front or back it will remove from the front or back it will return true as return false then get return true as return false then get front will tell you what is the front front will tell you what is the front element the back element get back and if element the back element get back and if there is no front to back element return there is no front to back element return minus one similarly for is empty we'll minus one similarly for is empty we'll check that whether the whole DQ is empty check that whether the whole DQ is empty and is full means that whether the 2 is and is full means that whether the 2 is full DQ is full that is it the size of full DQ is full that is it the size of that is equal to K so it's pretty simple that is equal to K so it's pretty simple you can directly use so C plus plus you can directly use so C plus plus actually gives you a little structure actually gives you a little structure that is DQ directly uh out of the box so that is DQ directly uh out of the box so you can directly use D you don't have to you can directly use D you don't have to implement that you can also actually use implement that you can also actually use a vector to implement a queue like DQ as a vector to implement a queue like DQ as well but because we have DQ that tree well but because we have DQ that tree out of the box from like provided by C out of the box from like provided by C plus we can directly use that so what we plus we can directly use that so what we have done that we moved under the board have done that we moved under the board because nothing much is here to explain because nothing much is here to explain as such the code will be sufficient as such the code will be sufficient enough so what we can do is that we have enough so what we can do is that we have this DQ that we have implemented in a this DQ that we have implemented in a global uh case you can assume at Global global uh case you can assume at Global State and this is a DQ and the capacity State and this is a DQ and the capacity that is cap that will be stored what is that is cap that will be stored what is the maximum capacity I can be stored the maximum capacity I can be stored inside the DQ so while we're inside the DQ so while we're initializing this details initialize in initializing this details initialize in the global state but we have to the global state but we have to initialize this like uh what is the size initialize this like uh what is the size of the QV or DQ actually up to you so of the QV or DQ actually up to you so that will be stored here now let us go that will be stored here now let us go down to each individual function so down to each individual function so insert front Okay so we can only insert insert front Okay so we can only insert in the front of the DQ when like until in the front of the DQ when like until they are less than K elements if it is they are less than K elements if it is more than more than K elements we cannot more than more than K elements we cannot so we should check that the size of the so we should check that the size of the queue should be less than the maximum queue should be less than the maximum capacity Which is less than the maximum capacity Which is less than the maximum capacity then only we can add the like capacity then only we can add the like the element so we will push front that's the element so we will push front that's the function we will be using with DQ if the function we will be using with DQ if you want to push in the front of the DQ you want to push in the front of the DQ so push front Okay we have to insert so push front Okay we have to insert this value and return true because we this value and return true because we have post like it is possible or we have have post like it is possible or we have inserted a value in the front of your EQ inserted a value in the front of your EQ so you don't Drew has written false so you don't Drew has written false because we are not similarly for the because we are not similarly for the last this is push back so push front and last this is push back so push front and push back are the functions for push back are the functions for inserting in the front and back of the inserting in the front and back of the DQ Point uh down so let's move it down DQ Point uh down so let's move it down so at last so at last the next function is delete front so for the next function is delete front so for deleting out we have to ensure that deleting out we have to ensure that there should be some element inside the there should be some element inside the DQ so the DQ side should be greater than DQ so the DQ side should be greater than equal to zero greater than zero actually equal to zero greater than zero actually not greater than equal greater than zero not greater than equal greater than zero so we'll just check that the size object so we'll just check that the size object should be greater than zero then only should be greater than zero then only we'll go outside this function pop so we we'll go outside this function pop so we have to pop out or delete out element have to pop out or delete out element from the front so pop front we delete from the front so pop front we delete the front element from the DQ if it is the front element from the DQ if it is possible to read will it run true as it possible to read will it run true as it does false and also delete out the like does false and also delete out the like the front element as is the back so pop the front element as is the back so pop front and popper back we return the front and popper back we return the black will delete the front and the back black will delete the front and the back elements similarly if we'll move on to elements similarly if we'll move on to now we have to get the elements okay so now we have to get the elements okay so when we want to get the elements because when we want to get the elements because when we want to get the front element in when we want to get the front element in the same thing we have to just check the same thing we have to just check that we can only get the elements if that we can only get the elements if there are actually some elements inside there are actually some elements inside the DQ so EQ dot size will check that it the DQ so EQ dot size will check that it should be having some elements so should be having some elements so decoded front will get the first element decoded front will get the first element and if it is not present then it will and if it is not present then it will minus one then similarly DQ dot back minus one then similarly DQ dot back will give you the back element if it is will give you the back element if it is not present related minus one now the not present related minus one now the last two functions are checking out last two functions are checking out whether the size is you know like it is whether the size is you know like it is empty or not so if the size of the DQ is empty or not so if the size of the DQ is added like when we are calling this added like when we are calling this function is zero then it will return function is zero then it will return true that it is empty so if the size is true that it is empty so if the size is zero which means that this is a Boolean zero which means that this is a Boolean expression it will return true if uh it expression it will return true if uh it is an empty uh DQ is false similarly if is an empty uh DQ is false similarly if it is full the size of the DQ should be it is full the size of the DQ should be equal to the capacity that is the equal to the capacity that is the maximum capacity that is equal to K if maximum capacity that is equal to K if that is true then answer is that it is that is true then answer is that it is full as it is not full so these are the full as it is not full so these are the Boolean Expressions that will run true Boolean Expressions that will run true or false or false uh like the code we just have to uh like the code we just have to implement these functions and the implement these functions and the overall will be handled by the lead code overall will be handled by the lead code only only so uh that's our problem the code part so uh that's our problem the code part of it and you're watching video till the of it and you're watching video till the end if you have any doubts you can end if you have any doubts you can imagine in the comment box I will see imagine in the comment box I will see you in the next one lucky coding and bye | 2024-03-20 14:31:31 | 641 | 641. Design Circular Deque | LEETCODE MEDIUM |
|
JyyS9mlMcr4 | In this video we will compare Quoy Jumper Actions and Conference the main Quoy Jumper Actions and Conference the main issue is difference and I had issue is difference and I had asked another question which was named Targets we asked another question which was named Targets we submit, he goes to 100 in broken and submit, he goes to 100 in broken and got many more so we recommend him that he got many more so we recommend him that he got many more so we recommend him that he information is different from how then it is first of all if I do not speak from the problem of Finance Corporation of India then I do special and tell how to solve it in a different way from our sugar syrup, okay see like the festival owner had read about that inside And the site issue And the site issue And the site issue requested that you have ₹ 2 points, this is requested that you have ₹ 2 points, this is from the point and then it is the same point, so and you had to from the point and then it is the same point, so and you had to target the intake, along with the payment, target the intake, along with the payment, three points on Meena Vikas Marg, if you three points on Meena Vikas Marg, if you can understand 45 one in coin change combination. can understand 45 one in coin change combination. You had to tell me how many combinations You had to tell me how many combinations are there through which it can be clearly seen and are there through which it can be clearly seen and Congress is telling me how many are there through which Congress is telling me how many are there through which how many majors go into it, who how many majors go into it, who can be made seventh, and someone else in Congress has can be made seventh, and someone else in Congress has Edison Edison and to find the answer, whom should we talk about in inches and years? and to find the answer, whom should we talk about in inches and years? So you can use any point two or three or So you can use any point two or three or four times because each four times because each point has its own cement supply, okay so point has its own cement supply, okay so as I tell you the combination, as I tell you the combination, it has to be roasted at 231 minutes, the special thing in this is the it has to be roasted at 231 minutes, the special thing in this is the combination is 12345 but mentha permit in this is combination is 12345 but mentha permit in this is 2515. 2515. 2515. break then there are five main combinations but it is okay and what is one more special thing, the second seal is broken, another question will come, sunset, this is very beautiful, it has If you have to put Mukesh, If you have to put Mukesh, If you have to put Mukesh, then we will compare this also. Now let then we will compare this also. Now let us see the reformation in it. So, us see the reformation in it. So, look at my questions and how I did it from here look at my questions and how I did it from here and see how my strategy worked and see how my strategy worked in the comments on the time of Congress and in the comments on the time of Congress and contesting from this. First I am contesting from this. First I am troubling you. troubling you. troubling you. 2012 384 506 Make it a big size Now I am calling permission here I told and we have these How many conditions are there to present 24 Press high This is 100000 subscribe to target It's just like rubber To introduce the conditioner, To introduce the conditioner, To introduce the conditioner, how much has I earned with Sakoon Saath, how much has I earned with Sakoon Saath, first I am putting a crush, okay, there first I am putting a crush, okay, there will be an example in front of you, then I will change something, I will will be an example in front of you, then I will change something, I will show show how the producer has become fair in the company, so the laddus are bursting. how the producer has become fair in the company, so the laddus are bursting. In this we happen that there is In this we happen that there is a way to do zero at the ends, okay, a way to do zero at the ends, okay, what is Africa, don't do anything at all, what is Africa, don't do anything at all, now I will recover my Vivek Oberoi, now I will recover my Vivek Oberoi, when the routine and targets, we when the routine and targets, we take the video of the subject first, please come and see it, then take the video of the subject first, please come and see it, then it is half it is half it is half is a way to do it from zero, that way is neither get anything nor give anything, now I am the one who treats 235 time 12345, I have to close on the forest by the oath. And there is no doubt at 1 o'clock if you don't want to take anyone then you will be able to drink if you pay 12% of the dues then you will know them but this is not a way so I am here in Delhi typing is fine Here is Here is Here is any study about China's forest. Now let's talk about you. Okay, any study about China's forest. Now let's talk about you. Okay, because let's talk, here I have given two because let's talk, here I have given two points, here I will hit tubeless. points, here I will hit tubeless. Okay, Monday, the first loop, I have given two boys, Okay, Monday, the first loop, I have given two boys, Maya, I have reached here to do it from zero. Maya, I have reached here to do it from zero. Maya, I have reached here to do it from zero. method is Akshar, this is our use, this is the method or 50 grams of society will send this gram, which I had researched in depth in the video, so whenever I do it here, it will seem prime, then the rest has to be narrated, And I And I And I can go and you can go and I came and I can go and you can go and I came and I can go, I stay away from the intake, I don't know the can go, I stay away from the intake, I don't know the height, monotony, brightness setting height, monotony, brightness setting are from him, then in the rest, the milk is filled with the total of going, are from him, then in the rest, the milk is filled with the total of going, so now it seems as if I will see it from someone's place. so now it seems as if I will see it from someone's place. Have to pay money and can't think Have to pay money and can't think that I have 10 destination is that when that I have 10 destination is that when zero is okay then if his eyes bowed zero is okay then if his eyes bowed Scars K 235 If I had paid with two Scars K 235 If I had paid with two then there are more days on my website then there are more days on my website Seventh after 3 to 4 minutes Seventh after 3 to 4 minutes Seventh after 3 to 4 minutes more days, there are some ways to pay you by letter, along with the scientists, there are those ways and looking at five, no, there are those ways, so if there were three ways, two ways There are so There are so There are so many ways to do totals, till today, many ways to do totals, till today, but till now, this is the only but till now, this is the only work. Time tried to do it on two, so brother, work. Time tried to do it on two, so brother, why are you, but I had to go to Rs. 10, why are you, but I had to go to Rs. 10, is the payment clear from you to two, is the payment clear from you to two, can I do it in the second cricket test? can I do it in the second cricket test? can I do it in the second cricket test? because they are big meat, okay or write it down once for repayment - York Times - 30 days will be left, now there is a way to use zero, something or both people - Sangh work happens, nothing people so And you will give me some road and I will And you will give me some road and I will And you will give me some road and I will also go. If there is no way then there is only also go. If there is no way then there is only one way to go to Shirdi. If I don't know one way to go to Shirdi. If I don't know then I went here where lizards grow and hurt. then I went here where lizards grow and hurt. Friends, please understand that we are in very detail. Friends, please understand that we are in very detail. Subscribe I will not leave every leadership Subscribe I will not leave every leadership soon. soon. soon. curtain from here, I am 2 - My one will reach, the coach of the team will neither definitely reach 500 or can not, now there is no arrangement for 10, what is visible is the There will be There will be There will be a way doctor find a way a way doctor find a way could block the way it went up just passes could block the way it went up just passes I three went behind him one time 201 this is I three went behind him one time 201 this is my tablet you are okay now let's talk about the flower my tablet you are okay now let's talk about the flower this way or we this way or we set why when I talk set why when I talk Network above too - - - - - You don't know the time to go from Network above too - - - - - You don't know the time to go from here to two, but if you go from here then it has here to two, but if you go from here then it has become an example. Okay, now you have to go from zero, there is become an example. Okay, now you have to go from zero, there is a way to go from zero, there is world.com, there a way to go from zero, there is world.com, there is no one else in the world, even on 24. is no one else in the world, even on 24. is no one else in the world, even on 24. way to do is if I am here then it reaches there and bow down subscribe this is two and this is nothing so that's all that is left now why did we have the bodies connected above ₹5 let's talk about doing 5 but sunshine more Punches can be made at your place, Punches can be made at your place, Punches can be made at your place, go to your friend's room, take go to your friend's room, take away Tuesday, take 50 zero pieces, now there is away Tuesday, take 50 zero pieces, now there is a way to go from zero to seats, a way to go from zero to seats, don't friends, don't see this method, there don't friends, don't see this method, there is also a way to go to 30, they have a technique. is also a way to go to 30, they have a technique. world.com 25 came out to see the world.com 25 came out to see the settings out of these are dot right yes then 3313.com's team was paid for, used rosary so it is ₹ 2, its fragrance method is dot then M.Com If we stayed and did it even with 5, If we stayed and did it even with 5, If we stayed and did it even with 5, then we reached here, there is then we reached here, there is a way to do it, those two track records are a way to do it, those two track records are fixed video.com OnePlus One Plus fixed video.com OnePlus One Plus One layer till here, do you have any problem, very One layer till here, do you have any problem, very good, very good thing, at working in Bandra. good, very good thing, at working in Bandra. good, very good thing, at working in Bandra. we can go past six and seven, then from 6, if we use Bandha, only the trick will reach 35, we will reach 1, there is no way to get one, there is a way to go right up, there is a way to dot, the There are methods of amount, There are methods of amount, There are methods of amount, okay brother, let us also see 200 okay brother, let us also see 200 here and three, then here and introduced with 5, here and three, then here and introduced with 5, okay here, then the way to get four okay here, then the way to get four is 222 will ask, got 222, the is 222 will ask, got 222, the way to see the foot game is dot re. way to see the foot game is dot re. is about returning home and 511 other pujas are nothing is about returning home and 511 other pujas are nothing but on Lord Krishna, it is just an exam. If but on Lord Krishna, it is just an exam. If you have any problem, you have any problem, then what is the return edition? It is a then what is the return edition? It is a very good thing for whom. Your mind is like this, very good thing for whom. Your mind is like this, basically this question is not a problem. basically this question is not a problem. basically this question is not a problem. do our chili coriander and fennel, how is it different from the combination, seven people have to die, five wickets have to be taken, Vinod has to be done four feet and 500 have to be made smooth and thick paste, see that part, there are three ways to There is a way and there is a way to do ₹2 There is a way and there is a way to do ₹2 There is a way and there is a way to do ₹2 so let's stop 5 Let's see here also so let's stop 5 Let's see here also 12 reached here reached here from three reached here from 25 reached here from two plus one plus one girl three five plus one if these three Daughter and want cotton 323 Daughter and want cotton 323 Daughter and want cotton 323 452 323 Is this our 452 323 Is this our way of presenting 17 or not? Used to end way of presenting 17 or not? Used to end 235. Raghu came in Boss. 235. Raghu came in Boss. Click on continue here. Click on continue here. Yasmin is Maya. Now we will see Islam Yasmin is Maya. Now we will see Islam is the combination. It is necessary to come to Congress. is the combination. It is necessary to come to Congress. 2525 and the second one is this, 2525 and the second one is this, we will do something with it and remain very simple, we will do something with it and remain very simple, what we did this time is that we took a what we did this time is that we took a pocket of 253 pieces of ceramic and the rest of the payment, pocket of 253 pieces of ceramic and the rest of the payment, what will we do now after breaking it whole, we will like it, we will what will we do now after breaking it whole, we will like it, we will believe it, we will fry it whole. believe it, we will fry it whole. believe it, we will fry it whole. 's take it and mute it, let's see how it is okay, so see, this time we are making it again for the combination, Solkar and you have to this is what we have to this is what we have to relax at this time, so relax at this time, so relax at this time, so after that you will have the extract layer, it is necessary to understand the questions, a little mention that the gang, the previous song again, first we are taking two cash in the whole, first soon in Mukesh, like if someone life was even Let's see, this time first we Let's see, this time first we Let's see, this time first we will make whole Bittu, then we will mix the whole and then we will make whole Bittu, then we will mix the whole and then we will type in the whole. So will type in the whole. So today I will be in front of you and see. Now first we are today I will be in front of you and see. Now first we are submitting the whole Bittu submitting the whole Bittu Pimples Infections 152. If you don't understand Pimples Infections 152. If you don't understand then you can use it. then you can use it. then you can use it. two can be used on this seat, he reached here from there, if nothing is found, he can use it, if he brings here one method, adulteration, daughter, friends can hit on five, but So here is So here is So here is that one method found, it adapted 2172 uses, that one method found, it adapted 2172 uses, this one is not found, all of the two have been done, now this one is not found, all of the two have been done, now it has been told that the team does it, I have to return to this, how many ways are there to do this using only two, how many ways are there to do this using only two, using only two. using only two. using only two. doing this, we can do it only on the even ones, their methods are then pick two multiple times, now I will put three chords, so that is how many ways are there using two and three. Okay, now it is important to note that If he comes then he will follow them only then If he comes then he will follow them only then If he comes then he will follow them only then now we cricketer now we cricketer Shankar Nath will stick behind him, if someone sticks then it Shankar Nath will stick behind him, if someone sticks then it is about getting better or the other can be big, always taking a dip and putting it towards the back, so he will go here along with the old answer Will be Will be Will be adopted from here Maya is the adopted from here Maya is the way to look at it, so one way is that you way to look at it, so one way is that you try this note 4, used the free on four, try this note 4, used the free on four, so we reached here it got so we reached here it got 25 views, so we reached here A, I am 25 views, so we reached here A, I am in a very shock, there is in a very shock, there is a a a ever the day wakes up on the seats, then this week is fine, it is after tuition, till now, why was the stubbornness in studying carefully, among them, I broke down, then there is something else behind them, on one side, okay, Let's see, Let's see, Let's see, for this, I found one method for this, I found one method from here, so it became two, Dot from here, so it became two, Dot fell here and there was video.com fell here and there was video.com that now we will use it together, so on our four, I that now we will use it together, so on our four, I found one method, daughter to 232 found one method, daughter to 232 found one method, daughter to 232 soil from there very quickly behind so now we will use it so from here to here and pronounce it, if you put type here then one more method and you got dot pipe if you put it in this area then you will get something, if you put dotter on seven then you get one here. First of all, if you see 15 or two apk files from Google Play Services, then it is fine because of that, but if you see a lot of 225 in all, then I install it here, just below it, I am solving it Only less but it Only less but it Only less but it can fit in the public's mind. It's okay for this thing, the can fit in the public's mind. It's okay for this thing, the way to zero is now just very way to zero is now just very beautiful, one but 0777 is over, afternoon is all beautiful, one but 0777 is over, afternoon is all mine, found a way, dot 235, can't escape, mine, found a way, dot 235, can't escape, now here, here, I now here, here, I now here, here, I on zero 12345 63 but two, now I went from here to three, found a way to message and 35, can't use it, even at 4, grandma can't understand. If I used two, When I asked When I asked When I asked 13 questions, I went here and found something, and 13 questions, I went here and found something, and look at the fiber that reached you, these are look at the fiber that reached you, these are not to be but and so on, now see not to be but and so on, now see only the umpire will come to that test, if you used two, then only the umpire will come to that test, if you used two, then reached here, found one method, it is specific, and if the reached here, found one method, it is specific, and if the team is used, then I am here. team is used, then I am here. team is used, then I am here. and found which is not see that your afternoon here in juice was tooth on free and now you used a two and three then ok find and two cigarette happened then you broke down here previous which is Mukesh doing this back Two to Z can say something and if you are riding it on your leave, then if up to three are born, then it can also be okay that what will happen to you and Congress in this city, in the first cycle of two, all the two are blackened, whereas if it Old decommissioned dog, if ever Old decommissioned dog, if ever Old decommissioned dog, if ever I tie a knot on it 2328, white I tie a knot on it 2328, white bangles and anklets and will get it bangles and anklets and will get it in daughter line, there is no need for recommendation, in daughter line, there is no need for recommendation, here we will do the training, here we will do the training, done on six, got a way which is done on six, got a way which is not two six not two six not two six Mila dot C three and five were imprisoned but will do two so from here three ways were found that if tube.com 320 MP3 was used then one more that if tube.com 320 MP3 was used then one more Mila dot s 5 use and Mila where dot Mila dot s 5 use and Mila where dot Print bottom you had done now the school had used that Print bottom you had done now the school had used that but you have that that while but you have that that while using subscribe in and using subscribe in and from hr hr only that from hr hr only that targets we true submit how Shimla targets we true submit how Shimla problem is the young man riding in it has got Aadhaar problem is the young man riding in it has got Aadhaar 235 you are asked 235 you are asked 235 you are asked any good subject of gesture which is equal to Samsad I can use these anyone twice that Congress Now who are you in this Internet up to Kumar Vishwas is not subscribed that passenger train is there will not come will not If it comes then I will If it comes then I will If it comes then I will make 2nd for it and today mark it may take time, let's make 2nd for it and today mark it may take time, let's see, this Singh is used in it, see, this Singh is used in it, I will request all the videos that I will request all the videos that son please first son please first watch a program subjective detail video of this, for watch a program subjective detail video of this, for this you will find description this you will find description search comparison below. search comparison below. search comparison below. and to do this is not its original special that if it will not be able to help you then we make this curve in it and this is the mini here know what is coming here is that is there any set of two three are The most problem on the five elements, you The most problem on the five elements, you The most problem on the five elements, you leave the praise, leave the praise, I will be soft, our 2315 is to be looted to to to to to two to to to two to two to two and only and only and only only If it goes to then you If it goes to then you If it goes to then you can subscribe, okay so in can subscribe, okay so in this way and this last one this way and this last one can make 235 ghagra 200 rs and if it is happy then anyone can make dros now, I anyone can make dros now, I will find vegetables here, second finally chem t- will find vegetables here, second finally chem t- shirt, subject of courage. shirt, subject of courage. shirt, subject of courage. everyone makes it that and if there is anything about the MP subject, then nothing can be made other than zero. Being an amputee is a part of it. This father-in-law of MP3, MP, if you understand it as a sum, then it is Like, definitely the question comes, if he is a player, then he is the lucky person of triple, there are vegetables and fruits, this is the problem, he has a root but a game, now I feel this and think, what can we make about this book, but friends, if not. Here I can tell you that you can go to Ra.One, if you do not come then before that the limit will be closed and if before that the limit has to be made - One, I do not like the fact that cooperative I will go I will go I will go intermediate if I can, it will be more intermediate if I can, it will be more about how those people are 220 price I will not about how those people are 220 price I will not come because it is two parts of this type of come because it is two parts of this type of MP subset at subset and jhatka MP subset at subset and jhatka communities and group of two most to so this will communities and group of two most to so this will definitely do will do to all the rest definitely do will do to all the rest definitely do will do to all the rest is a straight line then I fill the right line, it is Sunnah here but now we are rolling in a good way, I do it yourself, think about it, it is very important, its cutting is smaller than August, so this is so, So it wo So it wo So it wo n't be cooked, now I can't do it in school, I had already n't be cooked, now I can't do it in school, I had already made it, now I don't hate it here, made it, now I don't hate it here, if I got it while sitting and neither have if I got it while sitting and neither have you got it cooked properly. Hey you got it cooked properly. Hey Pappu ji, let's talk about team of two and three Pappu ji, let's talk about team of two and three together. together. together. three to four inside, but if three will not bat, then all the runs will have to be scored, hence if he bats, then the remaining wickets will be run. Tube Raghavan will make that, he will do it in his respective vouchers. If you are sitting Had scored one run, the food is not good, now it is Had scored one run, the food is not good, now it is Had scored one run, the food is not good, now it is teen, if I don't bat upside down, then teen, if I don't bat upside down, then I vote in relations, if I were lying, then I I vote in relations, if I were lying, then I will become those viewers. Cigarettes are present, so will become those viewers. Cigarettes are present, so you are the one who is going to tear Kingfisher, you are the one who is going to tear Kingfisher, what old 115 Bola, I said, I am a picture. what old 115 Bola, I said, I am a picture. what old 115 Bola, I said, I am a picture. then he will make the remaining breakdown, then there was a dispute between both of them, if we talk about a week, then saw this and if you see three behind, then take Paul with you, saw here and if you saw the team behind, then I have it, then Tak team I5 said, brother, Tak team I5 said, brother, Tak team I5 said, brother, I will bat for two and three. If I can't forget you, I will bat for two and three. If I can't forget you, I will not make any enemies. If you I will not make any enemies. If you start then I will bat for five elements. start then I will bat for five elements. This is my family, if it is not on a fast, then take This is my family, if it is not on a fast, then take them hostage. No, they have become, they have become good. them hostage. No, they have become, they have become good. Good, Bipasha can't make five and Good, Bipasha can't make five and said brother, you will be making mine said brother, you will be making mine and if I bet, how much will you take, zero has already been paid and and if I bet, how much will you take, zero has already been paid and in this tone in this tone I said, many people will make only there, I said, many people will make only there, and I make five in the voucher, will you make one and I make five in the voucher, will you make one ? ? ? I told her one teaspoon. Then I told her to make a banana. With me, I make my own brasil. I make the color near my name. Friends, will you make two of them? This Gautam This Gautam This Gautam waits that the duplicate will not come, waits that the duplicate will not come, how to install the album, the gas will not how to install the album, the gas will not come, this roll folds in such a way that the come, this roll folds in such a way that the pipeline line is passing, whether it will pipeline line is passing, whether it will rise or not, which does rise or not, which does not happen, and yes, the exam when not happen, and yes, the exam when Passing and not being able to pass in the same Passing and not being able to pass in the same 257, tell me what happened in the previous road, two and buy not made in the evening, did anyone make or not make anyone in two or three, are you talking about that, make or not make anyone in two or three, are you talking about that, then one goes, then all 5 do not come twice. then one goes, then all 5 do not come twice. then one goes, then all 5 do not come twice. way, Jatin was looking back, when he saw Bittu, he never did anything right in it, so anyone will meet twice and and for intervention is one day, when you look back, please like volume mute has been written many times. Okay, so what was there in it, ODI, that we used to look back, this but the question combination is written to you, I will take some development and again it is 1/2 inch Congress is confirmed decimal O0 12345 6725, but you would have Khusro Daaba lying with Used to bring this word Used to bring this word Used to bring this word sirvi daughter used to bring from 219 so two sirvi daughter used to bring from 219 so two jhal and dot if the water boils then by the first so that jhal and dot if the water boils then by the first so that you understand that because you understand that because on this channel we are in it and Sir Sanghachalak question of European Union can come because it is So I am fine, Bhilai's smile will go and no 2525 notice, these are the things that children should do, are they okay? So, have you understood sir, select the teams. Yes, children, I request you with Also, Also, Also, before watching this question, please targets, we before watching this question, please targets, we submit information and who submit information and who reach here after watching its individual videos reach here after watching its individual videos and are sitting with their diagrams. and are sitting with their diagrams. If you watch this video, you will get a lot of If you watch this video, you will get a lot of benefit. Meghnad will do the sewing, there benefit. Meghnad will do the sewing, there is a bar option, I have tried. is a bar option, I have tried. is a bar option, I have tried. not be able to understand completely. Okay, with this video also, there is a virus in marriage, your inside will be clear, which is in this site, so what to do in your mind, at that time, I take that how does the combination Combination: You have to see Combination: You have to see Combination: You have to see how combination versus competition how combination versus competition frees the community, how it creates an frees the community, how it creates an update function, how update function, how we targets, how the subject we targets, how the subject avoids someone, how an owl avoids someone, how an owl rejects someone, you have to think independently. If you rejects someone, you have to think independently. If you inherit then please. inherit then please. inherit then please. meet you in the next video. You will see us in the next video for this match. Team II and 225, we are Meghna, right now Meghnath and Cheez are in the meeting and if I am then we will have made it and if anyone moves away then he will And all of them are I, I, I, And all of them are I, I, I, And all of them are I, I, I, I, | 2024-03-24 10:28:18 | 322 | Coin Change Problems Analysis | Leetcode 322 v/s 518 Explained | Dynamic Programming In-Depth |
|
0FMKNDEopR0 | that paper to Ajay. In this video we will see the solution of super next number, so before that you solution of super next number, so before that you must watch the video of next number once, it is must watch the video of next number once, it is related to this, so related to this, so I have given us this knowledge to I have given us this knowledge to find the number of super and how to define super bheem number. find the number of super and how to define super bheem number. Whose prime factors are not, Whose prime factors are not, its prime factors are okay, it will be given its prime factors are okay, it will be given that the risk factors can be any of these, like we see with the district and like we see with the district and course one is the first super Ali number, this course one is the first super Ali number, this option is 3570, so this If you get it then you can get If you get it then you can get If you get it then you can get hands free life 1111, if it is a festival then we have to tell the number of add super now, its factors can also be only free 517 and your purse, then the first one will not improve anything from this, how to get the number time There could be a There could be a There could be a limit here, there could be any number, if it is limit here, there could be any number, if it is found in the literature about its size, then the found in the literature about its size, then the number is after Salamul and there are three number is after Salamul and there are three effects effects of what we used to do, one point is of what we used to do, one point is taken for tu and only one point is taken for thyroid. taken for tu and only one point is taken for thyroid. Point different and all three in starting that Point different and all three in starting that DP's post index point was made DP's post index point was made that track all three did rectal cancer Prophet toe were two in 2.82 C * Points pay that TPO a point of two DPO point that TPO a point of two DPO point of trees and fell into a diff of trees and fell into a diff A Painter 5th A Painter 5th Okay, okay, we will calculate the income in Okay, okay, we will calculate the income in our next next number, our next next number, then from where you got the mean value, its then from where you got the mean value, its point was a big, then similar point was a big, then similar and friendly work is happening here, see, and friendly work is happening here, see, now I am every one. now I am every one. now I am every one. my file, a point for intake for 11:00 and if there were more, there would be a point for all of them, so we are not going to do this, we will not keep separate pointers for each one, just maintain Lo Jhal Loot Hello friends, now what will its zero index Hello friends, now what will its zero index tell, okay where is the pointer, just tell, okay where is the pointer, just index five quantum is here, where is the is the point of second point of second point of second going to make my answer or that inside this ODI, inside this lamp, the junction is number one in this poster, the first super hero is number one, I had broken it and now I am a candidate for the next super league number. I right now, every single point is in Asati, this point is I right now, every single point is in Asati, this point is crore, this point is 1.5, this point is seven, crore, this point is 1.5, this point is seven, Abeer and 11.43 forces have to be Abeer and 11.43 forces have to be called, it happened that Priyanka is Ravi Shankar, the that Priyanka is Ravi Shankar, the point of the guy with 2036 pointers is very high. point of the guy with 2036 pointers is very high. From 0.5 Next Point is doing many such From 0.5 Next Point is doing many such 0.5% add till now so candidates for next super ali number which multiple life but its multiple life but its pointers is subscribing so simple then pointers is subscribing so simple then we a that we a that train to band spider-man 2 train to band spider-man 2 train to band spider-man 2 350 350 that now the minimum of all these will that now the minimum of all these will become the new super number become the new super number and from where you have got the minimum value, and from where you have got the minimum value, increase its pointer by one so increase its pointer by one so that its pointer increases by one so What happened to this, husband's What happened to this, husband's What happened to this, husband's point extract, by joining it, acid attacks are point extract, by joining it, acid attacks are cured, this one point will remain the point, cured, this one point will remain the point, Daabi is pointing here, the rest is Daabi is pointing here, the rest is of Spice also, the same is of One and of Spice also, the same is of One and also of Level, once again also of Level, once again Look at these two pictures Look at these two pictures together, vaccine pointer pipeline study, who will be the next candidates for the maximum on Quantum 11.2, team multiplying, then C who will be the next candidates for the maximum on Quantum 11.2, team multiplying, then C point, your pointers, join it, tighten the value that is lying on it, meaning Depot 3.0 tighten the value that is lying on it, meaning Depot 3.0 and the third on and the third on 15 Feb. 15 Feb. That is pointing to the tiles, 7.2 is That is pointing to the tiles, 7.2 is jointing it, 121 and 11.34 are pointing to the time itself, pass candidate for next time 95 pass candidate for next time 95 711, min max of these three, super hero number 711, min max of these three, super hero number one went, where did you get this from, his one went, where did you get this from, his points what should I do, go to the plus index and what should I do, go to the plus index and move that point forward. Next super, move that point forward. Next super, look from here for the next number. look from here for the next number. Next super on this number now, I Next super on this number now, I will fold it. Look from here on source will fold it. Look from here on source multiplied by this. multiplied by this. multiplied by this. run it again, okay, ₹1, ₹1, so brother, seconds are appointing, one from the port, the value placed on the next, I want the free fold it tightly. fold it tightly. fold it tightly. 1802, go to the conductor and there the value look here like this medicine west If there are pointers, two are placed on top of 101. We need a party on top of the bajo. Jhal is on 15th, that's how Sarvan is doing the point of 127. If I will ever send multiplayer, then there is a pointer crop, if there is a point, then But also, the minimum balance of value diamonds is of the But also, the minimum balance of value diamonds is of the But also, the minimum balance of value diamonds is of the next number above or from where next number above or from where you got this simple, increase its point you got this simple, increase its point together and there is the petrochemical point, move ahead from here, when loot in fact is not seen here, you can see the But we have moved ahead But we have moved ahead But we have moved ahead and Savitu Banega will be arrested. See and Savitu Banega will be arrested. See A.A.C.E.M. Multiplies from here. So I know what to do. I will select as many prime numbers as there are and pick them by either Times of Jack Pack. Jail Sanjay, I Jail Sanjay, I Jail Sanjay, I ran a loop. If you hold the number on the gesture from zero to the last, ran a loop. If you hold the number on the gesture from zero to the last, then then it is a multiple of birth it is a multiple of birth that now its good morning, that now its good morning, where is its pointer, we get information about the point which where is its pointer, we get information about the point which also possesses the point, which point is also possesses the point, which point is contacting which point. contacting which point. then DPO points 241, then DPO points 241, it is just simple it is just simple that you puncture it, basically you run it that you puncture it, basically you run it from two districts to the last - then you have considered the corresponding factor of every prime number, it will From here, the tuck will come, the factory will come, the From here, the tuck will come, the factory will come, the From here, the tuck will come, the factory will come, the factor for will remain that whatever factor has given their factor for will remain that whatever factor has given their minimum, your next super is now minimum, your next super is now of number either of number either then what you have to do is to increase the point of the point from where that then what you have to do is to increase the point of the point from where that minimum value was got by one, which is tight, then tight, then we explain it by one and a half. Main sochi multiple with 2002 mili aur difficult hi kept hai in spite of multiple with here willing to sacrifice unknown person three hai seventh eleventh multiple tweet post election eleventh multiple tweet post election 2014 2014 to in sab ka minimum to in sab ka minimum hai next super next number hai next super next number hai next super next number person moves his point one by one, you go here complaint that this point protects from attack, now this third join them, then 34 more or less me to the last Lootere media end meet ok so Lootere media end meet ok so I made a vent for my DP. This point is of the size of a pen plus one. It is This point is of the size of a pen plus one. It is in the tube. Ok ok so let's make this. We are going to have pointers. How many sizes will you make as And in this, fill all the space on the side by making And in this, fill all the space on the side by making race 2 full and race 2 full and keep all the space in this pointer as one keep all the space in this pointer as one and and after that I made the duty after that I made the duty Jhal N plus one size Jhalmuri iPhone Jhal N plus one size Jhalmuri iPhone from where do I know, it is from where do I know, it is mainly coming in a tight box. mainly coming in a tight box. mainly coming in a tight box. super on Defy, the next one super on Defy, the next one is Namaskar, then it depends on the answerer in the last, write this paste in it also write this paste in it also that today I will get it patterned that today I will get it patterned Jhala, if we start this recipe, then we will Jhala, if we start this recipe, then we will take it and fold it till the end, okay, Then what do I have to do for Then what do I have to do for Then what do I have to do for every prime number Girls only after every prime number Girls only after you have to do at least what I do I you have to do at least what I do I took the existence dot took the existence dot value value jhal ko tight and friends that by rotating over every prime number Plus, now look at now look at all my factors of cancer and all my factors of cancer and taking them to the minimum, we have till now, whatever is Tamil, taking them to the minimum, we have till now, whatever is Tamil, tractor, see what I do, prime tractor, see what I do, prime fennel, Jain, Prince Jain, multiply, tweet, which fennel, Jain, Prince Jain, multiply, tweet, which TPO, which are the pointers of J&K? which are the pointers of J&K? which are the pointers of J&K? I have found out is that the first number has been picked and where its point was pointing, then I went there and picked up the value, from there the platform number from the DP, the value of medical incense, the second number deleted with His daughter's His daughter's His daughter's first place of cancer was even, everyone's minimum was taken first place of cancer was even, everyone's minimum was taken out, the week's minimum becomes the next out, the week's minimum becomes the next prime number, the prime number, the prime number is also made, from prime number is also made, from where you move forward the point of valley million, where you move forward the point of valley million, these people will think again or one time I would write. that if its value that if its value looks equal to the minimum, say, say, I am from here, you take them, you will I am from here, you take them, you will go to her pointer, a hang, remind go to her pointer, a hang, remind that the point has become one bigger. that the point has become one bigger. that the point has become one bigger. principle of this is that if we try to run the ore, then first one more time we preserve it, not the opposite site and not that ok ok I understood ok ok I understood now see friend let's talk a little about this post now see friend let's talk a little about this post Look here, Look here, we will get an idea of the time we will get an idea of the time that it is clearly the end times from the outside till the end and then these people have kept it running, you have seen and it has been kept and then these people have kept it running, you have seen and it has been kept running by the people that this is running by the people that this is Kepler's two and Kepler's two and Kepler's two and 's * K's rate is 100g time complexity is coming from here its good ok so can we optimize it can it be done after let's I do 60 stories from yours I do 60 stories from yours I do 60 stories from yours first one and have left it here. and take pointers. and take pointers. Jhaal 20123. Flavor snacks have made each point pointed at the top. So what do I do on this. I I am fine, I am fine, what will I keep in the traffic, how will I do it, I am watching carefully, by the way, I am taking a fair class on it, what will be the things inside the class, scientists are scanning this tree, now the her. her. her. and what is the value of the person in relation to both of them? So let's do this once again. If for the first time, if you want to make a new super villain number, then who will be the candidates for it and who will be the Who lives Who lives Who lives here, this candidate's multiple is here, this candidate's multiple is 15817 121 1121, all these Androids, so 15817 121 1121, all these Androids, so all these cutlets have to be done, predicament bay two torch light, Rafi kept pinching, prime number is our three and its point is Abhivan infection, we are here and and and words like this in next five one and half inch 172 specs 11:00 and r prime number and its point ko is point hai tractor ki value hai toh aisa aisa yaar prime number this factor toh aisa aisa yaar prime number this factor is only showing this number multiple is only showing this number multiple is only showing this number multiple painter of debt prime number that the world is basically Ecuador by picking up the value tight, this is done to your bank, tight, this is done to your bank, okay, so now let's make all these minimum on Chairman okay, so now let's make all these minimum on Chairman Friday, all these are minimum here. Friday, all these are minimum here. Friday, all these are minimum here. those tracks then what should I do Pretty those tracks then what should I do Pretty because it is our remove practice to come back because it is our remove practice to come back out without you out without you Well I have removed so be tied to here Well I have removed so be tied to here Remove 313 Laila Kabir They will install the smallest at cheap prices I got the one that came out and I have made it the number for the next one, tighten it and I saw that the point of this prime number is now pointed here on one, so was prime number brother, enter one. was prime number brother, enter one. was prime number brother, enter one. and this is not value calculator which is not I have added it again on the side to tight good if I apply force to remove from Friday why then it is inside outside the commission talked like this so points 1515 outside I will make the next super campaign I will make the next super campaign I will make the next super campaign number number and then give it a big point, now by and then give it a big point, now by increasing the scope per quintal, increasing the scope per quintal, add it to the practical and make it twice on I, add it to the practical and make it twice on I, Wife Wife is a Pointer, its 21 A A was popular is a Pointer, its 21 A A was popular in 523 parties till date Remove this party separately, Remove this party separately, Remove this party separately, this limit will come out, the this limit will come out, the bell found in seven 7 came next superhero bell found in seven 7 came next superhero number one and let's increase its pointer by one, number one and let's increase its pointer by one, we used to add here we used to add here 172 10 2013 172 10 2013 seven more like seven more like this a little more this a little more this a little more only then it becomes clear, I approach a Hello friends, if I remove it in traffic, then the element will come out 2987 Prem and Laga Hai, I have got the next super villain number, now what will I do, I will come to now what will I do, I will come to a new place. a new place. a new place. whose point will be given a big and put it on 3DX and multiply it with the value fifteenth that you will see on the right hand side that you will see on the right hand side in the famous steps and it is going to happen in the famous steps and it is going to happen remove it from this meeting remove it from this meeting that the live wallpaper has come out that the live wallpaper has come out this this this then add a new platform, then add a new platform, increasing its point by one, husband alarm set up dance, want to see, why did I remove what is present on the valuation, here also the person here also the person here also the person any person can come out, let's come out, one pipe 215 Next, after generating the first number, one pipe 215 Next, after generating the first number, now 15 more will be added after making Preeti Yagya, now 15 more will be added after making Preeti Yagya, increase the value of village wife through internet and 5 minutes craft with Arjun tractor, Tighten it a bit poor, see next time you will Tighten it a bit poor, see next time you will remove it from here, which load will come out, this remove it from here, which load will come out, this element came out and element came out and what was I going to do, I was going to make the next Yagya number, if it is what was I going to do, I was going to make the next Yagya number, if it is fako, then we have to take care of this thing, fako, then we have to take care of this thing, this is the number that came out and this is the number that came out and this is the number that came out and number, if these two are there then do n't add me here again then it is coming that the last super clan was generated by itself and Nak was going to make super hero number if both of them are one because what kind of song is Repeated Reflection. And if you will not keep this water twice then what will you do, just do Chakia and till the last this number is the last superhero number 1 and if you will not simply add anything in the DP, then you will be able to add its point here in a big place that that that any burden will come but it will happen only once, one will come out of here twice but only once, it has been added once in DP, where is it, Talk about the Talk about the Talk about the phone's time complexity. What will be the size of the plateau? If it is a prime number then its size is tight. If you add or remove, then those operations of add and remove will be of the people of the village. So, if I have to update the next numbers, I remove one and then add it. After removing it, I will get the next number. Then I make a new pair and add its next factor in practical. Try that for each next number. Try that for each next number. Try that for each next number. generate a super villain number, now one addition and one removal has to be done and although it will take time, a pan will go to people's I used to add and produce for you, I used to add and produce for you, and these people and these people and these people complete the project and let's see, loot the police department, the that I will have to make a DP, so it has that I will have to make a DP, so it has happened happened that the end is plus one side, that the end is plus one side, that intelligence is also required for foot class, it is that intelligence is also required for foot class, it is my acting class, my acting class, pair it. pair it. pair it. is the prime number. Then we keep the answer. Where is the A pointer tight. prime, the prime, the point is the value of point is the value of 123, then the time. were President were President jhal pointers will be equal jhal pointers will be equal report value of toe pointers will absolutely go ok ok because now why did the makers of Friday have foot class so it will have to be implemented na Pebble and on planets less speak fierce and To implement this, it is the To implement this, it is the To implement this, it is the responsibility of this class to responsibility of this class to write the compare to function write the compare to function that the applicant and compare to go is jhal and convert the subject of oxen to be made in is jhal and convert the subject of oxen to be made in friday be returned s dot friday be returned s dot value minor daughter the value minor daughter the value of value of on do on do ok ok ok ok ok ok easily create a priority queue, click on the box, why pet class AP, the okay, so while typing, we have to set a few drops okay, so while typing, we have to set a few drops first that If there is plus plus, If there is plus plus, If there is plus plus, then there is nothing every time, no, you are then there is nothing every time, no, you are my friend at the language, the my friend at the language, the hero is of the length, it is good, it is the priority, why should I stop looting, add good camp, on the other hand, the times of crime sang that Valid Valid APhoto APhoto by Nakuul Mehta Pointer Prime Safai Sub by Nakuul Mehta Pointer Prime Safai Sub Point will be above Aman and value will come for the Point will be above Aman and value will come for the first time only the first 2 Prime Safai will be first time only the first 2 Prime Safai will be ok ok let's multiple will come ok will remain not So So So this coming plate gun has been added, now I would have got the answer of DPO one also stored, abe Akhil had started, this is first to n till lokay abe Akhil had started, this is first to n till lokay were in the last, we have got this return done, ok, ok, You will have to You will have to You will have to remove it on Friday. Practice on the remote on the phone. You don't remove. Okay, friends, I removed it. Okay, friends, I removed it. Now let's verify that. Now Now let's verify that. Now make your answer in fact. Before making it, you will have to apply a little oil make your answer in fact. Before making it, you will have to apply a little oil somewhere. That's it. somewhere. That's it. What? What? What? why not practice it somewhere, the value of the one that has been removed and the last super next numbers that it has generated is not for both. Once I say this, You had generated your last You had generated your last You had generated your last super hero number and now super hero number and now you have the value after removing it. Are you have the value after removing it. Are these two values equal? these two values equal? Okay, if both of them are equal then Okay, if both of them are equal then I will not create a new super hit number. I I will not create a new super hit number. I am for both of them. am for both of them. if these two are one bus, then we will if these two are one bus, then we will not do anything, except that in a GPO park, we will do many more of these, okay, you can write it like this only if it Shravan That the cat is good, fine and here press the address, village and here press the address, village is good, fine, good, otherwise what do you have to do, the pair has been removed, now you will be admitted on Friday, I am on top priority. I have to add a new love. 90, then read the name of the prime number of the remote part, then what were the prime pointers. Okay, the timer till the remote part of prime number will remain the same, just at that point. torch light and value will be given to the pet prime torch light and value will be given to the pet prime number multiply wealth number multiply wealth EPFO that its pointer plus one this one so this one here we made the prime number remain the same point made president till track number multiply wage DP which point is updated Its value is done, she writes it in the foot and adds it in the meeting. If you say yes then it will continue like this. All the numbers were deleted that if you get a different answer from me, then let's try solution two also. * Hello friends. faster, got integrated inside, so friend, faster, got integrated inside, so friend, we have discussed two products here, the we have discussed two products here, the first approach, the first approach, which was first approach, the first approach, which was decided from the fire number itself, so it is dry from the number decided from the fire number itself, so it is dry from the number and whose Montessori came *'s tight and whose Montessori came *'s tight second which second which second which so its time complexity is why we so its time complexity is why we bought it and it takes time to unlock. I hope you will hope you will understand the question. You will have a lot of fun by folding it. understand the question. You will have a lot of fun by folding it. I will call this question. I will call this question. Thank you very much and please subscribe our Thank you very much and please subscribe our YouTube channel Thank you Shravan | 2024-03-24 10:15:59 | 313 | Super Ugly Numbers | Dynamic Programming | Leetcode 313 |
|
DM2O_cQSwqY | Hello Jise Aggarwal welcome you all channel quarters made by so let's nine days let quarters made by so let's nine days let 's call problem for today airport 's call problem for today airport problem kya rahi hai achcha deformati problem kya rahi hai achcha deformati whatsapp problem whatsapp problem achcha you have understood and those who achcha you have understood and those who want to try it yourself see what is here want to try it yourself see what is here want to try it yourself see what is here happened was that all the functions were named and had all the values easily. The call will be made easily. There is no problem. Rendmai is set here. The set has to be initialized and then it has to be inserted. Some more difficulty is less. No, but there is a removal function in it, it is possible that you are getting stuck somewhere, so what can be the biggest hint for this, that whenever you are removing from a term, if you have Let's suppose that the function is done, so Let's suppose that the function is done, so Let's suppose that the function is done, so what will be this race function that it will be what will be this race function that it will be specifically linked to that point, but specifically linked to that point, but if you try to access this point, it will if you try to access this point, it will also give you the value. also give you the value. Okay, so what you will have to do is to Okay, so what you will have to do is to shift the entire values. shift the entire values. shift the entire values. not get the shift done and you ever go back to the same index, then always provide that value to you. This thing can be important here, it can be the biggest hit here. Well, you did There is There is There is no need to take it, first of all no need to take it, first of all understand it easily, the question is, what is the implementation of this problem? First of all, let's understand what the problem is. Look at yourself. If there was an input, there was something in the given input. It was a And this one was a And this one was a And this one was a vector given in which a lot of vector given in which a lot of numbers were given and numbers were given and how much was to be given in the output, it became clear to me, there is no problem, okay now how will it produce itself, so let's see Which function is ok, it has Which function is ok, it has Which function is ok, it has nothing to do with it, there are nothing to do with it, there are so many stings, you have to take care of yourself too, so many stings, you have to take care of yourself too, so it is not just a so it is not just a function with the name of all these strange things, they function with the name of all these strange things, they are already freely defined, you have to code them. are already freely defined, you have to code them. How to code that if How to code that if this function is ever called, this function is ever called, what does it mean that a new set is created here? what does it mean that a new set is created here? Okay, so no value will be passed with it, that's Okay, so no value will be passed with it, that's what you have to do here. what you have to do here. Creating a new set, okay, Creating a new set, okay, what did you say after that, said, this value is okay, then what should you do, let that function was already given, why did you initialize it, what happened after that, said insert This is the function named insectom, the function call was done automatically. Below, you just had to write some code inside it and after writing the code, you just had to insert the value, it is fine in this set, no problem. is fine in this set, no problem. is fine in this set, no problem. understood similarly that there is some value inside it, that value will be given, what will be the value that there is any value inside it, what will be the value that there is any value inside it, any value, please return a value, any value, please return a value, okay if it has said remove, then we will get it removed from inside but now the output. ok, what did you do at the time of insert ok ok, what did you do at the time of insert ok tell me one thing in which if you already have any value van is ok like take man here ok and then it will be given back to you to insert five It is It is It is fast fast and if you are given to set and there and if you are given to set and there was no 5% here already, then you have to make your was no 5% here already, then you have to make your first return. You have first return. You have understood what to do after making many returns. If you do understood what to do after making many returns. If you do not come out of it, not come out of it, then what is there till now? then what is there till now? then what is there till now? call, what was there inside it? Was there call, what was there inside it? Was there no value in it? There is a value no value in it? There is a value inside it and what is the return? Okay, very good, what happened after that, had to be removed, had to be removed now Okay, Okay, Okay, in this chapter you have said that you have to remove yourself, otherwise in this chapter you have said that you have to remove yourself, otherwise from where will you remove it, then okay, from where will you remove it, then okay, if it is not there and the remove function has been given, if it is not there and the remove function has been given, then what will be the return, okay and if that value is there, then it is okay. And if the function is called, what we do is that we remove that value from here, okay, similarly what is the insert of shirt again, we will set the value of 2 and our true, after that we get random, get random what happened in this entire Trend will be found over the entire vector and any value in it can come in the output. Okay, so any of the 1 or 2 values will come. After that, After that, what will happen in the pudding function of remove function, what will happen in the pudding function of remove function, who had to remove, that means we will do it So can you insert it? Are you already present? Okay, what did you say after that? The get rent function has come back. Okay, There are two more important things which need to be There are two more important things which need to be paid attention to here. paid attention to here. paid attention to here. first you can do it a little bit, four, okay leave everything else, okay do four, okay leave everything else, okay do n't just tell me all this that it n't just tell me all this that it is a vector, anything else is okay, tell me. is a vector, anything else is okay, tell me. is a vector, anything else is okay, tell me. search only in open time, then what elements can they be elements can they be and searching has to be done in them, that too in the oven, so and searching has to be done in them, that too in the oven, so here the thing is here the thing is clear to you, I understand that clear to you, I understand that a lot of things have to be searched in the oven. a lot of things have to be searched in the oven. a lot of things have to be searched in the oven. elements can be Map Map Very easily I understood that if you want to search then you will have to create a map, two are cleared then this is the initialization of yourself, two are cleared then this is the initialization of yourself, What What What else will you keep after 3 in the value? else will you keep after 3 in the value? Tell me what else will you keep in the map after searching in them. Now it is 12345, like it is of size 34. Okay, so Now it is 12345, like it is of size 34. Okay, so you have inserted three inside the map. You will you have inserted three inside the map. You will search it very easily but search it very easily but after that. after that. after that. remain in this vector, then what is the most important factor to remove, tell me its index, otherwise I will remove it, then I said, okay, that's what I wanted, I mean, what I, the company within, got this show I, the company within, got this show I, the company within, got this show done and will get the show done in value like this is three here, here is a three, here cannot come, it cannot come, it cannot come, what did you see in the Paneer set that cannot come, what did you see in the Paneer set that which one which one which one If you try to insert the value from it again, what will come if you try to insert it for the second time? Will you try to insert the value from it? What did you do normally? What will it do? What did you do normally? What will it do? Created a vector of yours. Created a vector of yours. Created a vector of yours. take the map from WAN to the point of time, what will we put inside the map, WAN and what will we do OK, similarly, if we insert then it will not happen. okay, let's okay, let's see, now you say this, this is your function, see, now you say this, this is your function, okay, because you have to do that return, okay, because you have to do that return, right, basically right, basically you have the insert number function here, the you have the insert number function here, the function named insert, what did you say that this is your function named insert, what did you say that this is your tell this van? tell this van? tell this van? first of all tell me whether this value inside the map is ok, is this value present? 1 2 3 4 5 is ok and Apna asked whether the 1 2 3 4 5 is ok and Apna asked whether the value inside the map is ok. value inside the map is ok. value inside the map is ok. search for 10, then along with the search for 10, never told you that there never told you that there is no present in it, so you are always is no present in it, so you are always there, then the minimum answer is possible, it can be Its Its Its value can be you, it will be through, it will value can be you, it will be through, it will be four and A so if I said that if its so if I said that if its value is present, then look at this point of time, it is clear, then that's it. is clear, then that's it. is clear, then that's it. function is cleared and it produces what you Okay, so whatever Okay, so whatever random value comes here, what do we do with it. I have modified the size of the vector with my vector. What will come on the mode, I have modified the size of the vector with my vector. What will come on the mode, like man lo. like man lo. like man lo. you are ok, then the value of tu is the same, Music] Let's Music] Let's discuss a normal thing, discuss a normal thing, first of all, what if a value first of all, what if a value function is called? function is called? If there is no value present in it, if that If there is no value present in it, if that function is called, then only half of the function is called, then only half of the return will be returned, we will do something, it return will be returned, we will do something, it is right, it is clear, it is right, what will we say, if the value which has just been returned is okay that it will be ours and okay that it will be ours and okay that it will be ours and no problem, okay, a also be there from here, there is no value in it, but if you call your index specifically, The show will do fine, you will have to do it well, because of this, you can reduce it by saying that if you shift the last element here then the form will be created that if your value is this, it is okay If you just get it done then If you just get it done then If you just get it done then what will happen here? Now what will what will happen here? Now what will happen is that if you happen is that if you ever call the index in this particular, then it is possible to use it as an inter ever call the index in this particular, then it is possible to use it as an inter function. function. If this is a random motion, here 11 This is the key of whatever was last in the map and now the whatever was found here is last one is sorry thank | 2024-03-24 11:50:32 | 380 | 380 || Insert Delete GetRandom O(1) || Leetcode Daily Challenge |
|
fxvHlezVcOE | hey so welcome back in this another daily code problems so today it's called daily code problems so today it's called missing element an assorted array missing element an assorted array so let's take a peek at this so so let's take a peek at this so essentially what you're given is just an essentially what you're given is just an array called nums as well as an integer array called nums as well as an integer called K and so what you want to do here called K and so what you want to do here is basically you want to find some is basically you want to find some missing number missing number but what really is going on here is that but what really is going on here is that this array has basically a bunch of this array has basically a bunch of numbers that is in ascending order so numbers that is in ascending order so it's sorted from smallest to largest it's sorted from smallest to largest and you can see here it doesn't have to and you can see here it doesn't have to necessarily start like at zero it can necessarily start like at zero it can start at four or five or six or any start at four or five or six or any arbitrary number but what matters is arbitrary number but what matters is that basically when you look from left that basically when you look from left to right it's an increasing order so the to right it's an increasing order so the numbers increase when you look left to numbers increase when you look left to right and so what you can also see is right and so what you can also see is that there's kind of some space between that there's kind of some space between each number at times where here you each number at times where here you don't see the numbers five and six it don't see the numbers five and six it basically goes from four and hops basically goes from four and hops directly to seven and then there's non-8 directly to seven and then there's non-8 but there's a nine but between nine and but there's a nine but between nine and ten well there's no kind of gap between ten well there's no kind of gap between them you just go from nine directly to them you just go from nine directly to ten ten um here's another example it goes one um here's another example it goes one two but then we skip three here two but then we skip three here and then we go on to four and so you and then we go on to four and so you don't necessarily want to grab like any don't necessarily want to grab like any of these missing numbers you want to of these missing numbers you want to grab a particular number and that is grab a particular number and that is described by this integer K and so described by this integer K and so basically what this K symbolizes is that basically what this K symbolizes is that you want to find the first missing you want to find the first missing number and so going from left to right number and so going from left to right here when you're looking at this array here when you're looking at this array you would see that okay you go from 4 you would see that okay you go from 4 and then the next number is seven and then the next number is seven and so there's some missing numbers and so there's some missing numbers between these two which is five and then between these two which is five and then six and we want to grab the first six and we want to grab the first missing number in this array and that missing number in this array and that would then be 5 because that's the first would then be 5 because that's the first number that's missing in this array number that's missing in this array okay and then for this one now that we okay and then for this one now that we want to grab the third missing number want to grab the third missing number when we look from left to right here so when we look from left to right here so in increasing order we see okay it goes in increasing order we see okay it goes four and then it goes seven and so four and then it goes seven and so basically there's two missing numbers basically there's two missing numbers between these two and so then K which is between these two and so then K which is initially three we would subtract 2 from initially three we would subtract 2 from it because essentially we've already it because essentially we've already kind of looked at two missing numbers so kind of looked at two missing numbers so far and so now we're just looking out far and so now we're just looking out for one more missing number which would for one more missing number which would be the next missing number and so then be the next missing number and so then we're looking at okay 7 and then it goes we're looking at okay 7 and then it goes seven to nine seven to nine and while there's a missing number and while there's a missing number between these two which is eight and so between these two which is eight and so now we found another missing number now we found another missing number we're now at zero and so we return this we're now at zero and so we return this missing number eight okay I'll hopefully missing number eight okay I'll hopefully explain that pretty well explain that pretty well um it doesn't make much sense I think um it doesn't make much sense I think the code I will really help you better the code I will really help you better understand this understand this um but yeah so but before I go into the um but yeah so but before I go into the code actually code actually um one thing that I did not realize and um one thing that I did not realize and I first implemented this if we look at I first implemented this if we look at my submissions my submissions um just a little bit ago I solved this um just a little bit ago I solved this question but I did it in O of n time and question but I did it in O of n time and constant space and so the way I did it constant space and so the way I did it is I kind of just did exactly what I is I kind of just did exactly what I told you I kind of went from left to told you I kind of went from left to right and I just tried to hit those right and I just tried to hit those conditions of okay once it hits like a conditions of okay once it hits like a zero or that base case then we just zero or that base case then we just return that particular number return that particular number um but what you can do is actually um but what you can do is actually provide a log n solution and that's provide a log n solution and that's because we can actually use binary because we can actually use binary search for this question search for this question and so that will give us a much better and so that will give us a much better time complexity same space complexity time complexity same space complexity because you're using constant space but because you're using constant space but it's much more performant and so it was it's much more performant and so it was an initial it wasn't an initial it wasn't um very intuitive for me to use that I um very intuitive for me to use that I just thought hey let's do kind of a just thought hey let's do kind of a greedy greedy um linear algorithm for this um linear algorithm for this but the way that you can do it using but the way that you can do it using um binary search I want to kind of type um binary search I want to kind of type that out which gives you this kind of that out which gives you this kind of log and solution log and solution is that okay we have these two pointers is that okay we have these two pointers left and right which is typically what left and right which is typically what you do for binary search and you can you do for binary search and you can find out at every Point find out at every Point how many missing numbers are between two how many missing numbers are between two numbers just by writing like a a numbers just by writing like a a particular Lambda function or just a particular Lambda function or just a function and so one way you can do that function and so one way you can do that is basically you can take is basically you can take say you want to find out okay how many say you want to find out okay how many missing numbers are between nine and missing numbers are between nine and four four and so basically what that's going to be and so basically what that's going to be is nine is nine minus four minus four which is 5 here which is 5 here and so basically there's five missing and so basically there's five missing numbers and so the benefit of this is numbers and so the benefit of this is then we can kind of compare it to K and then we can kind of compare it to K and then that can kind of limit our bound then that can kind of limit our bound saying okay we need at least one missing saying okay we need at least one missing number and while since there's five number and while since there's five missing numbers between this range let's missing numbers between this range let's limit our range between nine and four limit our range between nine and four and so let's no longer look at 10. and and so let's no longer look at 10. and so now we're kind of looking at between so now we're kind of looking at between 4 7 and 9 and so we say okay let's take 4 7 and 9 and so we say okay let's take the midpoint which is seven the midpoint which is seven and so then we do 7 minus 4 and see okay and so then we do 7 minus 4 and see okay how many missing numbers are between how many missing numbers are between these two points and well that's going these two points and well that's going to be to be um three here um three here and so that will enable us to say okay and so that will enable us to say okay well there's also enough missing numbers well there's also enough missing numbers to now be looking between these bounds to now be looking between these bounds and so essentially you get to the point and so essentially you get to the point and we just did where there's only two and we just did where there's only two different numbers four and seven and so different numbers four and seven and so then you just say okay let's take that then you just say okay let's take that left number and just kind of add that uh left number and just kind of add that uh K which is one here K which is one here um and that's pretty much it um and that's pretty much it um I think the only thing that I'm um I think the only thing that I'm missing here is that in some cases you missing here is that in some cases you want to be taken into the account the want to be taken into the account the particular location that you're in particular location that you're in because basically when you're saying because basically when you're saying okay okay really it's not exactly like okay really it's not exactly like okay um take four and nine here um take four and nine here four minus so nine minus four so yeah four minus so nine minus four so yeah there is a difference of five between there is a difference of five between these two numbers but what really these two numbers but what really matters is that you also take into matters is that you also take into account the index like nine here and so account the index like nine here and so that then you just subtract 2 from here that then you just subtract 2 from here because really what this is saying is because really what this is saying is that you're saying that there should be that you're saying that there should be at least five numbers but here you're at least five numbers but here you're saying that there's only two saying that there's only two uh or really I guess three numbers that uh or really I guess three numbers that should be here so really the number of should be here so really the number of missing numbers between these two points missing numbers between these two points is three missing numbers not exactly is three missing numbers not exactly five missing numbers right because there five missing numbers right because there should only be at most three here okay I should only be at most three here okay I hope that made a little bit of sense hope that made a little bit of sense so let's go ahead and implement it I so let's go ahead and implement it I think this will really help solidify think this will really help solidify things so the first thing that you things so the first thing that you typically want to do for binary search typically want to do for binary search is that the left pointer will be zero is that the left pointer will be zero the right pointer will be the length of the right pointer will be the length of the numbers minus one the numbers minus one and so essentially we're going to be and so essentially we're going to be returning some particular missing number returning some particular missing number at the end of this at the end of this okay and so from here okay and so from here um what we definitely want to implement um what we definitely want to implement is that is that um um function for determining what is the function for determining what is the number of missing numbers at a number of missing numbers at a particular index so number particular index so number or I guess return or I guess return the number of missing numbers the number of missing numbers at index I and so to do that we can just at index I and so to do that we can just write like a Lambda function or I could write like a Lambda function or I could just write a normal function and so that just write a normal function and so that would be okay let's call it would be okay let's call it um like missing Lambda um like missing Lambda and so that's going to be essentially and so that's going to be essentially we'll pass in a particular index and so we'll pass in a particular index and so then we're going to return then we're going to return um um the number of missing numbers from that the number of missing numbers from that point on so the number at I and then we point on so the number at I and then we basically just subtract the first number basically just subtract the first number to get the kind of the difference to get the kind of the difference between 9 minus 4 which we did in our between 9 minus 4 which we did in our previous example previous example um but then also we want to take into um but then also we want to take into account the index that you're at so account the index that you're at so that's like the true missing the number that's like the true missing the number of missing numbers not just the of missing numbers not just the difference between the starting and difference between the starting and current number current number all right and so from here there is one all right and so from here there is one Edge case that we have to think about Edge case that we have to think about and so what this is is that at certain and so what this is is that at certain points we can see points we can see um at this case the actual missing um at this case the actual missing numbers is in between these numbers it's numbers is in between these numbers it's actually past four and so we return 6 actually past four and so we return 6 here because 1 2 there's one missing here because 1 2 there's one missing number three right so we number three right so we only need to find two more missing only need to find two more missing numbers and that's pass four so then we numbers and that's pass four so then we would say okay five would say okay five and then we have one more missing number and then we have one more missing number and then after five would be six and and then after five would be six and then this would be zero and so we would then this would be zero and so we would return six we want to account for this return six we want to account for this Edge case Edge case so Edge case where so Edge case where um the missing number is past the last um the missing number is past the last number number and so to do this what we want to think and so to do this what we want to think about is okay about is okay um um we want to look at the missing num the we want to look at the missing num the number of missing numbers number of missing numbers our last index here and so if our k our last index here and so if our k that we have here is greater than the that we have here is greater than the number of the total number of missing number of the total number of missing numbers in this entire array then numbers in this entire array then naturally it's going to be beyond that naturally it's going to be beyond that point and so what that'll look like point and so what that'll look like is then okay let's go ahead and return is then okay let's go ahead and return basically the number the last particular basically the number the last particular number Plus number Plus or I guess minus the number of missing or I guess minus the number of missing numbers in our array so missing at this numbers in our array so missing at this particular loss index and then plus K particular loss index and then plus K which is okay how many or what missing which is okay how many or what missing number are we looking for number are we looking for all right and so from this point on we all right and so from this point on we can actually finally do binary search can actually finally do binary search here so let's go ahead and Implement a here so let's go ahead and Implement a binary search so typically what the binary search so typically what the pattern kind of looks like pattern kind of looks like um is this so while we meet this um is this so while we meet this condition let's go ahead and find the condition let's go ahead and find the current midpoint current midpoint which you can do it a couple different which you can do it a couple different ways but I like to do it this way ways but I like to do it this way and so from here we just want to be and so from here we just want to be looking at two different conditions all right and so basically what we're thinking about is that okay if our um we want to make sure that we're shrinking that range based on the number of missing numbers so we want to get the current kind of number of missing numbers at this particular midpoint and so basically we just care about comparing X um 2K and so from this point on we want to be comparing X to K and so we're saying okay if there is a greater number of missing numbers um at this current midpoint the knots shrink it so if x is greater than or equal to K that just means okay we have enough missing numbers at index M to satisfy um K so let's shrink our range so in that case r will then be equal to the midpoint otherwise we want to do the opposite so basically else it's the inverse of this so it would be like K is greater than x and so that case we want to um not shrink but really just kind of cut the left hand side because we need a greater number of missing numbers moving forward so otherwise then our left pointer will then be equal to the midpoint all right and so once we do this and we finally exit our binary search that then means we finally found where we what is the missing number and so what that's going to be is basically the number on the left hand side plus K because that is essentially the uh what missing number you're looking for but then we also want to be subtracting the number of missing numbers up to L and so what that looks like is that once again if I show you this example maybe um I like this one and so once we find that okay we finally got our left and right pointers the left pointer is at Fourth the right pointer is at seven then we say okay how many missing numbers are up to four well there's no missing numbers so missing will then return like zero and so then the number here at on the left pointer will be four and plus K well K is one and so that in that case would return five if we look at this example here we would get to a point where um let's see we're at seven and so this would return and I'll just kind of erase all these we would be at index seven so left is here and then the right pointers here and then how many missing numbers are up to uh this number seven well that's basically seven minus four minus one because this is index one so that would be returned by this Lambda function and so then that would basically do minus 2 here and then plus K which is 3 so plus 3 and then that would return 8. all right so let's try submitting this and success so that is the Waco problem for today so it's log n time complexity and constant space are o1 space complexity I hope that helped a lot and uh good luck with the rest of your | 2024-03-25 16:33:54 | 1,060 | 1060. Missing Element in Sorted Array - Leetcode Python Solution |
|
8_bJLk5up_M | in this video we'll be going over the question foursome so given array numbers question foursome so given array numbers of n of n integers and an integer target are there integers and an integer target are there elements a b c elements a b c ds and num such that the sum of the four ds and num such that the sum of the four elements is equal to target elements is equal to target find all unique quadruplets in array find all unique quadruplets in array which gives the sum of target which gives the sum of target notice that the solution set must not notice that the solution set must not contain duplicate quadruplets contain duplicate quadruplets so for example we have one zero negative so for example we have one zero negative one zero negative two two and our target one zero negative two two and our target sum is zero sum is zero and we have found three quadruplets in and we have found three quadruplets in which each of the set which each of the set in each set that some of the elements is in each set that some of the elements is equal to equal to zero so let's go over the dot process zero so let's go over the dot process so the brute force approach will be so the brute force approach will be to perform four nested for loops to find all of the possible quadruplets this approach will cost us of n to the fourth time complexity because of the nested we can implement and optimize approach we can implement and optimize approach by sorting the input rate by sorting the input rate in ascending order then we um we can use a for loop or a nested for loop to find the first two elements then we can implement a then we can implement a two-pointer approach for the last two elements this will allow us this will allow us to reduce the time complexity to to reduce the time complexity to of of n to the third of n to the three a side case we have to handle is the solution set must not contain the side case we have to handle this to prevent duplicate quadruplets when we sort the input array all of the duplicate elements are grouped together for example if our quadruplets for example if our quadruplets consist of of the elements consist of of the elements c d if we have already c d if we have already considered a for the first position we considered a for the first position we want to skip all future occurrences of want to skip all future occurrences of a to prevent us from getting a duplicate a to prevent us from getting a duplicate quadruplet quadruplet the same case the same case also apply the same case the same case also apply for b for b c and d so if we have b we have already c and d so if we have b we have already considered the considered the element b for our second position we element b for our second position we want to skip all future occurrences of b want to skip all future occurrences of b and the same case apply for c and d uh and the same case apply for c and d uh this will be more clear in the this will be more clear in the pseudocode pseudocode after we have accounted for a after we have accounted for a number at index number at index i inside our quadriplet i inside our quadriplet we will want to skip all future we will want to skip all future occurrences of let's denote this of x for the position i actually we should call position i instead of calling index i okay now let's go to the pseudocode so okay now let's go to the pseudocode so so we'll sort the input array in so we'll sort the input array in ascending order ascending order then we're going to create a list then we're going to create a list quadruplets quadruplets to keep track of all the quadruplets to keep track of all the quadruplets now we're going to iterate through now we're going to iterate through the indices from the indices from zero to numbers down length minus three zero to numbers down length minus three uh minus four uh minus four because we wanna have space for at least because we wanna have space for at least three more three more elements so this um so these indices elements so this um so these indices the first indices will be accounted for the first indices will be accounted for our first elements our first elements this will be the indices for our first this will be the indices for our first elements which we can say a elements which we can say a so the indices we're going to denote as so the indices we're going to denote as i i and then if i is not equal to zero and then if i is not equal to zero and and the previous elements is equal and and the previous elements is equal to the current elements so the previous element is good to current elements we want to skip the current elements because we have already counted for the current elements in the previous iteration basically if our current number is a and our previous number was also a we want to skip the current a so we just say continue to next iteration then we're going to iterate through the indices from i plus 1 to nums dot length minus 3. this this will be the indices for our second number so in this case will be a second number b so we're going to denote it as j then we have to handle the same case so is not equal to i plus one is not equal to i plus one and the previous elements is equal to and the previous elements is equal to the current elements the current elements we want to skip the current elements so we want to skip the current elements so for example if we if our current for example if we if our current elements b elements b and the element before is also b we have and the element before is also b we have already counted for b already counted for b for the current position so we want to for the current position so we want to skip the current elements skip the current elements now we're going to have our two pointer now we're going to have our two pointer approach to find our last two elements approach to find our last two elements so i'm going to create two variables to so i'm going to create two variables to be our two pointers so we'll have be our two pointers so we'll have k initially at k initially at um j plus one and also um j plus one and also m is our other pointer so initially at m is our other pointer so initially at the end of the array the end of the array so no it's not length minus one um we so no it's not length minus one um we use use m instead of l because the letter l m instead of l because the letter l looks like a one so it can be a bit looks like a one so it can be a bit confusing inside the code so i decide to confusing inside the code so i decide to use the use the letter m instead so letter m instead so while k is less than m while k is less than m that means we can still form a that means we can still form a quadruplet quadruplet if if k is not equal to j plus one if if k is not equal to j plus one and the previous element is equal to the and the previous element is equal to the current elements current elements we have we want to skip the current we have we want to skip the current elements again this is the same as preventing our duplicates in both of the cases above or i and j so when increments then if m is not equal to then if m is not equal to nums dot length minus one and the nums dot length minus one and the current elements current elements is equal to the previous elements we is equal to the previous elements we want to skip the current element too and plus one in this case because we're having our two pointers our two pointers are converging toward the middle so we're gonna decrement m and then now we're gonna find the sum find the now we're gonna find the sum find the sum sum of the four elements located at of the four elements located at indices i j k and m indices i j k and m then if sum is equal to target then if sum is equal to target then we know we have found a valid then we know we have found a valid quadruplet so we're going to add the quadruplet so we're going to add the four numbers four numbers to quadruplets then we'll increment to quadruplets then we'll increment a pointer k so we're going to increment a pointer k so we're going to increment our k pointer our k pointer just to allow us to have access to the just to allow us to have access to the next quadruplet next quadruplet if and then if else if then we'll say if if and then if else if then we'll say if some is less than target we want to increase ours we want to increase our current sum we're going else we're just going to decrease our else we're just going to decrease our sum so we're going to decrement sum so we're going to decrement m and then we can return our quadruplets m and then we can return our quadruplets now let's go over to time and space now let's go over to time and space complexity so the time complexity is equal to of n log n plus of n to the 3 is equal to n of n to the 3 where n and over n log n that's for sorting and and over n log n that's for sorting and of of and cube is is going to be and cube is is going to be [Music] [Music] um two nested for loops um two nested for loops four loops plus two pointer now my space complexity we're going to say of q where q is the total number of again this is our resulting list again this is our resulting list now let's go over the code so we're gonna first create our list for quadruplets now we're gonna sort the empire in now we're gonna sort the empire in ascending order iterate through the indices for our the current elements is equal to the the current elements is equal to the previous elements we want to skip the previous elements we want to skip the current index so just hit continue and then iterate through the indices of our then same similar case we have to skip then same similar case we have to skip the current elements the current elements which is equal to the previous elements which is equal to the previous elements j is not equal to i plus one and the j is not equal to i plus one and the current elements current elements let's go to the previous we want to go let's go to the previous we want to go to your next iteration now we can create our two variables to be our two pointers and then while we can still form and if the current element is equal to the if the current element is equal to the previous elements we want to skip the previous elements we want to skip the current index okay let's go to numbers k minus 1 i'm going to increment k and continue similar case for m if m is not good it's not at the end of the it's not at the last index and the current element is equal to the previous elements now decrement m and then continue now i'm going to find the sum of of the current four quadriplets and we will just uh we have found a and we will just uh we have found a valid quadruplet so i'm going to add valid quadruplet so i'm going to add quadruplets quadruplets add the current phone numbers and then add the current phone numbers and then we're going to increment we're going to increment k actually before here we should be k actually before here we should be doing an else if doing an else if so if else if so if else if some is less than target we want to some is less than target we want to increase our sum by incrementing our increase our sum by incrementing our pointer k pointer k else is greater than target so we want else is greater than target so we want to decrease our sum so we're going to to decrease our sum so we're going to move our right pointer instead and we're move our right pointer instead and we're going to return our quadriplets oh oh because we need to add a list instead so we cannot add it right here let's say erase that as list over four let's say erase that as list over four elements let me know if you have any questions in the comments section below like and subscribe if you would like more videos that will help you pass a technical interview i upload videos every day if you have even any topics that you want to cover below | 2024-03-19 16:06:23 | 18 | 4 Sum - Leetcode 18 - Java |
|
RAVyIJFGUYU | hello guys welcome back to another episode today we are going to solve L episode today we are going to solve L CES daily question which is minimize CES daily question which is minimize maximum pair sum in an array problem maximum pair sum in an array problem number is number is 1877 question is the pair sum of a pair 1877 question is the pair sum of a pair a comma B is equal to a + b the maximum a comma B is equal to a + b the maximum pairer sum is the largest pairer sum in pairer sum is the largest pairer sum in a list of pairs for example if we have a list of pairs for example if we have pair 1 5 2 3 and 44 the maximum pair sum pair 1 5 2 3 and 44 the maximum pair sum would be 1 15 2 3 44 which is would be 1 15 2 3 44 which is 658 okay fine given an array of uh n 658 okay fine given an array of uh n nums of even length n we have to pair nums of even length n we have to pair them into nums into n by two pairs such them into nums into n by two pairs such that each elements of nums is exactly that each elements of nums is exactly one pair and maximum pair sum is one pair and maximum pair sum is minimized fine so what they're looking minimized fine so what they're looking for is uh each element is paired once for is uh each element is paired once that is fine and pair sum is minimized that is fine and pair sum is minimized so what we can do is the maximum number so what we can do is the maximum number should be paired with the minimum so should be paired with the minimum so here they have paired five with two 3 here they have paired five with two 3 with three similarly here they have with three similarly here they have paired five okay we have six so six with paired five okay we have six so six with two which is minimum then it must be two which is minimum then it must be five with three and then four with four five with three and then four with four so this is how they are so this is how they are pairing okay let's move to the approach pairing okay let's move to the approach part okay so what we can do is sort part okay so what we can do is sort array so that we will divide it into n array so that we will divide it into n by2 pair so that we get Max and mean on by2 pair so that we get Max and mean on other side so what it will do is when we other side so what it will do is when we do it when we s for example let's take do it when we s for example let's take this example what it going to do is it this example what it going to do is it is going to take your array and change is going to take your array and change it into so this is going to convert it into this array and when we split it from here we can pair last with first second last with second third last with third so we have to minimize some so that we can pair Max with mean second Max with second mean and so on and at the end add some of these pairs in an array and get maximum from it that's enough for the approach part let's move to the program actual program going to blindly sort it let it be what uh it is then we can get length and let me take so as we have to length and let me take so as we have to divide it into half let me take uh half divide it into half let me take uh half length which is equal to length of we length which is equal to length of we already have total by two so just to be already have total by two so just to be safe int of L of two I in range of half safe int of L of two I in range of half length because we can just uh move to length because we can just uh move to half length what I'm going to do is let half length what I'm going to do is let me just quickly add a variable array SM now SM ARR do append we have to append what that is the first element and last element so the first element is going to be your n nums of I whereas your last element is going to be your total length total length so total last element is going to be your total length minus one this is going to be your last element but what we have to do is we have to subtract your I because first time it is going to be uh zero so that is fine we're going to get last element whereas after that it is going to increment by 1 one so that's why and let me just return uh Max of we have to take Max SM of error and one thing I just notice is the indentation and let me run it quickly and our first test case is accepted as well as the second test case let me submit it | 2024-03-25 11:47:31 | 1,877 | LeetCode Daily Challange 1877: Minimize Maximum Pair Sum in Array |
|
iWQXCP317P4 | so i was giving i was looking at the latest virtual i was looking at the latest virtual contest this is a hard problem number of ways to this is a hard problem number of ways to rearrange rearrange sticks with k sticks visible so you're sticks with k sticks visible so you're just given just given one to n and you want k sticks to be one to n and you want k sticks to be visible from the left visible from the left right now you can see that one three and right now you can see that one three and five visible from the left over five visible from the left over in this example one and three are in this example one and three are visible two and three are visible visible two and three are visible two and three are visible again so two and three are visible again so we have to find out how many such we have to find out how many such combinations exist and then return it combinations exist and then return it modulo modulo 10 to nine plus seven okay now the first thing we want to do is [Music] we want to create some kind of recursive relation as we can see this is thousand and thousands so dp of k into n or even dp of n square k would work so the first thing that came to my mind is maybe it's something to do with the maximum element where i place the maximum element because he will never be hidden but then it gets too difficult because you have to place left and right what about the minimum element minimum element can only be seen at the first index after that he will always be hidden right minimum element will always be hidden after the first release i've already written down some examples i've already written down some examples for explaining for explaining here we can see that let's ignore the here we can see that let's ignore the minimum element minimum element and we are left with two three four five and we are left with two three four five and six here if i remove the middle minimum element okay also another ob this is a key observation given these buildings and these buildings okay is there any fundamental difference in the structure no because these are just buildings with the consecutive difference of one so if you look at the diagram for these buildings it will just be five standing lines one greater another so the first problem is reduced into this right and here we can see building number one and out of the remaining we have to find k minus one buildings so that's one of the ways to reduce the so that's one of the ways to reduce the problem if we are seeing the first problem if we are seeing the first building building now what if we want to hide the first now what if we want to hide the first building building where can we hide the first building the first building can only can be hidden behind any of the other buildings right this one will be hidden behind any of these buildings any of these buildings is greater than one so it could be hidden behind two behind three behind four behind five and behind six so if we want to ignore this element the minimum element we can just ignore it and we have remaining n minus 1 buildings so dp of n minus 1 into k but n minus 1 times so this should be multiplied by n minus 1 ok let's write the recurrent solution first of all we want to see what if we show this building from the left so from the left so show equals to self self.rearrange show equals to self self.rearrange sticks i'm showing the building so i sticks i'm showing the building so i have one less building have one less building and i have one less building to show and i have one less building to show that's it now hide this building behind any of remaining n minus 1 buildings so height will be equal to first of all n minus 1 buildings to hide and then how many different ways to i need to among the n minus 1 buildings i need to among the n minus 1 buildings i need to place k buildings i need to place k buildings so that's for hiding okay so that's for hiding okay and finally we'll just return show plus and finally we'll just return show plus height now one thing we should not forget is to do the module over here and what about the base cases if k is equal to zero cannot show zero buildings if k is equal to n why because there's only one combination why because there's only one combination to show five buildings if i'm given five to show five buildings if i'm given five sticks sticks correct that is in increasing order sorted form if k is greater than n return 0 why i have how is it for humanly possible to see how is it for humanly possible to see n see more n see more right these are the base cases i've right these are the base cases i've written if but it could be alif but of written if but it could be alif but of course return so it shorts course return so it shorts now we can see this code and it won't now we can see this code and it won't run because i forgot to do the modular run because i forgot to do the modular part part of course let's write the modulo code as of course let's write the modulo code as well well modulo 10 raised to 9 modulo 10 raised to 9 plus 7. so that is the first solution this is the solution the same thing i just merged two of the return zero else statements and of course it's dp so we have to put the funk tools cache that is basically automatic memorization this is the code i'll just paste it here this is the code i'll just paste it here so we can see how to reduce it of course that one i forgot to put the funk tools cache so that's why it didn't run now these two if statements could be reduced into one if statement since equal to equal to comes under greater than equal to if i put a greater than equal to here so that's all for the logic if you're just interested in the solution that's all now i'm just making it a one-liner as we see the if statements can be like if it's greater than equal to or it like if it's greater than equal to or it is equal to equal to is equal to equal to when to return 0 when k is n and k is when to return 0 when k is n and k is not 0 not 0 these two if statements have been these two if statements have been reduced into that form reduced into that form uh what about this show and hide all uh what about this show and hide all this can be reduced into a single line this can be reduced into a single line just by pasting these values directly just by pasting these values directly inside what i mean is we can just take the value of show and paste it here take the value of hide paste it here now the final thing this is a if statement so that means this is kind of like an else right so let's just make it a one liner by return end else return that other thing which is else return that other thing which is the recurrent solution the recurrent solution of course you don't have to write return of course you don't have to write return inside the terminal and that's how we get it finally in one and if you did not get my explanation and if you did not get my explanation well uh well uh you can just learn about dp you can just learn about dp and the logic was just this there are and the logic was just this there are two choices two choices one of the choices each of the choices one of the choices each of the choices reduces into a sub problem reduces into a sub problem and in the sub problems n and k is and in the sub problems n and k is always less than the original n and k always less than the original n and k that's why it can be solved by dp since that's why it can be solved by dp since it is acyclic from n and k and it's either going to n minus 1 k which is this one or it's going to n minus 1 k minus 1 so o of n k time and that's it that's how to solve it in one line thanks for watching and yeah please upload the editorial uh if you find it | 2024-03-25 11:22:47 | 1,866 | solve newest leetcode hard in 1 line, 1866. Number of Ways to Rearrange Sticks With K Sticks Visible |
|
wqWv6hHTvyc | Hello Hello Friends Welcome To The Video Chahiye To Code No Problem Equal Nikle To Code No Problem Equal Nikle Central To Change The Language Of Development Central To Change The Language Of Development Cycle Benefits Mono Cycle And You Have To Cycle Benefits Mono Cycle And You Have To Determine The Inside Adsense Problems Determine The Inside Adsense Problems With Sister In English Apoorva Element With Sister In English Apoorva Element West Indies For Declaring His West Indies For Declaring His Pregnancy Director Cycle And Miss Pregnancy Director Cycle And Miss Cycle Stunt In Order For Smooth Is Particular Cycle Stunt In Order For Smooth Is Particular Nudge To Reduce Particular Notification Actress Rekha Richest Man Power Se Type Data Structure Royals Team Storing Day From That Flat They Straight Note One Needs To Read This Is Not To Play Store Read Receive The Loot Read Receive The Loot Read Receive The Loot Debit To Extend Maz Chal Poking Debit To Extend Maz Chal Poking Tax Return File Distorted Please Six Tax Return File Distorted Please Six Pieces Tourist Places 7 Okay Baby To Sit Pieces Tourist Places 7 Okay Baby To Sit In The As It Means Tours1 1919 Total Time In The As It Means Tours1 1919 Total Time Nothing Contents And Which Can Be Seen In The Nothing Contents And Which Can Be Seen In The Present Facts Not At Present Facts Not At All But All But One One Day You Won't Know Which is the Worst Day You Won't Know Which is the Worst Thing Is The Thing Is The Return Return of Rebel Without Oven and Difficult Question To Subscribe To Enter Subscribe To Meat Point Alexis Starting And The Same Question A What Happens Snow Point At Which Has At First At First At First Travel Point Also Pointed Mumbai Two Steps Travel Point Also Pointed Mumbai Two Steps Tax And Return Point Research Tax And Return Point Research Lawyers Mumbai One Step Birthday Gift Lawyers Mumbai One Step Birthday Gift Point At Which Has For Its Object Will Do It Well Mumbai Point At Which Has For Its Object Will Do It Well Mumbai Two Steps Murphy Raw Next Time In Mumbai Again Play Nuvve Nuvve Tips Angry Birds Winter Hai Nuvve Tips Angry Birds Winter Hai Printer 14.5 Printer 14.5 120 B OK 120 B OK Electronic Positive Mumbai Ka Time Table 2018 19 No Matter What This Point to Me Hai Idhar No Matter What This Point to Me Hai Idhar Slow Cycle is Important Hai Pimple Slow Cycle is Important Hai Pimple Play List Snow Point Play List Snow Point Play List Snow Point pointer will move two steps at a time and will not reach the channel and OK but they will me me on the road to cover the on the road to cover the distance from start to cover the distance to the question is. fast 10 steps us five do this lover non muslim point unorganized slow whose main in the next video fast point now return gift open the setting main let me write down let me write down admission with song the best way to cash admission with song the best way to cash Target on Withdrawal Declare Them To Point At Least Point That Point That Point Collect Daily Point Collect Daily Point To The List Of A Ploy Difficult Fast Indore Meetings In England Spinners Patience Cycle To Cycle Found Eligible Which Will Declare Isabgol Invalid Bullion Destination Immediate Destination Immediate Destination Immediate Call Spa Call Spa For Weaver Meeting Note Meeting Night Only In The Recent Election Will To Give Notification United Superstar Claim Notification United Superstar Claim Number Is Channel Number Is Channel Next Day The Next Day The First President Should Definitely First President Should Definitely Not For Not For All Which What Is You Is Tigers For These Truly Which What Is You Is Tigers For These Truly Believe In People From One More Step Believe In People From One More Step Audition Additional District Is Cycle Is From Its Audition Additional District Is Cycle Is From Its Significance Of Many 251 Significance Of Many 251 [Music] [Music] Pointers By One State Book Former Want Pointers By One State Book Former Want And Finally You Will And Finally You Will And Finally You Will latest after cycle understand then select start minute mile solar latest latest points 212 now half new cycle was not from inside the tune of visitors tap this cycle sperm is not regret this capsule vitamin And sewerage and king And sewerage and king And sewerage and king hua tha 120 dars on cycle part mahal gautam returning blood to it's ok to ki reddy whatsapp problem times new cycle click on this issue how to give very good and gives nod to steer with this situation ok no land beam That This Spider Solitaire Life Not Passed With That This Spider Solitaire Life Not Passed With Very Super Mr. Vivek Oberoi Jab Very Super Mr. Vivek Oberoi Jab First Epistle To This Amazon | 2024-03-21 12:36:11 | 142 | LEETCODE 142. Linked List Cycle II Explanation + Code |
|
Jip-D8TgsGM | welcome to september's leeco challenge today's problem is bulls and cows you today's problem is bulls and cows you are playing the following bulls and cows are playing the following bulls and cows game with your friend you write down a game with your friend you write down a number and ask your friend to guess what number and ask your friend to guess what the number is the number is each time your friend makes a guess you each time your friend makes a guess you provide a hint indicating how many provide a hint indicating how many digits in the guess match your secret digits in the guess match your secret number exactly number exactly in both digit and position those are in both digit and position those are called bulls called bulls and how many digits match the number but and how many digits match the number but are located in the wrong position those are located in the wrong position those are called cows are called cows so for example if we're given the number so for example if we're given the number 1807 and we're 1807 and we're given the guess 7810 we have one bull given the guess 7810 we have one bull because the eight because the eight is the right position and digit and we is the right position and digit and we have three cows because we have one zero have three cows because we have one zero seven seven and seven one zero we have the right and seven one zero we have the right digits but they're in the wrong position digits but they're in the wrong position if they don't match at all then we don't if they don't match at all then we don't return anything return anything and so on and so forth so this problem and so on and so forth so this problem is a little trickier than i expected but is a little trickier than i expected but the straightforward approach works fine the straightforward approach works fine here here what i'm going to do is convert both our what i'm going to do is convert both our secret and guess into a list secret and guess into a list a list of digits and what i'll do is go a list of digits and what i'll do is go through each position through each position and check to see if both the position and check to see if both the position and the digit match and the digit match if they do then i will pop that digit if they do then i will pop that digit off of the secret and guess off of the secret and guess and increase our bull counter once and increase our bull counter once that's finished i should have the that's finished i should have the leftover digits leftover digits and these are the possible cows right and these are the possible cows right because because maybe they're the right digit but maybe they're the right digit but they're in the wrong position we already they're in the wrong position we already know they're in the wrong position for know they're in the wrong position for sure sure so what i'll do now is create a counter so what i'll do now is create a counter object and just go through our guess and object and just go through our guess and see if see if any of these digits are in the count in any of these digits are in the count in the counter object if they are then the counter object if they are then we'll increase our bull or our we'll increase our bull or our cow count and we'll decrease the counter cow count and we'll decrease the counter all right so uh first thing i'll do is all right so uh first thing i'll do is initialize bull initialize bull and cow both as zero and i'm going to and cow both as zero and i'm going to convert our convert our secret and our guess into a list so what secret and our guess into a list so what i'll do i'll just call that s i'll do i'll just call that s we'll say list for secret and we'll say list for secret and for guests i'll call that g list or for guests i'll call that g list or guess guess now this part was a little bit trickier now this part was a little bit trickier uh what i want to pop off uh what i want to pop off uh the the digits if they're in the uh the the digits if they're in the right position for both the right position for both the both the secret and the guess right so both the secret and the guess right so what i'll do here is what i'll do here is initialize two variables i and j initialize two variables i and j i'll say while i is less than the length i'll say while i is less than the length of of secret or guess it doesn't matter secret or guess it doesn't matter because we can assume they're going to because we can assume they're going to be the same length be the same length we'll say if the s i is we'll say if the s i is equal to g i uh what will we do we'll equal to g i uh what will we do we'll pop it off pop it off so we'll pop it off of both i and sng but the thing is because i'll be popping it off while i go through this loop i need to make sure i'm in the right position so what i have to do here is actually use this j object i'll increase our bull by one whoops and i'll increase our oops our j counter by one as well because actually no we don't do that we will do that only if they don't match we'll increase our j counter if they don't match then we know we can move ahead in our j counter and we'll always move ahead for our i counter so that we'll get through the entire list all right so now we have all the bulls and now we have two lists that have the numbers which were not in the right position right so all that is required now is what i'll do is create a counter object using the s and this is going to be all the numbers and the number of them inside that are correct right so for the let's say l in for the letter in our guess g if this l is in the count object and the count [Applause] number for this character is greater than zero then we'll increase our cow and we'll decrease our count l by one just to make sure that we don't reuse any of those so once that's it we have both our bowls and cows so we can just return a string what i'll do is use the format string i'll say how many bulls how many cows and we'll say bull cow uh looks like i got an inject out of uh looks like i got an inject out of range range i hmm i guess this needs to be a j i hmm i guess this needs to be a j and that makes sense because i'm popping and that makes sense because i'm popping these off right yeah so i guess i need to be a j that's my mistake and it looks like it's working let's go and accept it all right so this approach and accept it all right so this approach is ofn and also probably uses ofn time is ofn and also probably uses ofn time complexity as well complexity as well which is fine like which is fine like the real big part here is figuring out the real big part here is figuring out that we have to use some sort of hash that we have to use some sort of hash object to check to see object to check to see if our digits are inside of our secret if our digits are inside of our secret but not in the right position but not in the right position there's definitely better approaches to there's definitely better approaches to this this is definitely not the best one this this is definitely not the best one but it works i think it's pretty but it works i think it's pretty understandable so understandable so just gonna go with that so thanks for just gonna go with that so thanks for watching my channel and remember watching my channel and remember do not trust me i know nothing | 2024-03-22 14:36:20 | 299 | Leetcode - Bulls and Cows (Python) |
|
FvW-sVhwnxY | cool 120 triangle given a triangle find the minimum pass some from top to bottom the minimum pass some from top to bottom each step you may move to adjacent each step you may move to adjacent numbers on the wall below exam we're numbers on the wall below exam we're given the following triangle some number given the following triangle some number the minimum have some time talk to the minimum have some time talk to bottom is 11 bonus point to be able to bottom is 11 bonus point to be able to do this using of an extra space where n do this using of an extra space where n is the total number of rows in the is the total number of rows in the triangle okay I mean it depends how you triangle okay I mean it depends how you want to define space you actually just want to define space you actually just used her input anyway and mutated but I used her input anyway and mutated but I assume that's that is you know assume that's that is you know cheerfully doctor point but uh yeah I cheerfully doctor point but uh yeah I mean I think this is actually standard mean I think this is actually standard and this actually so I think yeah so and this actually so I think yeah so this goes back to what we talked about this goes back to what we talked about earlier with bottoms up and Todd cow so earlier with bottoms up and Todd cow so you could certainly do this top down you could certainly do this top down with recursion and stuff like that but with recursion and stuff like that but but then you you're not going to be able but then you you're not going to be able to do it over any extra space so you to do it over any extra space so you have to do in dynamic programming in have to do in dynamic programming in this particular case oh sorry bottoms up this particular case oh sorry bottoms up dynamic programming to to get the of an dynamic programming to to get the of an extra space requirement and I think extra space requirement and I think that's what we're going to do yeah I that's what we're going to do yeah I mean I think this is a video on this a mean I think this is a video on this a standard eat problem but yeah we're Xbox standard eat problem but yeah we're Xbox for ya okay and I'm actually just gonna for ya okay and I'm actually just gonna be yeah the thing to note is that for be yeah the thing to note is that for each row you only need to look at the each row you only need to look at the world minus one or the world on top or world minus one or the world on top or the bottom to value one I think is the bottom to value one I think is symmetric it's just that if you don't do symmetric it's just that if you don't do it symmetric I mean it's symmetric but it symmetric I mean it's symmetric but if you defined how you want to do it if you defined how you want to do it some ways are no easier than other but some ways are no easier than other but um but yeah okay that's tough Mia so I think just well actually I could so I think just well actually I could come too maybe okay I know I said I was come too maybe okay I know I said I was gonna do things in place and you could gonna do things in place and you could certainly do it but I think I just for certainly do it but I think I just for the sake of my practice actually I'm the sake of my practice actually I'm gonna do this in this max I guess they gonna do this in this max I guess they don't tell you I should understand let's go okay so we want to set up to the first world mr. face case we just have to do that's the last one you know now we actually children is equal to 20 go class before such a or so it's take the minimum from the one that's under or the 100-200 okay I think that's it - let me teach my train so now one spot was today there another way to do this I think where you just use a two-dimensional or like a yeah matrix with two elements in any kind of smoke them right I think this one just way slightly clear basically we do and this is a maybe see specific but it's uh it this way I should be well but yeah but this just swapped a pointer so you could kind of we use the same erase I mean you could do that in Python - it's just swapping references so it's not specific I guess actually okay so you want to be turning currency all kind of is its kind because I think that as well do you like maybe Ines figured I as well do you like maybe Ines figured I got sick for something that's coming got sick for something that's coming universe but I might not have added one universe but I might not have added one thing hmm it's even a better path I thing hmm it's even a better path I think I just didn't add to to at the end I mean that's the answer for because we swap the current so that current is actually the last one percenters what I do before action should work that's the way one element that we tested I never prints maybe there is stuff I never prints maybe there is stuff crashing empty away okay then maybe I crashing empty away okay then maybe I don't need this an imprint okay I'm missing that case huh just fix it I'm a little lazy think about everything okay cool yeah yeah so this is kind of the UH actually way related to what we were just talking about obviously a easy example to understand because you could actually think about was if you would do it kind of top-down then you would definitely need an and square matrix to represent or these you know each of T's and even with Bottoms Up you could have easily done it with two-dimensional matrix but this allow us to kind of because we only we know that you only care about the on top or on the bottom of the way I did actually but I don't top on bottom then like yeah you only so you only need to need to know the content but that's well so you don't have to over allocate memory for stuff like that cool that's kind of that next funny term for this one this is a relatively straightforward problem I mean I think this also is one of those canonical dynamic programming problems so that's why I'm able to get it very quickly and hopefully I get that feels good having one cool thing I want to point out is that I actually implement not just per se but a similar thing like maybe I want to say 10 to 15 years ago actually comes up in a real world thing well but some definition we were anyway you're interested in all of these stuff is the if you have a play around with like Adobe Photoshop or something like that where you take an image and then you kind of resize it either squeezing that say squeezing them together right and squeezing them together you know there's obviously the story scale is a one one one way you could do the resizing you just kind of squish shrink together another cool thing that they cause I was at content aware okay I tried to content a real content sensitive but we have a name and a core these days but can't let's say content-aware resizing and what that happens what happens there is that and once you kind of familiar with this problem is that it actually takes a shortest minimum a minimum cost path from the top and the bottom or to the bottom and then delete that path so and and the cost function yeah you can play around with it and I think they tweak of it over the time but a really naive cost function is just like well look at your surrounding colors like you want to know one basically a cost function that is as similar to the cost of the new by ourselves as possible and trust they doesn't do English it means like let's say you have nothing but blue skies then yeah then you your assumption is that no one would miss it that much if you miss like a sliver blue sky right like versus if you take away I don't know say half my face or something or like two three columns off my face then like you'll notice that I don't have a nose or something right I don't know so that's kind of the idea between that behind that and and that just as you can imagine finding a minimum cost path from the top to bottom using this this cost function guide is using dynamic programming and that's actually one of the cool like earlier things that I learned about back in the day oh my god yeah wow you actually do your standard vogue wearing these things and and I definitely worked like playing around some projects on that it's kind of cool I guess nowadays everyone takes all these magical things for granted but like the image manipulation and stuff like that cool yeah I think this is a waste and applause oh I very much whatever expected this is yeah expected on an integral I would say long day and I don't really have much of a forum I think I keep saying postpone it but I mean retro just cause actually like this | 2024-03-21 11:07:37 | 120 | 120. Triangle (Leetcode Medium) |
|
oXEPfYaMOwI | in this video we're going to take a look at a legal problem called design a at a legal problem called design a memory file system memory file system so basically the goal is we want to so basically the goal is we want to design a data structure that implements design a data structure that implements or simulates an in-memory system or simulates an in-memory system file system so implement this file file system so implement this file system class system class that supports these following functions that supports these following functions so in this case we're basically so in this case we're basically have a constructor that initializes the have a constructor that initializes the object the system object the system and we also have this ls function and we also have this ls function basically basically do couple things here so if the it takes do couple things here so if the it takes a path a path right in a string format and if the path right in a string format and if the path is a file path is a file path right returns a list that only contains right returns a list that only contains this file's name this file's name okay and if it's a directory path we okay and if it's a directory path we want to return want to return the list of file and directory names the list of file and directory names in this directory so the answer should in this directory so the answer should be be lexical graphical order basically we lexical graphical order basically we want to want to return a list right of string that return a list right of string that contains contains either the file name if it's a file path either the file name if it's a file path if it's a directory path we want to if it's a directory path we want to return all the files return all the files as well as directory names under the as well as directory names under the current directory right current directory right in sorted order of course um and then in sorted order of course um and then you can also see you can also see here we have mkdir it takes the path here we have mkdir it takes the path and then it makes a direct new directory and then it makes a direct new directory according to the given path according to the given path so the given directory path does not so the given directory path does not exist exist if the middle directories in the path if the middle directories in the path does do not exist we should create them does do not exist we should create them so basically what we're going to do is so basically what we're going to do is that we're basically just going to that we're basically just going to create this path right this create this path right this this this path um so for example if we this this path um so for example if we have something like this we want to have something like this we want to create a create a we want to create b we'll create c each we want to create b we'll create c each of them is our directory of them is our directory and then b is under the a directory c is and then b is under the a directory c is under the b directory right under the b directory right so and then we also have add content to so and then we also have add content to file so it takes the file path and file so it takes the file path and content so what we're basically doing is content so what we're basically doing is we take we take this file path that's already exists this file path that's already exists right if the right if the if the file path path does not exist if the file path path does not exist create the file path containing the create the file path containing the given content given content but if it exists we basically just uh but if it exists we basically just uh appends the given content to the appends the given content to the original content right original content right and then we also have another function and then we also have another function called read content from called read content from file so this takes a file path returns file so this takes a file path returns the content in that file the content in that file right so the file path should be existed right so the file path should be existed okay um so you can see here we have an okay um so you can see here we have an example example right so initially we initialize the right so initially we initialize the class uh we create instance of this class uh we create instance of this class and then class and then in this case we're calling this ls in this case we're calling this ls function we basically passing a function we basically passing a directory in this case is the root directory in this case is the root directory directory there's nothing under this root so we there's nothing under this root so we return a list right empty list return a list right empty list so then we create this path so we have so then we create this path so we have abc abc so in this case we created directory a so in this case we created directory a create directory b create directory b b is under a c is under b right b is under a c is under b right and then in this case you can see here and then in this case you can see here is a void function we're not returning is a void function we're not returning anything anything so once we create this directory and so once we create this directory and then we're going to add a content then we're going to add a content add content to this to the file in this add content to this to the file in this case it's abc case it's abc and then we are creating the last one and then we are creating the last one right there is d right there is d that's basically a file right this file that's basically a file right this file basically basically we have a content that we're going to we have a content that we're going to append on to it right append on to it right so you can see here uh this is the file so you can see here uh this is the file name and then this is the content so name and then this is the content so we're basically creating that right we're basically creating that right and then you can also see fs uh sorry uh and then you can also see fs uh sorry uh ls we're basically ls we're basically going to call this function we are going to call this function we are getting getting this directory right which is under the this directory right which is under the root directory root directory so only directory a is in the root is in so only directory a is in the root is in the directory root right the directory root right so then if i want to read content from so then if i want to read content from the file you can see here the file you can see here it will return as hello right because it will return as hello right because here you can see here you can see d we already assign hello there so the d we already assign hello there so the output is the file and content output is the file and content and then you can see here the and then you can see here the constraints is that we're guaranteed to constraints is that we're guaranteed to have have path and file path our absolute path path and file path our absolute path which begins with this which begins with this not end with this except the path is not end with this except the path is just this right just this right and you can see here that you can assume and you can see here that you can assume that all the directory names and file that all the directory names and file names only contain names only contain lowercase letters and the same names lowercase letters and the same names will not exist will not exist in the same directory uh you can assume in the same directory uh you can assume that all operations will be passed as that all operations will be passed as valid parameters and users will not valid parameters and users will not attempt to retrieve file in the content attempt to retrieve file in the content or or list of directory or file that does not list of directory or file that does not exist exist so basically a couple of things that i so basically a couple of things that i want to clarify for this question want to clarify for this question first of all for each and every single first of all for each and every single path right either a path or a file path path right either a path or a file path you can see this is our path you can see this is our path right this can be a string right this can be a string right this can be a long word it doesn't right this can be a long word it doesn't have to be one character i didn't really have to be one character i didn't really know that know that when i first tried to do this question when i first tried to do this question so in this case so in this case like for each directory or for each file like for each directory or for each file name i could have name i could have more than one characters right i could more than one characters right i could have slash a b have slash a b c d slash d uh b c c d slash d uh b c d or whatever like it could be a long d or whatever like it could be a long words it doesn't have to be one words it doesn't have to be one character character so that's one thing now the other thing so that's one thing now the other thing that we have to pay attention to is this that we have to pay attention to is this add add content to file function um the other content to file function um the other thing that we have to pay attention to thing that we have to pay attention to is that is that when we're creating this when we're at when we're creating this when we're at content to this file maybe we have to content to this file maybe we have to create this directory or we don't create this directory or we don't right we append the string onto the right we append the string onto the content that we have already content that we have already onto this onto this current existing onto this onto this current existing content right content right if there is if there is content for this if there is if there is content for this file right for this file d file right for this file d then we just have to append hello right then we just have to append hello right after that content right after that content right if there is not if there's no content if there is not if there's no content then we just have to then we just have to put this as the content for this file put this as the content for this file right so right so basically this ad content doesn't mean basically this ad content doesn't mean that we have to replace what we have that we have to replace what we have before right for this file before right for this file or basically just append this content or basically just append this content onto onto uh what we have in this file right so uh what we have in this file right so that's another thing that we have to that's another thing that we have to clarify clarify um so other than that um let's take a um so other than that um let's take a look at look at how how we can be able to solve this how how we can be able to solve this right so of course like the brute force right so of course like the brute force approach approach will probably be that we are just going will probably be that we are just going to store to store each and every single path onto like each and every single path onto like some kind of like a table some kind of like a table right and let's say if i want to you right and let's say if i want to you know for example if i want to create a know for example if i want to create a directory directory i will just say this is the path and i will just say this is the path and then then i'll i will create it in our table right i'll i will create it in our table right and then add map or at content i'll just and then add map or at content i'll just same thing i would just you know create same thing i would just you know create it and then just return it and then just return and then just add it onto our our table and then just add it onto our our table add a row onto our table right add a row onto our table right but let's say if i want to do ls in this but let's say if i want to do ls in this case if i want to find case if i want to find all the file uh all the file path all the file uh all the file path or all the directories um under or all the directories um under the current uh path then i have to the current uh path then i have to check for each and every single rows check for each and every single rows right each every single right each every single um keys um keys prefix to see if it match so in this prefix to see if it match so in this case what we have to do is we have to go case what we have to do is we have to go to our table and then for each and every to our table and then for each and every single key we basically have to check single key we basically have to check for um you know for its prefix for um you know for its prefix to see if the current path um is the to see if the current path um is the prefix prefix of our current key right and then of our current key right and then if our current key is a directory if our current key is a directory right is it is it there's a directory right is it is it there's a directory under this path under this path right so in this case you can see we right so in this case you can see we have to iterate through the entire have to iterate through the entire table to do so so what we can do instead table to do so so what we can do instead is we can basically use a try is we can basically use a try data structure right to basically avoid data structure right to basically avoid checking each and every single keeps checking each and every single keeps prefix in our table prefix in our table so in this case let's say this is our so in this case let's say this is our path right we want to create this path right we want to create this you know we want to create this path in you know we want to create this path in this case we can basically have a try this case we can basically have a try in this case let's say this is our try in this case let's say this is our try right uh right uh you can see this is one file or this is you can see this is one file or this is one directory and then you can see that one directory and then you can see that there's two directories under there's two directories under this directory so in this case you can this directory so in this case you can see we can basically use a try see we can basically use a try to uh store our our files right our to uh store our our files right our directories directories uh in a trial in a try right in this uh in a trial in a try right in this case let's say the last one right here case let's say the last one right here let's say this let's say this abd is a um it's a file right what we abd is a um it's a file right what we can do is that inside our can do is that inside our our try class right what we can do is our try class right what we can do is that we can have a variable called that we can have a variable called content right if the content is content right if the content is initially content is null if it is not initially content is null if it is not null basically we know that this null basically we know that this this node right has a content this node right has a content right so in this case if i want to um right so in this case if i want to um basically realize that this node has a basically realize that this node has a content content then we can just return a list only then we can just return a list only contain the contain the the file's name right if the path is a the file's name right if the path is a directory path let's say this doesn't directory path let's say this doesn't have a content right let's say b doesn't have a content right let's say b doesn't have a content have a content it's not a content uh or not a file path it's not a content uh or not a file path in this case what we can do is we can in this case what we can do is we can return the list of files return the list of files and the directory names in this and the directory names in this directory so in this case we have c and directory so in this case we have c and d d right so in this case i'm going to show right so in this case i'm going to show you to approach how we can solve this you to approach how we can solve this problem problem but for each approach i'm going to talk but for each approach i'm going to talk about the pros and cons for each of them about the pros and cons for each of them so you can see here that what i'm trying so you can see here that what i'm trying to do here is to do here is inside our file system classes that have inside our file system classes that have a root which is basically the root a root which is basically the root node and then you can see we have a node and then you can see we have a trinomial and this trinode you can see trinomial and this trinode you can see here we have here we have two variables so one is the contents two variables so one is the contents initially we have null initially we have null and then we also have children in this and then we also have children in this case we have a table that keep track of case we have a table that keep track of uh kernel's children right the string is uh kernel's children right the string is basically basically the current directory's name and then we the current directory's name and then we have trinode which is basically the the have trinode which is basically the the the chosen right um of that the chosen right um of that directory right so and then you can see directory right so and then you can see here we have our ls function we takes here we have our ls function we takes the it takes the path the it takes the path and then basically what we're trying to and then basically what we're trying to do here is we're trying to get to the do here is we're trying to get to the correct node right correct node right so let's say the path is equal to a b so let's say the path is equal to a b right let's say if the path is equal to right let's say if the path is equal to slash a slash b then in this case slash a slash b then in this case we're going from the root we're going we're going from the root we're going down to a and then go down to b down to a and then go down to b right we want to get to the the last right we want to get to the the last node and then once we're at the last node and then once we're at the last node what we're going to do is we're node what we're going to do is we're going to get all the keys that we have going to get all the keys that we have for this node and then we're going to for this node and then we're going to sort it right sort it right because we want to you know we want to because we want to you know we want to have a have a uh return a list that is in lexical uh return a list that is in lexical order right order right we're basically in a uh increasing order we're basically in a uh increasing order uh uh sort of increasing sorted order right sort of increasing sorted order right for our string and then we're returning for our string and then we're returning as children right as children right and let's say if the path does equal to and let's say if the path does equal to you know this thing right which is still you know this thing right which is still okay okay like we're basically at the root and like we're basically at the root and then we're just going to return then we're just going to return you know the currents all the children you know the currents all the children for the current node right in this case for the current node right in this case it's just a it's just a right and we're basically add a onto the right and we're basically add a onto the list and then we're returning that right list and then we're returning that right we're sorting and we're sorting and returning that right and then if i want returning that right and then if i want to to create a directory in this case it takes create a directory in this case it takes a path and then what we're going to do a path and then what we're going to do is we're going to split is we're going to split by this string right and then basically by this string right and then basically here you can see we're basically here you can see we're basically starting at index 1 because if we starting at index 1 because if we are splitting by the uh are splitting by the uh you know the slash that in this case the you know the slash that in this case the first first index right the first element in the index right the first element in the array is basically going to be empty array is basically going to be empty right empty string and then what we're right empty string and then what we're going to do is that we're going to start going to do is that we're going to start to traversing to traversing the tree right starting for traversing the tree right starting for traversing to try so we have current string to try so we have current string array at i and then we check to see if array at i and then we check to see if it contains if it doesn't contain we it contains if it doesn't contain we create that in that create that in that uh create that element in the table uh create that element in the table and then we're basically traversing and then we're basically traversing right so in this case let's say if the right so in this case let's say if the path again if it's path again if it's abc right we're going to start from the abc right we're going to start from the roots go from here roots go from here here and here right pretend that you here and here right pretend that you know know bc is not there before right so bc is not there before right so that's we're basically doing and then at that's we're basically doing and then at the end you can see we also have another the end you can see we also have another function function add content to file which is also pretty add content to file which is also pretty easy right you get an idea we're easy right you get an idea we're basically creating that path if it's not basically creating that path if it's not there there and then if current.content is not null and then if current.content is not null then we basically just add that content then we basically just add that content out the current content onto it out the current content onto it if it's null we basically just set the if it's null we basically just set the current node's content to be content current node's content to be content for reading content from the file it's for reading content from the file it's pretty much similar pretty much similar right we're basically get to that node right we're basically get to that node and then what we're going to do and then what we're going to do is we're just going to return the is we're just going to return the current node's content right current node's content right so that's basically it which is pretty so that's basically it which is pretty simple simple but you can see that the core function but you can see that the core function is here right where is here right where basically you can see the time basically you can see the time complexity complexity for this right well basically when we for this right well basically when we try to get to this node in this case try to get to this node in this case it's basically just it's basically just m right m is basically how many uh m right m is basically how many uh or basically the longest path right or or basically the longest path right or the path the path right is basically it's basically the right is basically it's basically the path that we have the traverse right we path that we have the traverse right we basically have to traverse each and basically have to traverse each and every single every single uh kind of like each and every single uh kind of like each and every single string string that we have in our path right or in that we have in our path right or in this case if we want we want to traverse this case if we want we want to traverse each and every single directory each and every single directory right in our path once we get to the right in our path once we get to the last directory last directory we have to do our sorting right and this we have to do our sorting right and this current directory could have many current directory could have many directories under this directory directories under this directory so in this case we have to perform a so in this case we have to perform a sorting in this case sorting in this case is going to be depends on how many is going to be depends on how many elements that this directory has right elements that this directory has right let's say we have k let's say we have k number of elements then it's going to be number of elements then it's going to be k log k k log k right so you can see the time complexity right so you can see the time complexity for this is basically going to be m for this is basically going to be m plus k log k right plus k log k right so in in this case you can see here um so in in this case you can see here um this is this is this is basically the time complexity this is basically the time complexity for this and then for other for this and then for other functions right um basically you can see functions right um basically you can see that that we're basically just going to um we're basically just going to um going to create this directory so it's going to create this directory so it's going to basically m right basically m going to basically m right basically m is basically the size of our path same is basically the size of our path same thing for this one thing for this one as well as this one right basically as well as this one right basically we're traversing down this file path or we're traversing down this file path or directory path and then we're you know directory path and then we're you know changing some stuff changing some stuff right um and then that's it right um and then that's it but let's say but there's also another but let's say but there's also another way we can solve this problem way we can solve this problem to use a tree map right a tree map to use a tree map right a tree map basically is kind of like a hash map but basically is kind of like a hash map but we're basically just going to keep the we're basically just going to keep the tree right keep tree right keep all the elements in our tree in a sort all the elements in our tree in a sort of of sort of manner right but time complexity sort of manner right but time complexity for for you know adding elements removing you know adding elements removing elements and then checking to see if key elements and then checking to see if key exists exists is going to be a log in right because is going to be a log in right because this uh this this tree map this uh this this tree map basically uses and basically you can see basically uses and basically you can see that the the tree map implements red that the the tree map implements red black tree which is basically a self black tree which is basically a self self-balancing binary search tree self-balancing binary search tree right and we know that for insertion and right and we know that for insertion and deletion in binary surgery where binder deletion in binary surgery where binder tree tree is basically just going to be log in so is basically just going to be log in so therefore therefore if we were to solve this problem using a if we were to solve this problem using a using a tree map using a tree map right um the time complexity for you right um the time complexity for you know insertion know insertion and delete and reading elements or and delete and reading elements or basically traversing down this path basically traversing down this path right for example mostly those two right for example mostly those two functions uh add content functions uh add content we basically if if the the current node we basically if if the the current node doesn't have the string doesn't have the string then we basically have to insert it then we basically have to insert it right which is basically a login right which is basically a login or log k time complexity right or log k time complexity right um and then you can see here k is um and then you can see here k is basically the the size of our current basically the the size of our current nodes tree map size right and then we nodes tree map size right and then we basically have to traverse down this basically have to traverse down this file path file path and but for this function in this case and but for this function in this case because this is already sorted because this is already sorted we're basically all we're trying to do we're basically all we're trying to do is we're trying to go down to the is we're trying to go down to the correct path correct path and then we're just going to get its and then we're just going to get its children so you can see that time children so you can see that time complexity is basically just m complexity is basically just m which is basically how many directories which is basically how many directories that we have to go down to right that we have to go down to right so you can see that each and every so you can see that each and every single solution has single solution has its pros and cons if we're using entry its pros and cons if we're using entry map map for insertion it's basically going to be for insertion it's basically going to be a a you know kind of like m times log k you know kind of like m times log k and then for ls function in this case and then for ls function in this case we're basically just going to have we're basically just going to have m right or bagel of m right m right or bagel of m right because the tree battery is already because the tree battery is already sorted and all we have to do here is sorted and all we have to do here is basically just getting its children basically just getting its children right so that's basically how we're right so that's basically how we're going to solve the problem going to solve the problem and thank you for watching | 2024-03-20 12:00:05 | 588 | [Java] Leetcode 588. Design In-Memory File System [Trie #2] |
|
PNxHyHKcAJE | friends today I'm going to solve liquid problem number 373 find gay pairs with problem number 373 find gay pairs with smallest sums so in this problem we are smallest sums so in this problem we are given two integer arrays nums 1 and given two integer arrays nums 1 and nobster and it is sorted in ascending nobster and it is sorted in ascending order and we are also given an integer k order and we are also given an integer k now now um um here what are we going to do is we are here what are we going to do is we are going to form pairs where U is from the going to form pairs where U is from the first array that is number one and V is first array that is number one and V is from nums 2 and we are going to form from nums 2 and we are going to form Cape such Pairs and those K such pairs Cape such Pairs and those K such pairs should have smallest sum so U1 plus V1 should have smallest sum so U1 plus V1 should be the smallest sum U2 plus V2s should be the smallest sum U2 plus V2s would be the second smallest and so on would be the second smallest and so on so basically we need case such sums so basically we need case such sums whose whose um some of the pairs is the smallest of um some of the pairs is the smallest of all of the others okay so let's look at all of the others okay so let's look at this example here so what are we given this example here so what are we given is let's say is let's say let's stay here and let's stay here and look at the example look at the example all right so we are given nums one and all right so we are given nums one and Norms to end the value of K is equals to Norms to end the value of K is equals to 3 which means that we need three such 3 which means that we need three such pairs with the smallest sum now since we pairs with the smallest sum now since we already know these two uh array are already know these two uh array are sorted in ascending order so the first sorted in ascending order so the first two will always be the smallest number two will always be the smallest number which means that the first two of these which means that the first two of these elements will always be the smallest one elements will always be the smallest one so if we take the pair one two the sum so if we take the pair one two the sum is always going to be the smallest which is always going to be the smallest which is equals to 3. now let's take the next is equals to 3. now let's take the next pair so if we take one and if we take pair so if we take one and if we take four four that would also be the smallest one that would also be the smallest one right because it equals five right because it equals five now like like if you are taking 7 and 2 now like like if you are taking 7 and 2 that's equals to 9 which is greater so that's equals to 9 which is greater so instead of taking seven two what we do instead of taking seven two what we do is we take one and four is we take one and four now we are also taking the sum 1 and 6 now we are also taking the sum 1 and 6 here so let's see here one six and this here so let's see here one six and this gives us equals to 7 which is again gives us equals to 7 which is again smaller than 7 and 2 right so basically smaller than 7 and 2 right so basically what are we doing is we want the what are we doing is we want the smallest sum so we are taking the sum of smallest sum so we are taking the sum of one and two sum of one and four sum of one and two sum of one and four sum of one and six we are also taking the sum one and six we are also taking the sum of seven and two seven four seven six of seven and two seven four seven six and so on so if you were to perform and so on so if you were to perform Brute Force we would take each of the Brute Force we would take each of the elements from here and take some with elements from here and take some with each of the elements over here and then each of the elements over here and then um find the smallest K element so for um find the smallest K element so for that basically we could use mean Heap that basically we could use mean Heap Okay so Okay so let me just show you over here so that I let me just show you over here so that I can draw the solution and it would be can draw the solution and it would be easier for you to visualize so let's easier for you to visualize so let's look at the Brute Force solution look at the Brute Force solution so here we have one seven eleven and so here we have one seven eleven and next we have two four six okay next we have two four six okay so if we had to form pairs basically in so if we had to form pairs basically in Brute Force we will come take one two Brute Force we will come take one two one four one six right so that will one four one six right so that will get give us pair one two get give us pair one two one four one four and and one one six six now we have these pairs in the next uh now we have these pairs in the next uh step what we will do is next we'll step what we will do is next we'll take take other pairs seven to seven four seven other pairs seven to seven four seven six so now when we are taking the next six so now when we are taking the next pair that is seven to pair that is seven to and and seven four seven four and seven six and seven six and then similarly we are going to do and then similarly we are going to do with 11 so we are going to take the pair with 11 so we are going to take the pair with all of them okay with all of them okay so eleven Two Eleven four so eleven Two Eleven four and eleven and eleven six so basically we are taking each of six so basically we are taking each of the elements and uh taking period each the elements and uh taking period each of these so this would be n times n okay of these so this would be n times n okay now we also need to get the smallest one now we also need to get the smallest one right so this is how we actually form right so this is how we actually form pair now we need the smallest one so we pair now we need the smallest one so we could actually use uh could actually use uh mean hip for that one so what does mean mean hip for that one so what does mean he do is the top root will always have he do is the top root will always have the smallest value and the rest of the the smallest value and the rest of the nodes will be larger one so if we do nodes will be larger one so if we do mean hip then the minimum sum of all of mean hip then the minimum sum of all of these would be equals to what is the these would be equals to what is the three right this will have the minimum three right this will have the minimum sum so this will be at the top so sum so this will be at the top so basically we could DQ these Top Value basically we could DQ these Top Value and then we can add and then we can add to our result the pair so we would know to our result the pair so we would know that this is our result and then that this is our result and then similarly next similarly next these would be our least smallest right these would be our least smallest right so it will always be on the top so so it will always be on the top so basically we need a main Heap basically we need a main Heap I mean hip to find the minimum one okay I mean hip to find the minimum one okay so now this here we are doing n by n so now this here we are doing n by n times so now is it necessary for us to times so now is it necessary for us to do it n by n number of times to find the do it n by n number of times to find the minimum let's look at this example one minimum let's look at this example one more time so that we can optimize our more time so that we can optimize our solution so okay so here we have one and solution so okay so here we have one and two let's take the first two so the two let's take the first two so the first two will always have at least some first two will always have at least some why because these two are the least of why because these two are the least of all the elements so these two sum will all the elements so these two sum will always be the smallest so the first two always be the smallest so the first two we always take the first two and we are we always take the first two and we are adding the sum to our Q so um the sum is adding the sum to our Q so um the sum is equals to three so we are adding this to equals to three so we are adding this to our Q okay um okay let me write it this way so we actually do not even need the sum we are just going to insert these two pairs and the index of this one so I'm com taking one and two only so the index is equals to zero now next what I'll do is I'll move to this next value which is 7 and I'll only compare it with two so I'll only take the pair with the first element in the second one so one with two then seven with two so that would be seven two and the second index index of this at the second error which is zero we are only taking index 0 right and now eleven so eleven and then two and then index 0 right so now among these obviously this is the smallest one so we'll get the mean value from our mean hip because like we have already inserted this in our mean hip and compare the values okay so once the mid hip is now created what we do is next we have one and to know what we need we need to compare one with four as well right so we pop this out we enqueue this from our priority queue from our mean hit priority queue and then now we look at this Index this index is equals to zero so since this index is equals to zero which means that I'm comparing my element from the first array with the element at index 0. now I also need to compare with the next element which is 4 so I now in q1 4 and the index of 4 which is 1 okay so now that I have added to my queue now my mean hip will have this value as the minimum one okay so in the next step what happens is when I in queue these I will have the index one so this one index will be as the minimum so we have 1 4 we have one one two and one four now I will the next minimum value would either be 1 6 or it would be 7 2 right so since I found 1 4 as the minimum so next what I'm going to do is I'm going to in Cube one with the six that is the next index in the array to write its at index two so now encute this one now among the rest of the values that is these values in my priority queue which is the smallest one this is the smallest one right so I enqueue this and basically I am in Q indeed I'm adding all of these to my resulting area while I'm enqueuing those and when my resulting error length is equals to K that is when I stop in queuing because I already have the result and that is when I return my result so in summary let me summarize here once again what I have doing okay so what are we doing is first of all we always compare one to two because one two will always be the smallest one the first two elements are always smallest so the sum will always be the smallest so we take this one now we could either take these two or these two right so among these two which will be the smallest one of course it is one for right so that is why we take one foot so now that we have taken one four now the smallest one who could be either these two or these two right we already have these values so that would be either the smallest value in this and the next smallest here which is 6 because we have already taken that or the second smallest and the smallest one here so between these and these so of course here 1 and 6 is the smallest among between seven and two so that is why we take one and six so that is how we are actually doing it so let me just uh take another example here so I'm just going to make few changes to my example okay so now that we have these examples so I have one seven I'm just going to paste it over here and the next one is this one so I'll paste it over here as well so now we have these two arrays okay so how are we now going to perform our Q function okay so as we already know that the first two small are always smallest so we already have one and two now next we would take either one and 10 or 7 and 2. right so we are basically one we have one two now we are all only incrementing this index right this index and this seven and two we already have it in our list also 11 and 2 we already have it on in our list so now between these two which is the smallest one plus ten eleven seven plus two is nine so here I take seven and two so now in this case now 7 and 2 was taken so the next index would be 7 and 10 okay now between 1 and 10 and 7 and 10 which is the smallest one and ten is the smallest right so I take one and ten as the smallest one which is equals to eleven so now my next comparison would be between 1 and 11 and 7 and 10. so between 1 11 17 which is the smallest one 11 right so I'll take one eleven now since I'm done with one the index for one so in the next step now we have 17 right and now we have in the array I mean in the priority queue we already have 11 and 2 so we are actually comparing now 17 with 11 and 2 and between these two which is the smallest 11 plus 2 is equals to thirteen seven plus ten is seventeen so basically 11 and 2 right so this is how we would be performing our operation and for that we already have like inserted each of these elements which is of the first one and then now based on which element we took did we take this one if yes then now we are going to increment it we are going to take the next value and then compare that next value with the um remaining with 7 and 10 and so on so that is how we are doing because like as as we know as we could see like it only matters like in this way like one ten seven to only cross-sectional wise so that is why we are performing it in this way so now that we know how to solve this problem let's uh start coding so for that what do we need we need a mean priority queue right mean priority queue we need a list we need an array list to store our result and that's all that we are going to need so let us first create a mean priority queue so priority Q equals to um mean priority queue and then here we are going to perform our and here what we're comparing is and here what we're comparing is between the two between the two um um two elements in our list in our priority two elements in our list in our priority queue queue we take we take um some um some of a0 A1 so a0 is the first element of a0 A1 so a0 is the first element element from Norm Swan A1 is elements element from Norm Swan A1 is elements from nums two okay and from nums two okay and we need the smallest one right so b0 we need the smallest one right so b0 my plus b one so between these two we my plus b one so between these two we are going to get the smallest one the are going to get the smallest one the compare function will return as that and compare function will return as that and now we are going to push to our now we are going to push to our prior to Q so I less than numbers one prior to Q so I less than numbers one length I plus plus and then um priority q that push I mean NQ okay so we are going to enqueue into our priority queue the value add numbers at index I and nums to add index 0. so each of the element at index I I mean each of the element at norms one with and now next let us create a result and now next let us create a result array where we are going to store our array where we are going to store our result and now let us iterate over uh result and now let us iterate over uh each of the values a while K is greater each of the values a while K is greater than zero and while our mean hip mean than zero and while our mean hip mean hip which is our priority queue is not hip which is our priority queue is not empty we keep on performing our iteration so for that one now we are going to in queue I mean DQ so we need the first element is let us A2 okay that represents index of the A2 okay that represents index of the index at nums to array right index at nums to array right which is equals to prior to Q dot Q DQ which is equals to prior to Q dot Q DQ okay so now that we have the element we okay so now that we have the element we are going to insert to our result are going to insert to our result push to our result the value X comma y push to our result the value X comma y because because the priority queue will always return the priority queue will always return the smallest value from when we DQ the smallest value from when we DQ because it is a mean priority queue because it is a mean priority queue right now next what you are doing is if right now next what you are doing is if um I2 is less than um I2 is less than the last element I mean nums to that the last element I mean nums to that length minus one that is when we are actually going to know in Q2 hour mean priority queue so e n q let me just copy this thing here so we are enqueuing what we are just going to take this value only and now for the nums 2 we are going to take I2 plus 1 because we are incrementing our index for Norms 2 plus 1. so this would basically give us the comparison between like here as we uh like here as we uh we found the smallest one to write 1 2 we found the smallest one to write 1 2 means two is at index 0. so next we uh means two is at index 0. so next we uh we already have one we already have one two we had one two one two we had one two one seven seven not one seven actually so next value is not one seven actually so next value is 7 2 and the next value is 7 2 and the next value is 11 2 in our mean priority queue okay so 11 2 in our mean priority queue okay so since we already have these values we since we already have these values we decute this now we are going to insert a decute this now we are going to insert a new value so the new value the most new value so the new value the most appropriate candidate is the next Index appropriate candidate is the next Index right that is the value next to two so right that is the value next to two so that would be 1 and 10. so we are taking that would be 1 and 10. so we are taking the same value for nums one that is X the same value for nums one that is X and for y we are incrementing the index and for y we are incrementing the index by one so that's what we did here we are by one so that's what we did here we are taking X as it is and we are taking X as it is and we are incrementing norms to Pi upon index and incrementing norms to Pi upon index and that is what we are passing here and that is what we are passing here and finally we are going to also decrement finally we are going to also decrement the value of K so while K is greater the value of K so while K is greater than 0 it will run and once K is equals than 0 it will run and once K is equals to 0 we are finally going to return our to 0 we are finally going to return our result result okay so now let's try to run it all right now let's run this I need this thing here it's still giving me wrong answer undefined because and then here we are in queuing this right which is Norm's one at the index I and Norms 2 at index 0 and the index of norms 2. and then here while K is greater than zero and the priority is not empty we are dqing and then we push our X Y value and while I2 is less than nums 2 okay this would be numbers to the length because that's from indexed nums to this index represents index at norms 2 yeah great so yeah this is how we could great so yeah this is how we could approach this problem using mean approach this problem using mean priority queue priority queue um let me know in the solution in the um let me know in the solution in the comments down below what do you think comments down below what do you think about my solution yeah thank you | 2024-03-24 11:37:36 | 373 | 373. Find K Pairs with Smallest Sums | Min Priority Heap | JavaScript | LeetCode Daily Challenge |
|
eQvsVEt_j8M | uh hey hey everybody this is larry this is q4 of the recent is q4 of the recent lego daily uh sorry lego contest from lego daily uh sorry lego contest from the bi-weekly the bi-weekly uh detect cycles into the grid uh hit uh detect cycles into the grid uh hit the like button hit the subscribe and the like button hit the subscribe and join me in discord and let's go over join me in discord and let's go over this problem together this problem together um oh and you could watch me stop it um oh and you could watch me stop it live during the contest afterwards so i live during the contest afterwards so i think think this one is maybe it's not so this one is maybe it's not so interesting um interesting um but yeah for this one most of my time but yeah for this one most of my time was spent just thinking about the farm was spent just thinking about the farm uh once i uh once i figured it out i think it was okay um so figured it out i think it was okay um so i don't know how to attack this problem i don't know how to attack this problem it feels very one-off it feels very one-off uh because for me for these kind of uh because for me for these kind of problems i always try to think about how problems i always try to think about how to to um how to you know um how to you know build reusable components if you will to build reusable components if you will to kind of figure out how to kind of figure out how to learn to learn so that i can you know we learn to learn so that i can you know we use another case use another case um i think for me the biggest thing and um i think for me the biggest thing and i had a piece of paper just to figure i had a piece of paper just to figure out different cases out different cases uh and i was just thinking about maybe uh and i was just thinking about maybe different cycles of like length four and different cycles of like length four and then whatever right then whatever right and a naive breakfast or sorry now if and a naive breakfast or sorry now if that first search that first search is not going to be fast enough because is not going to be fast enough because given that uh each given that uh each side is 500 they could be up to 500 side is 500 they could be up to 500 square cells square cells uh which is 25 something 20 or 50 000 uh which is 25 something 20 or 50 000 something like that um but too big if something like that um but too big if you do uh exhaustive search right you do uh exhaustive search right um so the the way that i um so the the way that i thought about this uh during the contest thought about this uh during the contest was that was that uh well uh well because in this case we don't have to because in this case we don't have to return the length we don't have to return the length we don't have to minimize anything uh we only have to get minimize anything uh we only have to get the binary we solve true or force right the binary we solve true or force right so there's actually um so that means so there's actually um so that means that at any time that at any time you you're able to go to uh a word text you you're able to go to uh a word text that you've always seen before that you've always seen before then that means that there is a cycle then that means that there is a cycle almost like um almost like um you know the the classic linked list you know the the classic linked list with a little tail sticking out but you with a little tail sticking out but you don't care that has a tail you just don't care that has a tail you just carry that as a psycho right carry that as a psycho right and apologies for not having and apologies for not having visualization on board visualization on board uh because i don't know i have to set it uh because i don't know i have to set it up on this computer that's my fault up on this computer that's my fault but but yeah so that given that uh but but yeah so that given that uh visualization of just having like this visualization of just having like this uh you know the classic uh you know the classic cycle in the linked list uh except for cycle in the linked list uh except for in a 2d grid version in a 2d grid version uh then now you just have to uh uh then now you just have to uh check that it exists right um check that it exists right um and and the only the only and and the only the only thing that you would do if you're doing thing that you would do if you're doing naive that for search um naive that for search um is that you know there is a trivial case is that you know there is a trivial case where there's a trivial two cycles right where there's a trivial two cycles right uh a two cell cycle is just if you go uh a two cell cycle is just if you go from cell a to cell b from cell a to cell b and then back to a right like right and then back to a right like right um so the way that we prevent this is by um so the way that we prevent this is by doing something that i actually do in doing something that i actually do in trees now more and more uh because trees now more and more uh because someone taught me this at some point someone taught me this at some point actually like recently actually like recently well like in the past year uh but well like in the past year uh but is by keeping track of the parent cell is by keeping track of the parent cell and then not going back and then not going back as long as we so then now you can as long as we so then now you can imagine the imagine the recursive call of just like going down recursive call of just like going down down down and also i shall make sure that the and also i shall make sure that the recursive recursive stack is enough i guess in this case stack is enough i guess in this case they expect you to they did it for you they expect you to they did it for you uh because now i realize that i might uh because now i realize that i might have messed up if uh it gives me a have messed up if uh it gives me a recursion limit recursion limit but but yeah so now you you could look but but yeah so now you you could look at the at the you know if you if you're able to you know if you if you're able to visualize the different search visualize the different search graph um then graph um then you should be able to uh you know look you should be able to uh you know look at just at just going down the the list without going going down the the list without going back his parent and as long as you're back his parent and as long as you're able to if as soon as you find a note able to if as soon as you find a note that you've visited before that you've visited before that means there's a cycle otherwise that means there's a cycle otherwise it's just a straight line it's just a straight line uh or linked list even if you want to uh or linked list even if you want to call it that of call it that of uh you know that that would be a risky uh you know that that would be a risky path right path right and as soon as you see a note that and as soon as you see a note that you've revisited that means that you're you've revisited that means that you're already already you know being able to loop around you know being able to loop around because you don't go to your parent um because you don't go to your parent um and and in a way it it it's um it also is in a way it it it's um it also is similar to like bridge finding and stuff similar to like bridge finding and stuff like that like that so definitely it is a problem that uh so definitely it is a problem that uh comes up a bit more often comes up a bit more often on competitive programming but maybe not on competitive programming but maybe not so much to be honest on interviews so much to be honest on interviews but yeah uh so what is the the but yeah uh so what is the the complexity of this right complexity of this right well we look at each cell at most ones well we look at each cell at most ones or at most constant number of times um or at most constant number of times um because you know you go look at because you know you go look at neighbors so maybe it's like four times neighbors so maybe it's like four times the number of selves but still linear in the number of selves but still linear in the size of the the size of the grid uh being n times m so it's going to grid uh being n times m so it's going to be be o of row times columns and that's the o of row times columns and that's the space complexity as well because we keep space complexity as well because we keep a a visited matrix for that uh and visited matrix for that uh and and yeah i think that's all i have to and yeah i think that's all i have to say about this problem we'll go over the say about this problem we'll go over the code real quick code real quick uh but basically i just you know see if uh but basically i just you know see if i could start uh i could start uh a cycle from or just start a chain from a cycle from or just start a chain from a current cell a current cell uh and for every cell i well first i uh and for every cell i well first i mark it as true so that in the future mark it as true so that in the future if you come back to it then you know if you come back to it then you know there's a cycle uh this is also like how there's a cycle uh this is also like how you you this is almost uh actually now that i this is almost uh actually now that i think about it this is like think about it this is like red uh breadcrumbs in uh in um red uh breadcrumbs in uh in um in a maze or something like that right in a maze or something like that right that's like the classic greek myth or that's like the classic greek myth or something like that something like that where you know well i guess they also where you know well i guess they also tie themselves i think but if you leave tie themselves i think but if you leave breadcrumbs in a maze and as soon as you breadcrumbs in a maze and as soon as you see a breadcrumb again see a breadcrumb again you're like well uh i've been here you're like well uh i've been here before right so before right so that means that there's a cycle you've that means that there's a cycle you've made a loop uh that's basically the same made a loop uh that's basically the same idea here idea here uh you look at you know you look up down uh you look at you know you look up down left right and then you make sure that left right and then you make sure that it's within bounds you make sure that it's within bounds you make sure that the the color or the letter is the same the the color or the letter is the same so that so that that's a valid path and if it's not your that's a valid path and if it's not your parent parent and you visited before then you you just and you visited before then you you just mark it as true mark it as true if not then um you know you do the if not then um you know you do the recursive call recursive call actually i think actually i actually i think actually i quite could have terminated a little bit quite could have terminated a little bit earlier but that's okay earlier but that's okay uh well at least i got a little bit uh well at least i got a little bit lucky with time limit exceeded uh when i lucky with time limit exceeded uh when i was was solving this i definitely wasn't sure solving this i definitely wasn't sure that it was going to be fast enough to that it was going to be fast enough to be honest be honest but uh but it should have been it's just but uh but it should have been it's just that it's always unclear with v code that it's always unclear with v code sometimes with like random sometimes with like random hidden constraints uh but yeah that's hidden constraints uh but yeah that's all i have for this problem hit like all i have for this problem hit like button hit the subscribe button watch me button hit the subscribe button watch me stop the video next stop the video next and yeah bye so um this hmm hmm so hey everybody uh yeah thanks for watching the video this is probably after you watched uh the live portion of the salving during the contest uh hit the like button there's a subscribe button join my discord and i | 2024-03-21 14:10:39 | 1,559 | 1559. Detect Cycles in 2D Grid (Leetcode Hard) |
|
cfQFu_VDISI | hey what's up guys this is sean here again so uh list code number 1981 again so uh list code number 1981 minimize the difference between target minimize the difference between target and chosen elements okay and chosen elements okay so this one is pretty straightforward so this one is pretty straightforward basically you're given like i'm the basically you're given like i'm the m by n integer matrix and the integer m by n integer matrix and the integer target so your task is to choose one number for from each row right and then you got a sum for all the number you have chosen and you want to minimize the difference the absolute difference between the target and the sum right so that that's it so for example we have this matrix right so we can choose one five seven uh where the sum will be 13 right and the target is also 13 that's why the answer is zero right so for this one no we don't have any other options right that's why we have to choose these three numbers and the absolute difference is 94. okay and for this one right this one is seven right because seven minus six is one minus six is one and then we have some constraints so see we have uh we have 70 right and 70 and then the target is 800 right so since you know since the constraint is not very big we can some kind of some kind of brutal force way to solve it but we also brutal force way to solve it but we also we still need to use the dynamic we still need to use the dynamic programming programming basically you know you know like i said basically you know you know like i said since the m times and since the m times and and this one is also within 70 so what and this one is also within 70 so what does it mean it means that the total sum does it mean it means that the total sum in the end will be less than what would in the end will be less than what would be less than 70 times 70 right which is be less than 70 times 70 right which is four four thousand nine hundred right because for thousand nine hundred right because for each row each row we the biggest number is 70 right then we the biggest number is 70 right then for 70 rows that's 70 times 70 right so for 70 rows that's 70 times 70 right so basically that's the basically that's the the total the total number of different sums we can get number of different sums we can get right so which means we can simply just right so which means we can simply just use this one right as part of the state and the first one obviously should be the row right so basically we can have like 2d dynamic programming right right wait where basically the first state is the row and the second one is the sum okay right and then in the end we simply just we just need to get the minimum uh uh uh let's start coding yeah i'll explain let's start coding yeah i'll explain more more so the so the the state transition function is very the state transition function is very it's very straightforward right so like it's very straightforward right so like i said we have 2d state the first one is i said we have 2d state the first one is the row right the current row and the the row right the current row and the second one is the basically the current second one is the basically the current sum right that we have already sum right that we have already picked right then we have picked right then we have this cache right thing this cache right thing so what's the base case right so the so what's the base case right so the basic base case is this so basically basic base case is this so basically when the rows reach the end okay you when the rows reach the end okay you know what let me m is going to be the know what let me m is going to be the length of mat right so when when we have length of mat right so when when we have reached the last row right reached the last row right we just return the absolute difference we just return the absolute difference right between the sum right between the sum and the target so that's so that's the and the target so that's so that's the basic rules right and then basic rules right and then so the state transition function is like so the state transition function is like this right like um and then for num okay in math row right so for each row no we do the answer equals to minimum right of the answer dot dp of row plus one then the sum plus number okay and then we return the uh the answer right and then here we return the dp of zero and zero okay so that's how that's the the basic implementation so the way see so we have this 2db state right basically it means that you know if we could uh the reason we're using dp here is because you know we could end up with from multiple okay let's say this is the okay let's say this is the this is the path this is the path so let's say this is the the path let's so let's say this is the the path let's say we go here right and then we go say we go here right and then we go sorry sorry not here like this one this one right not here like this one this one right and then here here here let's say this and then here here here let's say this two path right two path right will end up with the same state which will end up with the same state which means that you know the numbers we're means that you know the numbers we're collecting from collecting from this one this one this one and this one this one this one this one and this one this one and this one will give us the this one and this one will give us the same sum right in this case we don't same sum right in this case we don't have to have to calculate this dp calculate this dp we don't we can only just use one after we don't we can only just use one after the path we don't have to calculate the the path we don't have to calculate the remaining parts multiple times right remaining parts multiple times right that's the that's the reason we use dp that's the that's the reason we use dp right right to to to remove the duplicate to remove the duplicate path okay path okay and and but this one would but this one would will fail tle you know will fail tle you know um i think the reason is that you know um i think the reason is that you know even though the see we have 70 so let's even though the see we have 70 so let's take a look at the time complexity for take a look at the time complexity for this one right so the dp time complexity this one right so the dp time complexity and how to analyze it analysis analyze and how to analyze it analysis analyze it is the total number of the states it is the total number of the states right right multiplied by the by the time complexity for each of the the function uh for each of the dp call right so how many states we have let's say we have n right so let's like this 70 right so we have seven we have n times sum right like i said the total sum the possible number of sums are like what is n squared right because we have already talked about that and then inside of the dp function here this one is also n right so basically it's going to be n to the power of four okay 70 to the power to the power of four um two million right two million right now for some reason this one tle now for some reason this one tle it couldn't pass so which means we need it couldn't pass so which means we need to do some to do some improvements or like work called improvements or like work called pruning right pruning right so what can we do so what can we do so first thing is that you know so first thing is that you know we can always remove the the duplicate we can always remove the the duplicate right the duplicate for each of the row right the duplicate for each of the row right so that's the first thing we can right so that's the first thing we can do do which means we can do this right for i which means we can do this right for i in range of m right in range of m right we have a match we have a match i i equals to the set we can simply do a set equals to the set we can simply do a set of the match i right so that's how we of the match i right so that's how we remove we remove the duplicate but this remove we remove the duplicate but this one's still tle and what's what's one's still tle and what's what's another thing we can do another thing we can do you know you know what we can improve is that you know we what we can improve is that you know we can sort you know because first you know can sort you know because first you know we uh all the numbers are positive right we uh all the numbers are positive right so which means that you know if the so which means that you know if the number if the sum is too big right number if the sum is too big right basically if by the time basically if by the time if by the time if by the time let's say we have a lot of rows here let's say we have a lot of rows here right so let's say we're trying to process this row right now let's see after picking this number let's say this number is four right this total sum has already exceeded the target right and then let's say for example this row also have like some 6 7 and 10 right then obviously we don't need to we don't have we don't need to try 6 any number that's greater than 4 because 4 plus the sum has already exceeded the current target right so we can simply stop that right so which means that you know in order to accomplish that we can just sort each each row so that we process from the smallest to the biggest right the moment the current sum has already exceeded target we can simply break the for loop which means we can simply break so that we don't so that we don't have so that we don't so that we don't have to try six seven and ten we can simply to try six seven and ten we can simply stay with it's four and then try the stay with it's four and then try the remainings remainings okay right so okay right so uh to sort uh we just simply need to do uh to sort uh we just simply need to do a little bit modification here which do a little bit modification here which do a sorting of that of the set right then a sorting of that of the set right then we'll have like sorted list here we'll have like sorted list here and here and here basically if the sum basically if the sum plus number right is greater than the plus number right is greater than the target okay right i think either great or equal it's fine yeah it doesn't really matter i think and then we break right so that's it so now if i run it yeah there you go right so yeah there you go right so it's not that fast but it passed okay yeah i think that's it right i mean that's the uh kind of standard dp problem with two state uh plus some pruning yeah i think that's pretty much yeah i think that's pretty much everything i want to talk about for this everything i want to talk about for this one and thank you for watching this one and thank you for watching this video guys and stay tuned video guys and stay tuned see you guys soon bye | 2024-03-25 12:46:14 | 1,981 | LeetCode 1981. Minimize the Difference Between Target and Chosen Elements |
|
qfjzaa40VzA | employee underscore ID name inquoting salary slave Shadow another inquoting salary slave Shadow another employee underscore ID salary so E2 employee underscore ID salary so E2 tables tables write an SQL query to report IDs of all write an SQL query to report IDs of all employees with missing information employees with missing information missing information entity missing information entity employee name missing Aina virtue employee name missing Aina virtue employees okay return the result table ordered by employee underscore ID and what in the ascending order two tables employee to employee to uh employee to ID second solution foreign either one yes on accounts in the Union on accounts in the Union basically foreign employee ID from where where employee employee ID not in employee employee ID from ID from salaries salaries and simple and simple again employee ID from salaries where employee ID not in select employee 80. from employee stable loan employees okay one of events is employee ID employee ID entity employee ID ascending s minus E calculations yeah accepted let's submit this foreign | 2024-03-25 13:26:26 | 1,965 | Employees With Missing Information (Leetcode 1965) in Telugu |
|
gk4qzZSmyrs | 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 number of music let's solve the problem number of music playlists this is definitely a difficult playlists this is definitely a difficult problem and I would take a couple extra problem and I would take a couple extra minutes maybe even more than that to minutes maybe even more than that to really understand it because I made a really understand it because I made a mistake in understanding the problem mistake in understanding the problem when I tried to solve it so let's go when I tried to solve it so let's go through that it's a very mathematical through that it's a very mathematical problem we're given n unique songs and problem we're given n unique songs and we want to build a playlist of this we want to build a playlist of this target length that's called goal and target length that's called goal and that's the term I'll be using as well that's the term I'll be using as well though maybe you want to use a better though maybe you want to use a better term like maybe even length would be a term like maybe even length would be a decent term to use the interesting part decent term to use the interesting part are the restrictions that we have to are the restrictions that we have to have on that playlist we have to have have on that playlist we have to have every single song included at least one every single song included at least one time so you can imagine that our goal is time so you can imagine that our goal is going to be at least greater than or going to be at least greater than or equal to the number of unique songs that equal to the number of unique songs that we have and if you read all the way at we have and if you read all the way at the bottom of the description of the the bottom of the description of the problem that is stated but this is problem that is stated but this is probably the more interesting probably the more interesting restriction and that is that a song can restriction and that is that a song can can only be played multiple times like can only be played multiple times like we can only repeat the same song If K we can only repeat the same song If K other songs have been played I think other songs have been played I think this is worded pretty poorly first of this is worded pretty poorly first of all they include the word only twice and all they include the word only twice and you don't need to do that that's you don't need to do that that's redundant the way this sounds is that if redundant the way this sounds is that if we've chosen K songs like let's say k is we've chosen K songs like let's say k is equal to two and we chose a song one and equal to two and we chose a song one and then we chose a song two that now we then we chose a song two that now we should be able to repeat any song like should be able to repeat any song like we can repeat one one one one or maybe we can repeat one one one one or maybe two two two two as long as we have at two two two two as long as we have at least K songs at the beginning that's least K songs at the beginning that's not the case this is not the case what not the case this is not the case what this is actually saying is we can only this is actually saying is we can only repeat the same song If K other songs repeat the same song If K other songs have been played meaning that if we have have been played meaning that if we have a three here now we can repeat the song a three here now we can repeat the song one because K songs have been played one because K songs have been played since we last had a one so here we could since we last had a one so here we could put a one and then after we do that we put a one and then after we do that we we can now put a 2 over here because we we can now put a 2 over here because we have that Gap here we can't put a 3 have that Gap here we can't put a 3 because there's only a gap of one we because there's only a gap of one we need a gap of two because our K is 2. so need a gap of two because our K is 2. so that's what this problem is saying that's what this problem is saying that's like the first step to actually that's like the first step to actually being able to solve it took me a long being able to solve it took me a long time to realize that now even knowing time to realize that now even knowing that this problem is still not easy but that this problem is still not easy but we can kind of start to solve it first we can kind of start to solve it first of all this first example is pretty of all this first example is pretty trivial it's not going to help you trivial it's not going to help you understand the entire problem this is understand the entire problem this is just basically permutations in this case just basically permutations in this case the K doesn't even matter because we the K doesn't even matter because we have three slots that's how I see the have three slots that's how I see the goal number like we have three slots goal number like we have three slots that we need to fill and we have exactly that we need to fill and we have exactly three unique songs so a unique song is three unique songs so a unique song is going to be included in exactly one going to be included in exactly one position so this is basically position so this is basically permutations it's three times two times permutations it's three times two times one the way I'm getting this formula is one the way I'm getting this formula is because we have three songs to choose because we have three songs to choose from so in the first position we have from so in the first position we have three songs to choose from if we already three songs to choose from if we already pick one of those songs now we have to pick one of those songs now we have to still fill in in two more unique songs still fill in in two more unique songs so how many choices do we have in this so how many choices do we have in this spot two how many choices and then would spot two how many choices and then would we have in this spot one so this is just we have in this spot one so this is just some basic math background but this is some basic math background but this is not nearly enough to solve this problem not nearly enough to solve this problem this is just permutations and that's this is just permutations and that's going to lead us to an answer of six it going to lead us to an answer of six it works for this example but it's not works for this example but it's not going to work for many of the others going to work for many of the others where our K value actually matters now where our K value actually matters now this example while it's pretty simple this example while it's pretty simple you might be scratching your head to you might be scratching your head to figure out like the algorithm to figure out like the algorithm to actually arrive at the solution so I actually arrive at the solution so I think it's a pretty decent example to go think it's a pretty decent example to go over but in this case we have three over but in this case we have three slots that we are trying to fill we have slots that we are trying to fill we have exactly two unique songs and in this exactly two unique songs and in this case the way this example is using them case the way this example is using them is basically song one and song two is basically song one and song two that's fine of course we don't actually that's fine of course we don't actually have to build the playlist We just have have to build the playlist We just have to count them and I guess I should cover to count them and I guess I should cover that we're gonna count the total number that we're gonna count the total number of possible playlists that we can create of possible playlists that we can create and we're gonna mod that number by this and we're gonna mod that number by this Prime number because it could be a very Prime number because it could be a very large result but just because we're large result but just because we're using these semantics doesn't mean we're using these semantics doesn't mean we're actually going to need an ID for each actually going to need an ID for each song we actually don't we're just going song we actually don't we're just going to count the number of songs and we're to count the number of songs and we're going to use a little bit of math to do going to use a little bit of math to do that and of course a little bit of that and of course a little bit of recursion and the reason we need to do recursion and the reason we need to do that the reason we can't just write like that the reason we can't just write like a formula like I kind of talked about a formula like I kind of talked about with the permutations is because first with the permutations is because first of all there is like this restriction of all there is like this restriction here we can in some cases repeat the here we can in some cases repeat the same song keep that in mind because it's same song keep that in mind because it's really important but also we have n really important but also we have n songs and we have to use every single songs and we have to use every single one of those at least one time that's one of those at least one time that's also going to make this problem hard also going to make this problem hard it's why it's not so easy to just write it's why it's not so easy to just write a math formula for this problem so a math formula for this problem so initially the logic is pretty simple for initially the logic is pretty simple for the first slot we can choose either one the first slot we can choose either one or two so it kind of seems like we have or two so it kind of seems like we have two choices initially and then for the two choices initially and then for the next spot we kind of have two choice is next spot we kind of have two choice is again we can either put a one or a two again we can either put a one or a two so drawing out that decision tree we'd so drawing out that decision tree we'd get this and you can see each of these get this and you can see each of these kind of does exist like one one you can kind of does exist like one one you can see is in this first playlist and one see is in this first playlist and one two that prefix is in this playlist it's two that prefix is in this playlist it's also I think in this one as well two one also I think in this one as well two one also exists here and I think here as also exists here and I think here as well two two it looks like exists here well two two it looks like exists here but now when you take it one step but now when you take it one step further we basically realize we're just further we basically realize we're just creating every single possible creating every single possible combination now the reason this doesn't combination now the reason this doesn't work is because that first thing we have work is because that first thing we have to use each song at least one time so to use each song at least one time so here when you do all of these you're here when you do all of these you're gonna end up with eight different gonna end up with eight different playlists because that's how many like playlists because that's how many like Leaf nodes we have here and you realize Leaf nodes we have here and you realize the solution is six so where did we go the solution is six so where did we go wrong like this is not straightforward wrong like this is not straightforward at all well the first thing I'm gonna do at all well the first thing I'm gonna do is I'm not not just going to count every is I'm not not just going to count every single leaf node we're going to have single leaf node we're going to have some kind of restriction or a better way some kind of restriction or a better way to put it would be within our recursion to put it would be within our recursion we're going to have some way to filter we're going to have some way to filter out some of these and the best way to out some of these and the best way to usually do that is with a base case so usually do that is with a base case so the base case that we are going to use the base case that we are going to use is first of all we expect every playlist is first of all we expect every playlist to be exactly of length 3 in this to be exactly of length 3 in this example at least so that's pretty easy example at least so that's pretty easy to do with recursion but we also expect to do with recursion but we also expect that the number of unique songs used is that the number of unique songs used is exactly equal to two in this case at exactly equal to two in this case at least or whatever the end variable least or whatever the end variable happens to be so we need to kind of keep happens to be so we need to kind of keep track of the number of unique songs that track of the number of unique songs that we use like in this path clearly we only we use like in this path clearly we only used one unique song so if we're keeping used one unique song so if we're keeping track of the number of unique songs how track of the number of unique songs how do we do that that's the number one do we do that that's the number one question and perhaps you'll be able to question and perhaps you'll be able to figure it out you can maybe even stop figure it out you can maybe even stop watching this video at this point but watching this video at this point but I'll tell you it's actually not easy to I'll tell you it's actually not easy to do even if you can make it this far the do even if you can make it this far the thing is as we choose like initially we thing is as we choose like initially we haven't chosen any songs yet so no haven't chosen any songs yet so no matter what we choose we're choosing a matter what we choose we're choosing a new song AKA a unique song I'm Gonna Be new song AKA a unique song I'm Gonna Be referring them to though as new or old referring them to though as new or old songs a new song is one we haven't songs a new song is one we haven't chosen yet and an old song is one that chosen yet and an old song is one that we already chose previously so we can we already chose previously so we can choose a new song here and a new song choose a new song here and a new song here can't really choose an old song yet here can't really choose an old song yet not just because we haven't already not just because we haven't already chosen a song so literally there aren't chosen a song so literally there aren't any old songs for us to even choose from any old songs for us to even choose from but also because we're not allowed to but also because we're not allowed to repeat an old song Until K songs have repeat an old song Until K songs have already been chosen now K is 0 in this already been chosen now K is 0 in this case so that doesn't really matter but case so that doesn't really matter but you can kind of see there are multiple you can kind of see there are multiple angles to this right like this is why angles to this right like this is why it's not a straightforward problem it's not a straightforward problem there's multiple things you have to keep there's multiple things you have to keep in mind one once we've chosen a song we in mind one once we've chosen a song we know that we need three songs like here know that we need three songs like here we needed three or or here we needed we needed three or or here we needed three actually but after we've chosen three actually but after we've chosen one like over here we need now two songs one like over here we need now two songs like my handwriting is pretty bad but I like my handwriting is pretty bad but I think this is a pretty simple point and think this is a pretty simple point and then at this level we would need one then at this level we would need one song and at this level we would need song and at this level we would need zero songs and that's how we know this zero songs and that's how we know this is a base case that part again is pretty is a base case that part again is pretty straightforward but the part where we're straightforward but the part where we're counting the number of old songs that counting the number of old songs that we've chosen so far that's how I'm gonna we've chosen so far that's how I'm gonna use this conversely you could keep track use this conversely you could keep track of the new songs that we have available of the new songs that we have available but I'm gonna do it this way so old but I'm gonna do it this way so old songs initially is gonna be zero right songs initially is gonna be zero right here we haven't chosen any songs there here we haven't chosen any songs there are zero old songs for us to choose from are zero old songs for us to choose from now at this level whether we chose a one now at this level whether we chose a one or a two the number of old songs now has or a two the number of old songs now has become one and at this point you're kind become one and at this point you're kind of realizing we're keeping track of two of realizing we're keeping track of two variables we're keeping track of the variables we're keeping track of the goal which initially is going to be E3 goal which initially is going to be E3 and we're keeping track of the number of and we're keeping track of the number of old songs which initially is zero so old songs which initially is zero so these are our actual variables in the these are our actual variables in the recursion we actually don't need to keep recursion we actually don't need to keep track of which song like that's why I'm track of which song like that's why I'm drawing this out like the ones and twos drawing this out like the ones and twos but remember when we code this up we but remember when we code this up we don't care whether we chose a one or a don't care whether we chose a one or a two we we're not going to consider any two we we're not going to consider any of these individual numbers this is what of these individual numbers this is what we actually care about over here now at we actually care about over here now at this point like at this point over here this point like at this point over here here we chose one so we can choose here we chose one so we can choose either here an old song one or we can either here an old song one or we can choose a new song too when we do choose choose a new song too when we do choose another new song then we would set our another new song then we would set our old equal to two for this part but here old equal to two for this part but here where we chose an old song old would where we chose an old song old would actually stay as one and the reason actually stay as one and the reason we're even allowed to choose an old song we're even allowed to choose an old song Here is because K is equal to zero but Here is because K is equal to zero but if K was not equal to zero suppose it if K was not equal to zero suppose it was equal to one we would still be able was equal to one we would still be able to choose an old song here but if K here to choose an old song here but if K here was actually a one we would not be able was actually a one we would not be able to choose an old song here because to choose an old song here because remember we can only choose a repeated remember we can only choose a repeated song AKA an old song If K other songs song AKA an old song If K other songs have been played since if we haven't have been played since if we haven't even played well actually we have played even played well actually we have played K songs we played exactly one song but K songs we played exactly one song but remember that K actually refers to the remember that K actually refers to the Gap like remember that sequence I was Gap like remember that sequence I was talking about one two one the Gap has to talking about one two one the Gap has to be K between the previous and the be K between the previous and the repeated old song The Gap has to be K repeated old song The Gap has to be K that's what you have to keep in mind and that's what you have to keep in mind and that's what is going to be relevant in that's what is going to be relevant in the code so firstly what we're only the code so firstly what we're only allowed to choose an old song If the allowed to choose an old song If the number of old songs is greater than k number of old songs is greater than k for the reason I just talked about for the reason I just talked about second what is the number of old songs second what is the number of old songs for us to choose from can we choose all for us to choose from can we choose all of the old songs like for example of the old songs like for example theoretically let's say old was equal to theoretically let's say old was equal to four like we've chosen four old songs four like we've chosen four old songs before perhaps the sequence would look before perhaps the sequence would look like one two three four now just because like one two three four now just because we've chosen four old songs doesn't mean we've chosen four old songs doesn't mean the next song and I'll use a different the next song and I'll use a different color doesn't mean the next song we have color doesn't mean the next song we have four choices actually we only have one four choices actually we only have one choice we can only put a one here we choice we can only put a one here we can't put a two a three or a four and can't put a two a three or a four and that actually is if our K value is equal that actually is if our K value is equal to three that's very important so I to three that's very important so I forgot to mention that K part sorry forgot to mention that K part sorry about that because here if K is equal to about that because here if K is equal to three then we have our K Gap here and three then we have our K Gap here and then we can only choose a one if our K then we can only choose a one if our K was smaller like perhaps K is equal to was smaller like perhaps K is equal to two then we'd be able to choose either two then we'd be able to choose either of these two values to go in this slot of these two values to go in this slot but the formula for this let me tell you but the formula for this let me tell you the formula first and then really the formula first and then really explain it to you is going to be the explain it to you is going to be the number of choices as we have here is number of choices as we have here is going to be exactly the number of old going to be exactly the number of old songs we've chosen the unique number of songs we've chosen the unique number of old songs we've chosen minus K now why old songs we've chosen minus K now why is that because well first of all no is that because well first of all no matter how long our sequence is like matter how long our sequence is like I've showed you some pretty simplified I've showed you some pretty simplified examples here but no matter how long our examples here but no matter how long our sequence is one two three four one two sequence is one two three four one two three four this is just one sequence we three four this is just one sequence we could possibly create others but again could possibly create others but again let's assume our K is three and here our let's assume our K is three and here our old is clearly four because we've chosen old is clearly four because we've chosen four unique songs even though we four unique songs even though we repeated some of them we repeated each repeated some of them we repeated each one exactly twice there's still four one exactly twice there's still four unique songs that we've already chosen unique songs that we've already chosen so the number of choices we'd have here so the number of choices we'd have here is going to be four minus three we can is going to be four minus three we can only choose one song and that makes only choose one song and that makes sense in the context of this example sense in the context of this example because we need at least a gap of three because we need at least a gap of three if we took that three and changed it if we took that three and changed it maybe to a two maybe to a two but we kept old as four then we'd have but we kept old as four then we'd have two choices here because a gap of two is two choices here because a gap of two is sufficient we can either put a one here sufficient we can either put a one here or we can put a two here so that's the or we can put a two here so that's the reasoning behind that and with all of reasoning behind that and with all of that said and done I'm gonna jump into that said and done I'm gonna jump into the code now and I'll explain the time the code now and I'll explain the time complexity when we get into the code I complexity when we get into the code I didn't entirely explain like a hundred didn't entirely explain like a hundred percent of the solution here but I think percent of the solution here but I think I gave you enough of the intuition that I gave you enough of the intuition that the code will actually make a lot of the code will actually make a lot of sense so first thing I'm going to do is sense so first thing I'm going to do is actually just quickly create that mod actually just quickly create that mod value because we might need it in value because we might need it in multiple spots I think in Python multiple spots I think in Python actually you don't because we can get actually you don't because we can get away with a lot and we're gonna use a DP away with a lot and we're gonna use a DP cache I'm not going to write that yet cache I'm not going to write that yet because I want to just solve this because I want to just solve this problem recursively first to just show problem recursively first to just show you that it works so remember we have you that it works so remember we have two variables we're going to keep track two variables we're going to keep track of our goal and the number of unique of our goal and the number of unique songs I think I could actually use goal songs I think I could actually use goal here but I don't want to like create a here but I don't want to like create a name conflict so I'm just going to name conflict so I'm just going to change this to current goal I think this change this to current goal I think this might be my first time using snake case might be my first time using snake case in a leak code video but I probably in a leak code video but I probably should have done it all along and the should have done it all along and the second thing we're going to keep track second thing we're going to keep track of is the number of old songs and I'll of is the number of old songs and I'll make it even more descriptive and make it even more descriptive and actually call it that now we kind of actually call it that now we kind of talked about the main base case one is talked about the main base case one is we have to use well first of all the we have to use well first of all the current goal let me show you actually current goal let me show you actually how I'm going to call this count how I'm going to call this count function first we're going to call this function first we're going to call this passing in how many songs we need which passing in how many songs we need which is what our goal is and that value is is what our goal is and that value is supplied to us here and secondly we're supplied to us here and secondly we're going to pass the number of old songs going to pass the number of old songs that we've already chosen which is that we've already chosen which is initially going to be zero and we're initially going to be zero and we're going to return the result of this going to return the result of this helper function now since we need this helper function now since we need this many songs we're gonna wait until this many songs we're gonna wait until this current goal has been decremented all current goal has been decremented all the way down to zero but that alone is the way down to zero but that alone is not enough remember one important fact not enough remember one important fact is we have to choose every single one of is we have to choose every single one of these n songs at least one time so the these n songs at least one time so the number of old unique songs has to be number of old unique songs has to be equal to n exactly and if that's the equal to n exactly and if that's the case we can return 1 because we found case we can return 1 because we found one playlist now this base case might one playlist now this base case might not make a lot of sense until I actually not make a lot of sense until I actually show you the rest of the code but it's show you the rest of the code but it's basically we have filled all of our basically we have filled all of our slots but we used more unique songs than slots but we used more unique songs than we actually needed to or that we even we actually needed to or that we even had available to us and you would think had available to us and you would think well how the heck would that ever happen well how the heck would that ever happen how would we ever use more songs than how would we ever use more songs than were available to us and not just the were available to us and not just the nature of the solution that I'm going to nature of the solution that I'm going to show you so if this is the case or even show you so if this is the case or even that old songs is greater than n then that old songs is greater than n then we've reached a base case where we did we've reached a base case where we did not create a valid playlist and we're not create a valid playlist and we're going to return zero the reason I'm going to return zero the reason I'm putting an or here is because this case putting an or here is because this case will execute first like I put this first will execute first like I put this first for a reason if both of these are true for a reason if both of these are true we return one but if this is true and we return one but if this is true and this is not true then we want to return this is not true then we want to return zero that's what this part of the zero that's what this part of the condition is for and can and the other condition is for and can and the other part here if old songs is ever greater part here if old songs is ever greater than n of course we can't like that than n of course we can't like that that's just not a playlist that we were that's just not a playlist that we were trying to build so we would ignore that trying to build so we would ignore that as well now here's the part where we as well now here's the part where we have our actual choices we have two have our actual choices we have two choices either choose a new song or choices either choose a new song or choose an old song the new song case is choose an old song the new song case is a bit more simple so I'll start with a bit more simple so I'll start with that we're gonna recursively when we that we're gonna recursively when we choose a new song our goal is going to choose a new song our goal is going to be decremented by one because we filled be decremented by one because we filled one of the slots anytime we choose a one of the slots anytime we choose a song we have just filled a slot so we song we have just filled a slot so we can go ahead and say current goal minus can go ahead and say current goal minus one is going to be the new current goal one is going to be the new current goal that's a new sub problem and if we chose that's a new sub problem and if we chose a new song then the number of old songs a new song then the number of old songs has clearly just increased by one so old has clearly just increased by one so old songs plus one the number of unique old songs plus one the number of unique old songs has just increased by one now songs has just increased by one now there's only a finite number of times we there's only a finite number of times we can choose a new song long and that's can choose a new song long and that's why we have this base case that will why we have this base case that will return zero if we ever exceeded that return zero if we ever exceeded that threshold this is the sub problem but threshold this is the sub problem but how many new songs do we actually have how many new songs do we actually have available to us because that's what we available to us because that's what we should multiply this result by like this should multiply this result by like this is the sub problem but how many new is the sub problem but how many new songs do we have that's what we need songs do we have that's what we need here and that's going to be n here minus here and that's going to be n here minus the number of old songs I think that's the number of old songs I think that's just a little bit of math so once we just a little bit of math so once we have that we're going to store it in a have that we're going to store it in a variable and it's possible that this variable and it's possible that this could end up being zero because of this could end up being zero because of this base case now we can also choose an old base case now we can also choose an old song but remember we can't always choose song but remember we can't always choose an old song we can only do that if we've an old song we can only do that if we've chosen at least K songs in total or chosen at least K songs in total or probably more than K actually that's why probably more than K actually that's why I'm putting this condition old songs has I'm putting this condition old songs has to be greater than K because the Gap has to be greater than K because the Gap has to be at least K if we haven't even to be at least K if we haven't even chosen K songs how can the Gap possibly chosen K songs how can the Gap possibly be okay so that's why we have this be okay so that's why we have this conditional that's protecting this uh conditional that's protecting this uh recursive case where we now choose an recursive case where we now choose an old song so let's start with the old song so let's start with the recursion what's that going to look like recursion what's that going to look like the easy part is that our current goal the easy part is that our current goal is once again going to be decremented by is once again going to be decremented by one because we just filled a slot one because we just filled a slot secondly the number of old songs is secondly the number of old songs is actually going to stay the exact same actually going to stay the exact same because we just chose an old song so the because we just chose an old song so the number of unique old songs we've chosen number of unique old songs we've chosen should not be incremented it's only should not be incremented it's only incremented when we choose a new song incremented when we choose a new song I'm still not sure if I should have I'm still not sure if I should have named this variable new songs if that named this variable new songs if that makes more sense for you feel free to do makes more sense for you feel free to do that but I think old songs is more clear that but I think old songs is more clear and it is more even more clear here in and it is more even more clear here in this equation that we're about to do this equation that we're about to do because when we choose an old song what because when we choose an old song what is the number of old songs that we have is the number of old songs that we have to choose from well that's pretty simple to choose from well that's pretty simple it's just going to be uh old songs the it's just going to be uh old songs the variable that we have but remember also variable that we have but remember also that we need that Gap to be at least K that we need that Gap to be at least K just be because we have all this many just be because we have all this many old songs available doesn't mean we can old songs available doesn't mean we can choose all of them we need the Gap to be choose all of them we need the Gap to be at least K and this is the formula we at least K and this is the formula we came up with in the drawing explanation came up with in the drawing explanation old songs minus K if K happens to be old songs minus K if K happens to be zero then we can choose all of the old zero then we can choose all of the old songs if it happens to be one then we songs if it happens to be one then we have to skip at least one of those have to skip at least one of those that's the idea here and what are we that's the idea here and what are we gonna do with this value well we're gonna do with this value well we're going to increment it we're going to going to increment it we're going to take it and add it to the result like take it and add it to the result like this now I haven't really been using the this now I haven't really been using the mod and that's because in Python mod and that's because in Python integers are like infinitely large so we integers are like infinitely large so we can actually get away with it but if can actually get away with it but if you're using a different language you you're using a different language you probably want to put a Mod over here probably want to put a Mod over here where we initialize the result and also where we initialize the result and also you probably want to put a Mod here you probably want to put a Mod here where we take this value which might be where we take this value which might be really really big and then after you've really really big and then after you've modded like this part by this you modded like this part by this you probably also then would want to say a probably also then would want to say a result is equal to result modded by that result is equal to result modded by that prime number up above but we actually prime number up above but we actually don't need to do that in Python here we don't need to do that in Python here we could just say return result mod and could just say return result mod and just like that and I'll run this I'm not just like that and I'll run this I'm not going to submit it I'm going to run it going to submit it I'm going to run it to make sure that it works on the first to make sure that it works on the first few cases and Below you can see that it few cases and Below you can see that it does and we're going to get time limit does and we're going to get time limit exceeded if we try to submit it so now exceeded if we try to submit it so now I'm going to go ahead and add caching I'm going to go ahead and add caching you can see that we have two variables you can see that we have two variables here there's no Loops or anything like here there's no Loops or anything like that within our recursion So in theory that within our recursion So in theory this should execute a total of the this should execute a total of the number of goal multiplied by the number number of goal multiplied by the number of songs so that's going to be the of songs so that's going to be the overall time complexity it's going to be overall time complexity it's going to be n times goal that's also going to be the n times goal that's also going to be the space complexity because we're going to space complexity because we're going to have a cache that I'm going to use a have a cache that I'm going to use a hash map for you could also use a hash map for you could also use a two-dimensional array so here caching is two-dimensional array so here caching is pretty easy to add here we'll check if pretty easy to add here we'll check if this is a case that we've already this is a case that we've already executed before of this combination is executed before of this combination is already in our DP cache I'm going to go already in our DP cache I'm going to go ahead and return it this is probably the ahead and return it this is probably the bad part of having to descriptive bad part of having to descriptive variable names because we have to type variable names because we have to type them all out like this so old songs and them all out like this so old songs and we can only return a cached value if we we can only return a cached value if we actually cached it in the first place so actually cached it in the first place so here I'm going to go ahead and cache it here I'm going to go ahead and cache it like this and I'm going to set that to like this and I'm going to set that to this over here and then I'll go ahead this over here and then I'll go ahead and just return this value over here so and just return this value over here so as long as we did that correctly it as long as we did that correctly it should work I'll go ahead and submit it should work I'll go ahead and submit it and as you can see on the left yes it and as you can see on the left yes it does and it's pretty efficient if you does and it's pretty efficient if you found this helpful please like And found this helpful please like And subscribe if you're praying for coding subscribe if you're praying for coding interviews check out neatcode.io it has interviews check out neatcode.io it has a ton of free resources to help you a ton of free resources to help you prepare thanks for watching and I'll see prepare thanks for watching and I'll see you soon | 2024-03-25 11:02:17 | 920 | Number of Music Playlists - Leetcode 920 - Python |