id
int64
1
2k
content
stringlengths
272
88.9k
title
stringlengths
3
77
title_slug
stringlengths
3
79
question_content
stringlengths
230
5k
question_hints
stringclasses
695 values
tag
stringclasses
618 values
level
stringclasses
3 values
similar_question_ids
stringclasses
822 values
503
what's up guys then quite here now I'm not ready to install I check the description for all the stuff I do tech and coding stuff on Twitter Newton blah whatever we're doing Lee code join the discord and check out patreon for premium problems if that's what you're interested in you know so this is you know next greater element to this is we just did next greater element one please watch that before you watch this I do not want to you know explain it you know that much but if you did see that we'd use the hash map to solve this problem last time and we're not going to be doing that this time we don't need to last time we have two arrays this time we have one only differences we're basically what you do is you will go through the array and for each number you find the next greater number so you see one the next greater number is two so we put two there is no next greater number because two is the highest so you put negative one if there's nothing if it doesn't exist put negative one the toys Don this is normally you're looking to the right for the next greater number in this one you're allowed to be go to the right or left so you are you know it's actually circular or not right or left sorry about that it's circular meaning you if I'm at this one after the last index it goes right to one give it a circular array you see the next element of the last element is the first element in the array print the next greater element for every element so yeah basically how do we solve this I mean it's not too bad I mean you know all we have to do is you know find the next greater element so how do we do this well literally all we have to do is just I don't know if you guys saw rotate or see if a string is within another strings rotation but if we want to find you know a e i o you in see if we wanted to see if this string is within a io u a if we wanted to see if this string is a rotation of this string all we have to do is duplicate it so we just have to at or you know to add the same shirring onto the end of and then we could just look through the whole string and find it that was a problem we did called likes I don't know what it was called but if it was in the you know the addition of the two strings like we'd be able to find it similar concept here we're gonna extend as if the input array is in we're just gonna ask pretend like it's like this almost like we're dealing with you know an extra array of the same thing on the end and then we want to just find the next greater element of one we just keep going through the array and then oh look it's two right there you know so that's the whole thing you just kind of like extend the array with a extended for loop we don't need a hashmap because we're gonna be indexing or stack we literally have to do that so let's just get started I'll explain it as we go so n is equal to num length we're gonna have our output array equal to new and this is gonna serve as a similar to our hash map I mean you can use a chef if you want it's just gonna be a waste of space you don't need to right now so we have our output array we're setting up and then we're gonna have that stack like I mentioned and this is gonna hold the index the indices of the elements rather than the actual elements this time so we'll go through an example at the end we reverse tack set up here and if since if there's nothing if it doesn't exist we output negative 1 we're just gonna initially fill our output array with negative ones because we're gonna be filling it with the next greater values so if there are none it'll just be negative 1 by default which is perfect honestly so what are we gonna do well we're gonna loop we're going to loop to n times 2 that's the length of the array x 2 less than the array x 2 which will that means we're extending the array to 2 times the length now how are we going to make sure that we're hitting all these elements we're not adding on to this array like it's still the same array so what we have to do is we have to well we're gonna be pushing things onto the stack don't push I yeah that's fine and what we're gonna be doing here is we're gonna say okay if stack is not empty and numbs since the stack is gonna be filled with indices and stacked nums of stack dot peak is less than numbs of I mod n then what we're going to be doing is we're gonna say output array of know of stack uh pop the Enda C is equal to num of I mod n okay I'll explain this right now okay so let's run this and make sure that it's working correctly and it's not working correctly because we're not doing a while loop my bad remember the while loop like last time there we go okay perfect so let's explain this so while we're looping to n by 2 just like I explained earlier we want to loop the array twice so for example in this example we're gonna be looping and we're putting the indices onto the stack so the stacks filled with the indices so if I lost a none we're just doing a casual loop through this alright we're gonna say ok if 1 is less than n meaning that we haven't reached the end of the array we're gonna put that onto the stack so the stack has one right so and then we're gonna do a check ok we're gonna say ok same as the last video if you watch that if one is less than if nums of we're putting the indices of one on it or though we're putting stack top push to 0 you know so we're gonna be putting a 0 on to the stack we're gonna say if nums of 0 is less than nums of i mod n which is gonna be 2 in this case we're going or it's gonna be 1 numbers of 1 if 1 is less than 2 then yet our output array of 0 is equal to 2 so that's what it does it makes the index equal to you know the current value that we're looking this is the current value this is what's on the stack and then for two it's gonna say okay we put then we put two onto the stack or we don't put two on the stack we put want the index for a two which is one onto the stack and then we're gonna say okay is nums of one which is two less than you know the next element which was one the current element which is one no it's not so we just skip over it and nothing happens then we put one onto the stack or three are two onto the step index 2 for element 1 onto the stack and we say okay is you know nums of you know stack dot peak less than numbers of I'm on 10 so here's the part where you just need to know this is it goes we have these indices for these two onto the stack and we haven't found greater elements for them yet but we continue to loop even after we've looped through the initial first three elements of this array onto a dupe onto the same duplicate array basically afterwards because we're just using I mod n so if it goes over n elements we just continue going and it's like we traverse the array twice almost so we just keep going and then you know you chit 1 is at the peak of the stack the index for 1 so you just keep checking one and versus you know one that's not it and then you get to 2 and you're like oh we did find something in the second loop over the array that is greater than 1 so you set the index for 1 to output array of 2 equal to 2 so you know I know it's kind of you know with all these the words I'm saying it's kind of hard to explain with all the modulus and stuff but you're just using an index stack you're putting indexes in instead because you're using you're going to end by 2 elements to loop through twice and if you just use I mod N for indices then you can go through twice and it makes it a lot easier you know hopefully that makes sense you guys I know this was a pretty crap so X the nation it's just it's hard to it's kind of almost math so it's kind of a little bit hard to explain this one specifically especially with the indices and you know I'm trying to say you know one is zero the zero in to see if these are different numbers it might have been easier but sorry about that basically just index tack look into it a little more let me know if you have questions maybe we could get on a discord call if everyone doesn't understand if I was just speaking gibberish let me know if I was speaking gibberish or if this made sense so yeah thanks for watching and see us next time
Next Greater Element II
next-greater-element-ii
Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`. The **next greater number** of a number `x` is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return `-1` for this number. **Example 1:** **Input:** nums = \[1,2,1\] **Output:** \[2,-1,2\] Explanation: The first 1's next greater number is 2; The number 2 can't find next greater number. The second 1's next greater number needs to search circularly, which is also 2. **Example 2:** **Input:** nums = \[1,2,3,4,3\] **Output:** \[2,3,4,-1,4\] **Constraints:** * `1 <= nums.length <= 104` * `-109 <= nums[i] <= 109`
null
Array,Stack,Monotonic Stack
Medium
496,556
326
Hello friends so in today's video let's all read code daily challenge problem which is power 3 so we are given integer n and we need to return true if it is a power of 3 otherwise we would return false so this is again a very simple problem what we are given a number n and we need to check if it is a power of any power of 3 or not so first and foremost thing is that uh if the other powers of any number can cannot be negative and 0 right so for negative and 0 given input we would directly return false from here and otherwise how would we check if it is a num if number is a power of three see I can take logarithm both sides so log n would be log so this is base 3 okay so this is base three and this is 3 power x so that means my X is uh logarithm of n base 3 which could be also written as logarithm of n base 10. divide by logarithm of 3 base 10 correct how see this is a standard logarithm property which you uh which we should all definitely know it so what I said logarithm of n base X could be written as logarithm of n base 10 divided by logarithm of X base 10 correct so this is a standard property of logarithm so now just what we need to check then see if we need to just check that if logarithm of n b is 10 and logarithm of n logarithm of 3 base 10 see if it results in an integer then we are sure that this number is a power of 3 okay so this is a simple deduction from that so if n is equal to 3 power x then we take logarithm both sides bs3 then X would be this right then now this could be written as log n base log 3. base 10 is equal to X so now if this value left side value is an integer that means that the number was a power of 3 correct so now let's directly code it and here it is up so the first case if n is less than or equal to 0 then we would directly return of false from that else what we would check we can have uh yeah we need to have double right because logarithm could be in decimals also the logarithm of 10 of 9 and divided by logarithm of 10 base log 3 of base 10 okay so if my answer equal to when I cast it to an integer if it this is the case then I would return a true else I would return false correct so we'll just see the simple simulation of what I explained to you let me check it if it is working yes so it has passed all of the test cases and we have solve the religion problem so if you like this uh solution then you do not forget to like And subscribe the channel for such content thank you
Power of Three
power-of-three
Given an integer `n`, return _`true` if it is a power of three. Otherwise, return `false`_. An integer `n` is a power of three, if there exists an integer `x` such that `n == 3x`. **Example 1:** **Input:** n = 27 **Output:** true **Explanation:** 27 = 33 **Example 2:** **Input:** n = 0 **Output:** false **Explanation:** There is no x where 3x = 0. **Example 3:** **Input:** n = -1 **Output:** false **Explanation:** There is no x where 3x = (-1). **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Recursion
Easy
231,342,1889
1,463
it has been asked by flip cart Amazon and Google hi guys good morning welcome back to the new video in this we're going to see the problem cherry pick two Cherry pickup to but although it is marked as a hard problem but we will relate it with a medium and a medium like medium and a medium easy problem and then from that it will be very easy for you let's start off what the problem says the problem simply says that we are given a rows cross columns Matrix which means a m cross n Matrix called as grid and it represents the field of cherries where grid of I comma J represents the number of cherries that you can collect from I comma J cell okay so every cell of that Matrix has some number of cherries and you can collect those cherries now you have two robots that can collect cherries for you robot one it starts off from the top left corner which is 0 comma 0 because if you have a matrix this is a top left corner which is 0 comma 0 and robot two starts from the top right corner which is 0a n minus1 if the columns are n so you can say n minus one is the number of columns now uh we have to return again both the robots will keep on moving and again make sure that both robots should reach the super end of the grid any of the robots cannot stop at every time every robot will go one level down and they have saying or they are saying that what is they have said that um a robot if it is at a cell I comma J then the possible options for him to me to move at the next iteration is I + 1 comma j minus1 i next iteration is I + 1 comma j minus1 i next iteration is I + 1 comma j minus1 i + 1 comma j i + 1 comma J +1 or you can + 1 comma j i + 1 comma J +1 or you can + 1 comma j i + 1 comma J +1 or you can indirectly say that if I have a grid a robot is let's say at this specific cell I comma J then in the in this step he will have to go on to the next cell which is I + 1 I + 1 I + 1 so for sure which is I + 1 I + 1 I + 1 so for sure which is I + 1 I + 1 I + 1 so for sure he has to go on Next Step which is I +1 he has to go on Next Step which is I +1 he has to go on Next Step which is I +1 which is the next row he has to go on and for the next column he has three options either if he is at the column J he can remain at the column J as you can see he can remain at the column J he can go to column J minus one or he can go to column J + 1 J + 1 so we he can go to column J + 1 J + 1 so we he can go to column J + 1 J + 1 so we can easily visualize that if I am at this specific cell I can go to this and this just next left cell next right cell next down cell and all of them should be one step down to me and we have to ultimately return the maximum number of cherries which we can collect we as in two robots combined can collect for us maximum number of cherries and also just say that when any robot picks and pass through a cherry it picks all the cherries and the cell becomes a zero which means he'll just pick off all the cherries which means um you can pick a cherry exactly once that's what it means uh next thing is very important when a r when both the robots stay in the same cell only one takes that cherries for it is very obvious that okay both the robots are kind of moving like this down left down and all that stuff so for sure there will be a point let's say here it comes then here it comes here and it comes here so for sure there can be a point where both the robots can Collide and again both the robots are smart and you know that if at this speciic cell I had four cherries so only like in total combine can someone can pick only four cherries because I have at Max four cherries so this says one thing that if you have four cherries you can only take in four cherries that's it and ultimately you are not concerned about what robot one takes what robot two takes ultimately you concerned about what again both the robots are your robots so we just want maximum number of cherries to be picked not considering what robot one will pick or what robot two will pick that's it make sure this will confuse many of you that you will be concerned about okay what I should make robot one big n don't think about that terms because we maximum number of cherries and both are your robots that's it last is that for sure robots cannot move outside the grid and last as robot could reach the bottom of the grid only then I say okay now I should say what all have my robots grabbed so you can for sure see with this specific example this is robot one which is in green robot two which is in blue so he will make like this down then right and then down this is what Rob robot one will collect robot two will collect like this so in total robot gave me 24 as my number of cheres now considering that we had two robots here let's forget that for now we consider that if you had only one robot and if I would have asked you imagine like okay just imagine you have only one robot and everything remains exactly same but the operations required are from I comma J you can move to I + 1 from I comma J you can move to I + 1 from I comma J you can move to I + 1 comma J + 1 I + 1 comma j i +1 Jus one comma J + 1 I + 1 comma j i +1 Jus one comma J + 1 I + 1 comma j i +1 Jus one and also to Super End you have to what one again remember you have only one robot because we have to break the problem down to what we have seen earlier what problem we have seen earlier here so we'll just simply say Okay Aran um I cannot try greedy uh because for sure if I might end up trying greedy which means let's say if I have a three here Al I could have moved to a five here but let's say I don't move to a five because greedily greedy thinking I would have moved to a five let's say but okay let's change the value let's say here is a five it is a two right now from this two let's say this value would have been a very Big Value which is 15 that's it so it is more than sufficient to prove that greedy would not work would have been H here so greedy would have been one you could have moved here so this having a score 3 5 1 and two if you would have not gone greedily and would have tried for all the possib 2 two 15 and then 2 one for sure in future if I get some big value that's not sure so I have to try for all the possibilities so one thing is for sure that I cannot go greedily in these kind of problems and I have to try on for all the possibilities now to try on for all the possibilities just simple try on for all the possibilities initially my robot again remember I have only one robot my robot was at the cell 0 he has three options he can go like this and like this which means left down right down so again left down we cannot move because it is out of the RO that we can handle with some if conditions that okay if your cell I comma J all that stuff um if it goes out of bound just simply make sure that you return something but that we can handle in the edge cases and stuff but the actual case okay here or here so he will have two options again we will plot both the options differently one option was landing at the cell right here other option was Landing the cell right here which is one comma one now again he has three options you can again whenever I say he land onto a cell remember this cell so what all Chang he might had he at that location he his result and remember he has to maximize his res cherries so again and try Okay children I will go to my next C + one again I have written DFS or C + one again I have written DFS or C + one again I have written DFS or solve so it is simply saying okay I will try recursion but what I'll try with my recursion I'll go on to my next cell which is IP go on and try for all the possible columns as you have remembered my columns are three possibilities one I will Trav for all these three values for my column for this specific i+ one row this specific i+ one row this specific i+ one row and what some Maximum I would get from my recogition I will simply add in my current answer so that is how I can simply get maximum number of cherries now simply let's dry much more further but yeah that is how our answer would look like or our code would look like for one robot remember now if you were at this specific cell again you have two options although you had three options which is left also but you cannot go left so you know that you will have only two options so he will go on 2 comma 0 and 2A 1 and same way uh if you at 1A 1 you have three options either this cell or this cell so you will go on to 2 comma 0 2A 1 and 2A 2 now again if you had seen so far is so you will simply add while watch out for like obviously you were at 0a 0 now you would have asked for 1 comma all these possible J values as you can see 1 comma 0 and 1A 1 you would have asked for although you would have asked for butus one would never as a column uh like will occur so you would have try for 0 1 as you can see 0 comma like 0 and 1 you would have tried for it which means 1 comma 0 and 1A 1 you would have tried for uh when you will try for something then you again it will go on and count for its own recursion then you will simply add its corresponding cell values which means you will call you will count grid of 1 comma 0 and then again call for recursion again you in the other case you can have grid of 1 one and again call for recursion can see simply this will also count and this will again call for recursion all that stuff so you can see you are calling for recursion with the same cell and 2 comma 1 or 2 comma 1 oh and again the same tree will be made for this specific cell in this specific cell same as the tree will be made for this cell and this cell so you know in one robot itself I know to find the maximum number of cherries I will have repeating sub problems so for sure I will have to apply or do the memorise with my DP that is for sure and we are using two robots so for sure two robots is much more complex than one robot then we will again have repeating problem so we will always make sure that we will apply memorization in that two robots also but we have we got a glance of how the problem or how the answer would look like now coming on back to a main problem when we had two robots now make sure one thing that both the robots coinci said please take only that number of cherries which means only one robot will take the cherries other robot will go empty-handed so make sure robot will go empty-handed so make sure robot will go empty-handed so make sure that part now we'll start off with the same problem again because of one robot now we have a background of how the recursion Tre will look like we know for sure that we have to apply DP and we know that okay how the base cases and stuff will look like and probably we also know that how the recursive State because if you gone if you have gone back it is simple you will add simply grid of I comma J and then you will try on for all the possible values like same recursive next row and then possible J values you will try on the same way we will do in for two same way we'll do in for two robots now we have a robot one and robot two now simply go on and try for so you will see robot one if I bifurcate down which means let's say if I bifurcate and imagine robot one will Mo robot two will move individually so robot one would have been there it would have gone to the below cell or the below right cell okay below cell is here below right cell is here and for same for robo two it would have gone to below left cell and Below down cell so this is below left cell this is below down cell now again uh the same way Arian Aran hold on you took one robot where did the other robot go in a grid two robots should be there where did you miss where is the robot one here ah so that is we are doing something wrong we have to put in both the robot possibilities so you know that robot can move either robot one can move either down or down right robot two can move either down or down left so I can say that if I have to move one possibility so one possibility can be robot one again one possibility can be robot one moved down and robot two moved down left another possibility can be robot one moved down robot to move down itself other possibility can be robot one move down right robot two move down left other possibility can be robot two robot one moved down right robot two moved down so that can be the four possibilities but Arian how we would know we had four possibilities see as simple as that uh first robot will have three options to move on second robot will again have three options to move on right if he has three options so for sure if some I comma J is here I will see corresponding I will have three options for my robot 2 for this also I have three options for my robot 2 so for three options for robot one movement I have three corresponding options for robot two movement in total I will have nine options for my robot one robot two movement that's it you can see although you had only four options why is that because this got because of it was out of my Matrix but it is simple robot one had two movements two possible movements robot two had two possible movements so in total I have four possible movements and that is how it will look like that robot one robot two here and that's how again if you remember in the very basic example we knew that we had these three possible movements at every step which means in my recursion tree I will have three childrens at Max now in my new recursion tree I will have nine childrens at Max right now let's simply see how you will write the code for it exactly same so you saw that earlier for the simple recursion if you had gone back uh just let's let quickly go back in the simple you had only I and J that was more than sufficient for you because you had only one robot but as you have now two robots so you will have robot 1 I Robot 1 J robot 2 I and robot 2J now you can simply go and apply your simple recursion but if you again I have not even written the code but with seeing this recursive State itself and I know I will have to memorize my ING itself because in the above smaller example we saw that you have to memorize in because you have a repeating sub problem of in as said then for sure I will have to memorize R1 i r R1 J and R2 I and R2 J so for sure if I have to memorize this which means for sure hands down my time complexity will at least be n into M sorry M into n let's say m is the number of rows and N is number of columns multiplied by m into n so m into n whole squ or I can say m² into n sare will for sure be time complexity it can be more depending upon if we apply some more Loops inside this recursion but it will for sure be this so can we optimize it right here right now can we optimize it yeah we can how because you will see how like firstly how you even think of memorizing or basically improving something which means you have to right now memor like you have to right now optimize it if you have to optimize something right now you will see okay can I reduce this which means if you want to reduce this you will have to reduce the states or basically either you reduce this States right here or you can take these states but the memorized state which means the states which you will actually memorize you will have to reduce those so uh can we figure out a pattern oh yeah if you remember word there was a very stressful thing in the beginning I told as in like I give a stress in that thing uh it was that at every step you are going on to next row which means for both the robots their row will be same for both the robots their R1 I and R2 I will be same both the robots will be at the same row at every step that is the thing which we can utilize to remove one of the robot eyes and thus we will remove one of the M from the entire thing this means one row factor in a time and space both have been reduced because of this small optimization which we have done right here so instead of robot one I Robot 2 I will just only keep I itself because I know both robot one and robot two will have the same I and then I will have robot 1 G because it can be different and robot 2G now a simple base cases as we can simply see that I my robot should not go out of my Matrix and if it going out of my Matrix I have to return something now to return what defines that ultimately my answer wants what my answer wants maximum number of cherries now if something has gone zero so something of my Matrix out of my grid I will return number of cherries for him to add because I want in my answer to add maximum number of cherries so ultimately maximum which means if something is out of my Matrix or out of my GD or basically invalid simply return zero because it will not impact my answer thus if I have reached the Super End which means my I has gone out of the grid then simply return a zero or if my J has out gone out of the grid simply return a zero that's a simple basic which you can have now that was case but how's the actual case going on if you remembered in the above case if you remember in the above case we simply added the grid of I comma J because we imagine we had only one robot and that will actually uh we will add the number of cherries in that specific robot but here we have two robots so for sure for the first robot I will add the number of cherries which means grid of I comma R1 r1j for the second robot also I will have to add the number of cherries again I remembered that both will be on the same row but can be on the different column so R2 J I will add the corresponding number of cherries in my result in my final number of cherries maximum of cherries which I can have in my answer that I will add that is okay but if you remember there was one condition I again stressed on very much what was that it was the condition that one robots when only one can take the number of cherries so I can add a simple condition in this is that if again I know the I is always same so to make sure the robots are not on the same cell I will make sure if my r1j is not equals to my r2j which means both the robots are on the different s only you should add their corresp like you should like actually add the uh R2 J corresponding cell number of cherries also in your result if they are on the same cell you have already counted please don't count that cherry again because in from one side you can take only number of that number of cherries so that will be our actual case but I where's the regive where's the recursive code gone no worries uh you can actually again this is the cherries which you have gotten from the current cell but as a recursion you will go and ask for the maximum number of cherries which you can get from the children and if you have remembered we will get at Max nine children so I will go and ask for solve of I + one but now my X and Y will be of I + one but now my X and Y will be of I + one but now my X and Y will be there again if you had remember our base case was like our actual case was R1 J and r2j saying okay the corresponding column of robot one and the corresponding column for robot two so X my corresponding column for robot one it can either again if you remember he can either go to R1 J minus1 R1 J R2 J sorry R1 J + 1 and same for robo 2 he J sorry R1 J + 1 and same for robo 2 he J sorry R1 J + 1 and same for robo 2 he can move to R2 J minus 1 R2 J and R2 J + can move to R2 J minus 1 R2 J and R2 J + can move to R2 J minus 1 R2 J and R2 J + 1 but if you remember I have to move both the robots one robot two so my one possibility can be R1 J minus one R2 J R r2j minus one next possibility can be R1 jus1 r2j next possibility can be R1 jus1 R2 J +1 next possibility can be R1 J R2 J +1 next possibility can be R1 J R2 J +1 next possibility can be R1 J comma R2 J minus1 next possibility can be R1 J comma r2j next Poss can be R1 G R2 G+ this is how nine possible pairs I R2 G+ this is how nine possible pairs I R2 G+ this is how nine possible pairs I can form which means at every level for every cell I will have nine possible pirs and out of all of them I want the maximum Cherry sum which my child can give me I will get that specific Cherry sum same which we did for one robot in one robot we just have three options and from that we grabbing the maximum uh Cherry here we have nine we just grab the maximum Cherry from it and then we can simply add that maximum Cherry in our this specific result see the code it's pretty simple let's see the recursive code exactly same that firstly we will have our I we will have our R1 J and we will have our R2 J very beginning if you remember you will start your robot one from cell 0 comma 0 and you will start your robot two from cell 0a n minus one this is the this is showing the starting set so I've named I as I itself this is my r1j robot 1 J and this is my robot 2 J now simple base cases if anything goes out of my Matrix simply return a zero now if remembered if I am at a specific row then simply count the corresponding number of a cherries which you can have so for this specific I comma r1g I will add the corresponding number of cherries and I'll also make sure if my r1j is not equal to r2j which means both the cells are different I will simply add the I comma r2j number of cherries also to my result but this is the simple result you have to go and ask the recursion for the maximum answer maximum number of cherries which you can get in from the sub problems as in from a child so I'll go and try for all the possibility as I have showed we have nine possible options starting from R1 J minus1 to R1 J +1 which means R1 J minus1 to R1 J +1 which means R1 J minus1 to R1 J +1 which means r1j minus1 r1j and R1 +1 same for r2g r1j minus1 r1j and R1 +1 same for r2g r1j minus1 r1j and R1 +1 same for r2g minus1 r2g and r2g + one I will form minus1 r2g and r2g + one I will form minus1 r2g and r2g + one I will form nine possible combinations and I will just go and ask maximum for the next row what's the maximum I can get okay get that maximum which means improvise that keep on improvising that maximum value and keep on going and asking your recursion to solve it for the next row with this specific X and Y cell again these can be the nine possible options and with this I will simply again in the existing result whatsoever my child has given me I will add that in my result and can simply return my result but we know it's a simple recursion and we know that we can actually memorize it so we'll just simply add two lines of code we will initialize are DP again the memorization Vector I name as Nam it as a DP and I initialized my DP saying DP is nothing but of size m n and n this is for I this is for r1j and this is for r2j this is how I initialize my DP the default value of minus one and then while checking while going on inside my I just checked okay if I R1 G r2j if it's notus one simply return that value and before just returning Please assign this value with this you can easily see that my time compy has reduced to n sorry m n and this is O this is the nth so you can Al you can say my time complexity is actually o of M into n² into 9 but 9 is a con Factor so you can actually remove it so this is your time complexity and the same way your space is also o of M into n² again remember the fact that you have optimized the space by a factor of n while generating this answer itself although that will also pass which means n sare to n sare will also pass but still you optim that and ultimately you have reached to that M into n whole Square as both time and space and that's why you can simply solve it cool thanks goodbye take care bye-bye
Cherry Pickup II
the-k-weakest-rows-in-a-matrix
You are given a `rows x cols` matrix `grid` representing a field of cherries where `grid[i][j]` represents the number of cherries that you can collect from the `(i, j)` cell. You have two robots that can collect cherries for you: * **Robot #1** is located at the **top-left corner** `(0, 0)`, and * **Robot #2** is located at the **top-right corner** `(0, cols - 1)`. Return _the maximum number of cherries collection using both robots by following the rules below_: * From a cell `(i, j)`, robots can move to cell `(i + 1, j - 1)`, `(i + 1, j)`, or `(i + 1, j + 1)`. * When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell. * When both robots stay in the same cell, only one takes the cherries. * Both robots cannot move outside of the grid at any moment. * Both robots should reach the bottom row in `grid`. **Example 1:** **Input:** grid = \[\[3,1,1\],\[2,5,1\],\[1,5,5\],\[2,1,1\]\] **Output:** 24 **Explanation:** Path of robot #1 and #2 are described in color green and blue respectively. Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12. Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12. Total of cherries: 12 + 12 = 24. **Example 2:** **Input:** grid = \[\[1,0,0,0,0,0,1\],\[2,0,0,0,0,3,0\],\[2,0,9,0,0,0,0\],\[0,3,0,5,4,0,0\],\[1,0,2,3,0,0,6\]\] **Output:** 28 **Explanation:** Path of robot #1 and #2 are described in color green and blue respectively. Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17. Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11. Total of cherries: 17 + 11 = 28. **Constraints:** * `rows == grid.length` * `cols == grid[i].length` * `2 <= rows, cols <= 70` * `0 <= grid[i][j] <= 100`
Sort the matrix row indexes by the number of soldiers and then row indexes.
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
Easy
null
167
hello everyone welcome to day nine of june lead good challenge my name is sanchez dodeja i'm working as technical architect sd4 at adobe and here i present some two input array is sorted here in this question we are given an array wherein the elements are stored sorted in non-decreasing order what do we need to non-decreasing order what do we need to non-decreasing order what do we need to identify those two indices whose sum is equal to the given target if that exists then we need to return those two indexes otherwise we need to return null so this is a very important question for creating the foundation of a two pointer approach and handling of maps so we will be solving two questions today that forms the foundation of map manipulation and two-pointer approach so manipulation and two-pointer approach so manipulation and two-pointer approach so do watch it very carefully if you're not able to understand these questions then you will not never be able to solve medium and hard level questions of two pointers or maps by yourself so do watch it till the very last now let's get started with the presentation also in case if you have any doubt understanding this question or if you want to ask anything from me in general with respect to placement and show internships hiring process then please feel free to drop a message on the telegram group or the discord server of coding decoded both the links are stated in the description so do check them out looking forward to solving all your queries out there now let's get back to the question and just for a second let's assume that the array is not sorted although it is specified in the question but let's hypothetically zoom that is not sorted and we'll go step by step building the approach one by one so we'll be solving this question by three approaches so let's get started so in the first approach let's consider the same data set although the r is sorted but we are not considering that aspect right now the target that we are looking for is nine and we are searching for those two elements where the sum happens to be nine so what we can do we can use two for loops for this purpose so the first for loop will start from two and then it will iterate and search for the remaining value 9 minus 2 is 7 so another loop will start for the jth index starting from this particular index up till the end and we will check whether 2 array of i plus array of j happens to be equal to target or not and you break this up as soon as we find this condition as true and i and j are those two elements so this is a pretty straightforward approach where you have used two loops one for i other one for j and at whatever position you see that array at the ith index plus area at the jth index happens to be target you avoid the process and they turn those two indexes the time complexity of this approach is order of n square now let's shoot for the other approach which is order of n approach where we'll using extra storage of size order of n again so let's go ahead and create the map and it would be of type integer gamma integer and the key of this map would be equal to the element comma the index at which that element occurs in my input array so let's quickly fill this up so first entry will be 2 comma 0 next entry would be 7 comma 1 followed by 1 11 comma 2 followed by 15 comma 3 and now let's start the iteration the first element that we see happens to be two and what is the counter remaining part that we are looking for at two we are looking for nine minus two which is seven so the first entry is 2 that we are aware of now we are looking for 7. what do we check whether 7 is present in my input in my map or not yes 7 does exist in my map and at what index does it occur it occurs at 1 so as a result of which we can say that the counterpart for achieving the target sum is present in my map as a result of which i have identified two indexes that leads to the sum of nine so at 2 what do we check whether the counter remaining sum does exist in the map or not here it does exist which is 7 and we extract its index which is 1 we know the index of the current element which is 0 so 0 comma 2 becomes part of our answer these are the two indexes that add up to give 9 as a total sum so this is the second approach and the time complexity of this approach is order of n because you are iterating over the input array and the space complexity is also again order of n in the previous approach the time complexity of order of n square and the space complexity was constant time now let's shoot for the third approach which is the to some kind of an approach and we will be exploiting the property that the array is sorted it can only be applied when the r is sorted these two approaches can be applied when the r is unsorted as well so let's shoot for writing the same case we have 2 7 11 and 15 so what do we take two pointers one from the zeroth index other one from the last index and we call it start comma end and we check what is the sum of the start and the end so start plus end 15 plus 2 gives you 17 is greater than your target as a result of which you'll reduce the value of end pointer has it been the case that the sum of start and end would have led to your target it would have aborted the process in case the sum of start and end is less than the target in that case you will be incrementing the start pointer this one and in the third case which is the right now case we are reducing the end pointer because the sum exceeds the target that you are looking for so we'll reduce the target and we'll reduce the end pointer and end now points to 11 let's do the same thing again start plus n gives you the sum of eleven plus two is thirteen is greater than nine as a result of it he'll reduce the end pointer and now points to over here seven plus 2 gives you 9 you have satisfied the condition it's equal to the target and you bought the process these are the two indexes that add up to the total target value that you have been looking for the time complexity of this approach is order of n because we have not sorted the rx exclusively it was already sorted in the equation the space complexity is order of one now let's quickly look at the coding section and load this up even before jumping onto the details of today's question i would like to introduce you all coding decoded is the preparation and revision sheet i know for students especially it becomes really overwhelming because there are so many concepts out there and if you have an eminent interview planned then you don't know how to go about it since there are so many questions on lead code approximately 2300 which one to go for what questions will give you the confidence that you are interview ready so to help you guys i have created dynamic programming graph try binary search backtracking bit manipulation monotonic stacks sliding window heaps priority queues matrix sd division sheets so if you go and check out the sheet you will find the first thing is a template that wherein i have explained the basis on the core algorithm that gets utilized in that concept for example bit manipulation so you go through this video up and then you will see that all the following questions utilizes the same template so this question is for building the understanding and the rest one is for the application part you will get a good hold of the concept go and try these questions up and i promise after going through the entire sheet bit manipulation will be done and dusted similarly for grass as well tries as well and do have a look at the backtracking sd revision sheet because it's quite difficult to understand and i promise once you'll go through the combination some three template uh you can you yourself will see that the same template gets applied in all the rest of the questions you will get the confidence that you are ready for the interview you are ready to go into that battlefield and i promise it will give you a good hold of the concept that you are looking out for now let's get back to the question so let's shoot for the two pointer approach first and then we'll move to the map approach so here i've created two pointer start is pointing to zero and is pointing to the last terminal while start is less than end if my sum of start plus numbers at end if the sum of these two elements is equal to the target this is what we have been looking for that means we have found out the answer we built our answer and return it up otherwise we check if the sum of start plus sum of end happens to be less than the target what we should do we should increase the sum so for increasing the sum we will increment the start pointer otherwise in the third case the sum of start plus end is less than is more than the target as a result of which we are decreasing the total sum therefore we will reduce the end pointer because end holds the maximum value start holds the least value once we are out of this while loop what do we do simply return null so this is the first approach so let's try this up accepted time complexity is pretty fine understood for the second approach now here i've created a map and uh what do we add entries onto this map and we check whether uh the target dot el we have iterated we are writing over the input ra and we check whether target minus cl is present in my map or not if it is present then we check whether we are not considering the same element again and again for example let's assume the target is 4 and the element that exists in my input ra happens to be 2 then we should not consider the same two twice as a result of it we should have a corner case specified that map dot get the index of the remaining element remaining some element should be equal to the current index into consideration if that is the case we have found out our answer we build our answer array and we simply break that up otherwise what do we keep on adding that particular element at that at the ith index into the map and contain the for loop once we are done with this we simply return this count array so let's try this up again accept it and i think this should not be named count we should name it the answer array that would be a better nomenclature so updated it up and with this let's wrap up today's session all the links are specified in the description below so do check them out over to you guys the hard work is yours i can only be the catalyst thank you you
Two Sum II - Input Array Is Sorted
two-sum-ii-input-array-is-sorted
Given a **1-indexed** array of integers `numbers` that is already **_sorted in non-decreasing order_**, find two numbers such that they add up to a specific `target` number. Let these two numbers be `numbers[index1]` and `numbers[index2]` where `1 <= index1 < index2 <= numbers.length`. Return _the indices of the two numbers,_ `index1` _and_ `index2`_, **added by one** as an integer array_ `[index1, index2]` _of length 2._ The tests are generated such that there is **exactly one solution**. You **may not** use the same element twice. Your solution must use only constant extra space. **Example 1:** **Input:** numbers = \[2,7,11,15\], target = 9 **Output:** \[1,2\] **Explanation:** The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return \[1, 2\]. **Example 2:** **Input:** numbers = \[2,3,4\], target = 6 **Output:** \[1,3\] **Explanation:** The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return \[1, 3\]. **Example 3:** **Input:** numbers = \[\-1,0\], target = -1 **Output:** \[1,2\] **Explanation:** The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return \[1, 2\]. **Constraints:** * `2 <= numbers.length <= 3 * 104` * `-1000 <= numbers[i] <= 1000` * `numbers` is sorted in **non-decreasing order**. * `-1000 <= target <= 1000` * The tests are generated such that there is **exactly one solution**.
null
Array,Two Pointers,Binary Search
Medium
1,653,1083
829
how i had a pretty good answer for this question and i would like to share it with you guys 8 29 consecutive numbers sum um i'm going to assume you're already familiar with the question i'm not going to explain it first i want you to think about what it means to be consecutive here's what i think it means my intuition is this if any number has any consecutive sum that consecutive sum has some base that is divisible by that number subtracted after you subtract the extras for example if i have 15 we know that uh eight plus seven is i can say oh let's do like four plus five plus six that's a consecutive sum of fifteen the base number in this case would be three plus one three plus two three plus three what my intuition is this base number after you subtract these numbers from 15 what you get is what i'm arguing well my intuition is that three uh whatever we have on the right side is gonna be divisible by three so we're gonna have uh nine divisible okay and uh this is gonna be true for all consecutive sums all we have to do is check going from uh one up to square root of n if that number is uh the space if i if it you know uh satisfies this equation if it does then that means we have an extra consecutive sum now instead of iterating from zero to square root n we can do even an even more simpler way okay here's the code so we have count this is going to be our return and i equals 1. instead of going from i to square root n we're gonna do it this way and uh yeah that's it the reason this works is uh we first check one okay if we have an example of 15 when we subtract one the base becomes uh if after subtracting one uh the remainder is divisible by one then there must be a base that means our base would be this 14. then we'll go to two now uh n becomes 14 because we already subtracted one so we don't want to subtract one again all we're going to do is uh subtract 2 now and we're going to be left with uh 12. so we have subtracted 2 out 2 already so basically what we have is 15 minus 1 minus 2. if this is divisible uh divisible by two then we have a uh that's a consecutive sum then we do minus three divisible by three and then minus four divisible by four that's what we're checking for each time this is true until uh this left side is uh while this left side is greater than zero anytime that is true then we have an additional consecutive sum okay that's basically uh what i have shown here um please let me know if that makes sense if you have any questions leave a comment and keep practicing okay
Consecutive Numbers Sum
subdomain-visit-count
Given an integer `n`, return _the number of ways you can write_ `n` _as the sum of consecutive positive integers._ **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation:** 5 = 2 + 3 **Example 2:** **Input:** n = 9 **Output:** 3 **Explanation:** 9 = 4 + 5 = 2 + 3 + 4 **Example 3:** **Input:** n = 15 **Output:** 4 **Explanation:** 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 **Constraints:** * `1 <= n <= 109`
null
Array,Hash Table,String,Counting
Medium
null
455
hi everyone welcome to leid syntax today we will be solving the question assign cookies so let's see what is this question assume you are an awesome parent and want to give your children some cookies but you should give each child at most one cookie okay each child eye has a great Factory GI which is the minimum size of a cookie that the child will be content with and each cookie J has a size SJ okay we are given with greed factor which for which a child cannot accept a cookie less than this G factor and we have been given a size array for the size of the cookies okay if SJ is greater than or equals to GI we can assign that cookie J to the child I and the child I will be content your goal is to maximize the number of your content children and output the maximum number so what we need to do in this we can assign a cookie to a child only when the size of the cookie is greater than or equal to the G factor and we need to find the number of cookies or we can say we can find we need to find the number of content child and the child will be content only if we assign a cookie of size greater than to its GRE Factor okay so let's see how we can solve it so let's start by taking the first example in which the green factor is this and the size of cookie is this so first of all let's start if when we are given with if we sort the G factor and also Sol the size of the cookies okay so then let's start with the first G factor and the first size okay so compare if it is greater than equal to this yeah cool so we will simply assign this cookie to this child okay now we will move to the next child and we will also move to the next cookie now we will check if this size of cookies greater than this grid no okay now the game is okay so what we need to do here how means how we need to increase the pointer like if we can assign that cookie then we implemented both the pointers but what if we were not able to assign this cookie to this okay let's see this size of cookies is less than it is great Factor okay so if we just increment this point then obviously all the GRE Factor after this is greater because we have already sorted this so if this size of cookies is not able to fulfill this greed Factor then how it will be able to fulfill the next greed factors which are already greater than two so yeah we need to we came to know that we can't increment this pointer this will not be worth okay so what if we will increment this pointer yeah we can increment this how the size of cookie after this pointer will be greater than or equals to one because we have already sorted the size of cookie as well yeah so if the size of cookie increases then yeah it might be able to forfill this GD okay so we will increment this pointer but no cookie is present after this so it will finally return one because we were able to fulfill only one child greed okay this was very small example let's see some big example for better understanding so now in this example first start with first cookie and first child okay so yeah one is greater than c yeah cool so we can assign this cookie to this ch very good now we will increment both the pointers okay now one is greater than equals to two no so incrementing I pointer let's say this is an i pointer and let's say this is the J pointer so incrementing the I pointer will be not worth because the GED after the two or greater than two and one will not be able to F for two GD so how it will be able to fulfill the G greater than two so we will increment the J Point yeah now we will check for 2 is greater than or equal to two yeah very good so we will increment this cookie to this child okay now if we have uh issued this cookie to this child then we will increment both the pointers that is I and J so yeah now we will check if two is greater than three no so we will inclement J pointer now yeah three is greater than equal to yeah so we will simply give this cookie to this child now if we have given this cookie so we will inclement both the IJ pointers and they gets out of bound so finally we will return our answer yeah one thing I forget to tell when we need to increment our answer when the size of ookie is greater thanal to size of sorry is greater than or equals to Greed of child then we will be incrementing our answer so in this way at first we will increment here now at second we will increment at this now at third we will increment at this so finally the total number of content child in this example is three okay so I hope you get this now let's try code this approach so what we were doing we were first sorting both the arrays that is GRE and the size of cookie okay so sorting the G array and then sorting the size array s do begin comma s do end okay now I will declare my result variable as zero now I will initialize two pointer I from z and j from Z and I will Le a r when I is less than G do size and J is less than G do if both are under bound both are inside the bound of array then only we will learn this Lo now we will check if sorry J is less than the size of cookie if the size of cookie is greater than or equals to the size of grid then we will increment our result and increment both the pointer as we will simply increment the pointer of the size array of the cookie when this we came out of this Lo we will simply return the result let's try run this yeah it's working fine let's try submitting this yeah it's good now let's talk about it time and space complexity so you can see we are sorting this so let's say if it is of n size then inserting the G array it will Take N of log n and for sorting this let's say it size is M so it takes M log M and this Loop will run till minimum of n comma M the smaller okay minimum of n comma n because if any one pointer goes out of one then we will come out of this Loop so we can say what we the overall complexity if n is greater then the complexity will be n log n if m is greater then the complexity is M log so let's say the complexity is n log N I am assuming that n is greater than okay I hope you get it because it finding its complexity is very simple I am assuming that n is greater than n okay cool it also needs to be added yeah now let's talk about space complexity we are using this constant space for showing the result and this i j so space complexity will be big go of one okay good so I hope you get this question it was a very easy question in and it was also very intuitive as well thank you for watching this video bye-bye guys
Assign Cookies
assign-cookies
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number. **Example 1:** **Input:** g = \[1,2,3\], s = \[1,1\] **Output:** 1 **Explanation:** You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. **Example 2:** **Input:** g = \[1,2\], s = \[1,2,3\] **Output:** 2 **Explanation:** You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. **Constraints:** * `1 <= g.length <= 3 * 104` * `0 <= s.length <= 3 * 104` * `1 <= g[i], s[j] <= 231 - 1`
null
Array,Greedy,Sorting
Easy
null
1,028
hello everyone today we are going to see this problem one zero two eight recover a tree from pre-order traversal recover a tree from pre-order traversal recover a tree from pre-order traversal the question is like we run a pre-order the question is like we run a pre-order the question is like we run a pre-order depth first search dfs on the road of a binary tree at each node in this traversal we output d dashes where d is the depth of this node then we output the value of this node if the depth of a node is d the depth of its immediate child is d plus one the depth of the node is zero root node is zero if a node has only one child that child is guaranteed to be the left child given the output s of this traversal recover the tree and return its root so here the example says like you have one as a root node two five three four six and seven and the pre-order traversal will be one and the pre-order traversal will be one and the pre-order traversal will be one two three four five six seven so since like two and five are at the level 1 in front of 2 you will see 1 and 1 dash and since 3 4 6 7 has the level as 2 you will see 2 dash in front of those nodes so you being given as a string as an input and you need to provide the output like this so this is a level order traversal like if you see like one two five three four six seven that's the output that you have done let's see another example you have one two five three six four seven and if you see for four it's like three dashes up there which is left four is in uh level three and you know same for level seven you'll see like three dashes and for six you will see two dashes and for three you see two dashes in front of that node and for two and five you will see only one dash and the output should be one two five three null six null four null seven so that so consider this three one four zero one three forty nine eighty eight and ninety and your input is given like 1 4 0 1 3 49 90 and 88 so here we need to pass the string and extract out the numbers and whenever you find dash you will increment the level for dash and extract the numbers two steps after that what we can do is we can add these node to a stack and when you see let's say like we are adding 1 to the stack and when you get 4 0 1 what you can do is you need to check whether 4 0 1 the level 4 0 1 which will be 1 in this case is greater than the stack size if it's greater then you need to pop otherwise what we can do is create a node for this and take the peak of this stack and you put that 401 to the left of it if we already have left for one then you will have to put the note to the right of it but in this case since one doesn't have a left node we are putting that into the left node for the first step so we put that and push this back on top of the stack so now the stack size is two now i trade again now go for 349 so we get the number 349 and in this case your level information is 2. so level is 2 here the stack size is also 2 so we cannot pop it so what we do is we take the peak of that the current stack and push it to the left of the node then put this 349 back so now the stack size becomes 3 and we are getting 90 here and for 90 our level is 2. so the stack size will be so for 90 it's three so since the same thing we push that 90 pushing it to 90 here so after 90 we get 88 so 88 we got the level for this one is equal to 2 is equal to 1 is equal to 2 so the stack size is now four so it's definitely greater than level three is greater than left four so what we do is we pop it so 90 is popped out of the stack and we have 349 as the peak right and now stack size is equal to 3 and again we level equal to 3 which is greater we pop out 349 also stack becomes 2. so the top is 4 0 1 so since 4 0 1 is already having 349 the level is not is lesser than the level we push this 88 to the right of the 4 node 401 so that is getting added and we push this 88 into the stack so we go through that like this and we pop it out once we went through all these string so we are going to code this out um so let's initialize level and we have to go through the length of this string that we got and let's say we have to initialize the stack as well so you know character is a hyphen or not then we increase the level so for that one what we have to do is level equal to zero and s dot at i is equal to so we have to proceed only if it goes through that and increment the level so we got the level for this one and the same case we have to so every time initialize the valve and the i should be less than one and s dot 10 plus star i minus 0 so here we are extracting out the number after that what we have to do is why stack dot size is greater than level we pop it out because that's what for whenever we see a stack size is greater than the level we pop the stack and we create a node here if the stack is not empty we go through that and see if uh stacked or peak dot left is equal to if left equal to null what we do is stack dot left is equal to the current node otherwise stack dot write a be our current mode so once this is done let me just uh add for the number so once we are out of the string we extract the stack size because we need the last stacked this should be good i guess so it is accepted and then i'll submit it okay it's getting submitted thank you
Recover a Tree From Preorder Traversal
interval-list-intersections
We run a preorder depth-first search (DFS) on the `root` of a binary tree. At each node in this traversal, we output `D` dashes (where `D` is the depth of this node), then we output the value of this node. If the depth of a node is `D`, the depth of its immediate child is `D + 1`. The depth of the `root` node is `0`. If a node has only one child, that child is guaranteed to be **the left child**. Given the output `traversal` of this traversal, recover the tree and return _its_ `root`. **Example 1:** **Input:** traversal = "1-2--3--4-5--6--7 " **Output:** \[1,2,5,3,4,6,7\] **Example 2:** **Input:** traversal = "1-2--3---4-5--6---7 " **Output:** \[1,2,5,3,null,6,null,4,null,7\] **Example 3:** **Input:** traversal = "1-401--349---90--88 " **Output:** \[1,401,null,349,88,90\] **Constraints:** * The number of nodes in the original tree is in the range `[1, 1000]`. * `1 <= Node.val <= 109`
null
Array,Two Pointers
Medium
56,88,761
1,684
okay guys so today we'll be solving the problem count the number of consistent strings on lead code so the question says you're given a string allowed consisting of distinct characters and an array of strings words a string is consistent of all the characters in the string appear in the string allowed return the number of consistent strings in the array words so what the question says is you have to check if the letters a b which is in the variable allowed is present in the words list basically we'll go through you have to go through each element in the list like 80 and check if each element a and b basically are a or b or not so we have to check if all the words are either a or b there shouldn't be any word other than a b okay so uh will be for example a d so we have a but we don't have d so this is an invalid word in bd we have b but we also have d so this is invalid word but in the third one we have three times a and one time b so this is valid because all the elements are either a or b so here it can also be for example in the next question it can also be just a and b a b and c as uh it's present here it doesn't have to be compiled together it can either be a b a c b c a b c individually as all the words are given okay so this is a question so how can we solve it so uh we can use the double for loop method for this so we have to set a counter and we have to loop through the words in the list in the words list so for example we go through each word so the first word we get is 80. we have to loop through each letter in the ad word so first will be a and then b and then we have to check if each letter is present and allowed so as if it's in this list in this string of word then it's a valid word otherwise it's an invalid word and we'll set the counter to check if it's an invalid word and if it's an invalid word we'll increase the count it is one and in the end we return the length of words minus count so i'll go ahead and show you so i'll be on running it yeah it's accepted and submitting head yeah we get a 89.4 percent uh accuracy yeah we get a 89.4 percent uh accuracy yeah we get a 89.4 percent uh accuracy so what we're doing in this question is as i told before middle loops so let's take an example of this question so we're going to loop through the words array so here the first word will be a and we'll check if a is present in a b c in the allowed so it's present so it's a valid word and if it's a valid word we go to the next word so b it's a valid word we go to the next one c then we go to a b it'll check if a is valid it is then we check if b is valid then it's also valid if ac the same thing happens bc and abc all the times the same thing happens so we get the length of words would be seven because it's the length of this and minus the count so count is zero so seven minus zero is zero uh seven so it'll be seven but the question like this will be we'll go from 80 we'll check if a is present yes it's present we'll check if b is present so d is not present so we increase the count to 1 and we break through and go to the next question so it's bd we go to the next element in the list so it's bd so b is present and b is not present so we increase the count again here a is present and b is present so we'll go to the next list we won't increase the counter here and similarly for b a and b a d a b so in the end we get length of words would be so then the words is 5 and minus 3 so the count would be 3 for 1 2 and 3 so we get answer to
Count the Number of Consistent Strings
find-latest-group-of-size-m
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`. Return _the number of **consistent** strings in the array_ `words`. **Example 1:** **Input:** allowed = "ab ", words = \[ "ad ", "bd ", "aaab ", "baa ", "badab "\] **Output:** 2 **Explanation:** Strings "aaab " and "baa " are consistent since they only contain characters 'a' and 'b'. **Example 2:** **Input:** allowed = "abc ", words = \[ "a ", "b ", "c ", "ab ", "ac ", "bc ", "abc "\] **Output:** 7 **Explanation:** All strings are consistent. **Example 3:** **Input:** allowed = "cad ", words = \[ "cc ", "acd ", "b ", "ba ", "bac ", "bad ", "ac ", "d "\] **Output:** 4 **Explanation:** Strings "cc ", "acd ", "ac ", and "d " are consistent. **Constraints:** * `1 <= words.length <= 104` * `1 <= allowed.length <= 26` * `1 <= words[i].length <= 10` * The characters in `allowed` are **distinct**. * `words[i]` and `allowed` contain only lowercase English letters.
Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map.
Array,Binary Search,Simulation
Medium
null
1,189
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is maximum number of balloons so in this question we given a string called text we have to count the number of instances for the word balloon we have to check the characters present inside text and using those characters how many times you can form the word balloon and you can use each character at most once while calculating the output and we have to return the number of times you can form the word balloon using the characters inside this input text now let's take this example and see how we can solve this question so here you can see that so using this b a l o n you can form one balloon and you used up most of the characters except these two and using these you can't form the word balloon so you return one as the output so here you can see that you're making use of how many characters are present inside the word balloon so let's use the hash map to count how many times uh these characters are repeating the characters used to form balloon are b a l o and n l you're using twice and O you're using twice so let's see how we can solve this question using Code so I've declared a hashmap and I initialize the characters and initially I put the count as zero for these characters b a l o and L and now I'm iterating through the input string text using a for Loop I'm accessing each character at a time and I'm storing it inside the character variable CH and then I'm checking if that CH which I'm iterating through is present inside the map or not if it is present then I'm inserting that character and updating its count to one if I take the same example let's see how the hash map is being filled so initially all of them are going to be having zeros as values and each time you iterate from left to right I'm going to iterate this input string so I'm going to start with n through O So n is appearing once L is appearing once a is 1 e is not there inside the map so you don't consider that b is 1 o is one you have a l again so you update L to two you have a k is not present inside the map so ignore it o again so update O's count to two till here we have fil the map now you know you can use only each character once you find the minimum among all the values present so first I'm starting with a variable Min and getting the count of B to start with B's count is one so Min is equal to 1 since o and L are appearing twice in the word balloon so I'm dividing that count by two so that I compare it with the minimum value because in each balloon you're using two L's and two o's so if there are two L's and two o's inside the map you are going to use both these characters to form one balloon so that is why I'm dividing L and O with twos to form one word so minimum among them is one so this by two will also give you one so minimum among them is one so I'm updating each Min variable by getting the count of all the characters used to form the word balloon starting with b through n b a l o and n and L and O will be divided by two because in one balloon word you're using two L's and 2 O's and finally you're returning the variable Min and in this case Min is going to have one only so one will be returned as the output so the time complexity of this approach is O of n because I'm using a for Loop to fill the map where n is the length of the input string text and the space complexity is also of one because I'm using constant space inside the map though I'm using a map I'm using constant space inside the map so you can say that the space complexity is constant because the space is always going to be o of 5 because I'm using five entries inside the map since o of 5 is constant I'm using o of one as the space complexity that's it guys thank you for watching and I'll see you in the next video lady
Maximum Number of Balloons
encode-number
Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible. You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed. **Example 1:** **Input:** text = "nlaebolko " **Output:** 1 **Example 2:** **Input:** text = "loonbalxballpoon " **Output:** 2 **Example 3:** **Input:** text = "leetcode " **Output:** 0 **Constraints:** * `1 <= text.length <= 104` * `text` consists of lower case English letters only.
Try to find the number of binary digits returned by the function. The pattern is to start counting from zero after determining the number of binary digits.
Math,String,Bit Manipulation
Medium
1070
834
welcome to september's leco challenge this problem is called sum of distances in tree there is an undirected connected tree with n nodes labeled from 0 to n minus 1 and n minus 1 edges you are given the integer n that's the number of nodes and the array edges where edges i equals a and b indicating that there's an edge between nodes a and b in the tree return an array answer of length n where answer i is the sum of the distances between the eighth note and the tree and all other nodes so if we wanted to find the answer for this node here node zero we are going to count the distance to all the other nodes that's going to be one 2 3 4 5 6 7 8. you can see the answer is 8 here so at first glance it kind of looks like we can just do a traversal starting with some node and do a variation of dixter's algorithm keeping track of the nodes that we visited and just increase the distance traveled by one and keep track of that somewhere and return that right so let's begin with that approach let's say we want to first build a structure to traverse right and we're not given a binary tree notice this isn't a binary tree at all it's kind of like more like a graph so let's create a graph here what we'll do is make a default dict and we'll make a list of values and that's going to be all the next nodes or child nodes rather that this node can travel to so for source target and edges keep in mind that this is bi-directional keep in mind that this is bi-directional keep in mind that this is bi-directional so we can travel either way so that means for the graph s we want to append the target and for the graph t we want to append the source because we want it both ways now to keep track of the uh make sure that we're not going to do any cycles here we can just use a visited set what i'll do is create a function passing in the i node that we want to calculate for and we're going to have some structures here we'll have a set and we'll first include this node itself so that we don't travel it uh we'll also have a q and this will be the q with a tuple of the node that we've traveled as well as the distance that we've traveled so far so this would be zero at first and we'll also have to have some sort of output right so output will start with zero all right so while there's a q let's first pop off we'll have the current node exposed as well as the distance and that means we have to travel to the next one for next in graph of current as long as we haven't visited before if next not in visited let's add to the visited set this next and we are going to add back to our queue the next as well as the distance plus one but we want to keep track of you know all the sum of distances right so we'll say output plus equals distance plus one finally we just return our output and all we would have to do then is return a list uh we'll say travel i or i in range of n and n is given to us right so this was my first approach and i wasn't sure if it would work it looked like it would work but unfortunately it reaches a time limit exception reason for that is this is going to be an n squared solution right for every single node that we want to travel we have to travel again and even if we did like lru cache here it wouldn't really make any difference so what can we do um well essentially then what we'd have to do is figure out a way to calculate all this in one traversal or maybe two and i'm gonna go through the answer here it's a bit complicated so i'm gonna show the white board all right so this was our tree that we've our example right well what is some value that we could calculate for every single node in one pass one of the things that we could calculate is how many nodes including itself are underneath this tree so we can do just whatever a depth or search and every node starts with one right each one of these leaves has at least one and what we do is when we return let's say we go that first search and we go back to two we'll add whatever values here up here back here so we start with one this becomes one two three and including itself that's another one so that's four right so this becomes four and here this returns one four that's five and include itself this is going to be six so what this shows is how many nodes including itself are beneath the tree so you can see it's like one two three four five six one two three four these all have one okay that's great and everything but how does this help us well if we did our traversal first let's just say we had the answer for our parent node so say that somehow we figured out what the answer was for our root node eight right if we had the answer to our parent there's actually an equation that we could use to calculate what the answer would be for here so think about if we want to figure out what's the answer for one it's essentially everything to the right side here gets shifted by one so how many nodes are on the right side that's going to be n number of nodes subtracted by how many counts are here at this child right so this would be let's call it c of child and that would be 6 minus one right so we can see like let's take our answer from the parent that would be eight we can add the n minus child here that's gonna be five but keep in mind we actually need to subtract everything to its left side so everything beneath here actually gets shifted by one as well because you know everything here to the right side is like one further but everything to the left side here is one closer right so we have to minus our count of the child as well here so that would be one so in total that's gonna be eight plus five that's 13 minus one and it's going to be an answer of 12. so we can do this in two passes we have to first figure out though um we need to keep track of the counts in some sort of array and we also need to calculate the answer for that root node in the very first pass and if we do that then all we need to do is use this equation traverse everything again doing another search and we can calculate everything and add that to some sort of array and return that all right so hopefully that kind of helped explain the approach let's begin all right let's first initialize a couple of variables here um we'll first have our output and this will just be starting with zero times n and we also want the counts right of everything beneath it and this would start with one because each node itself counts as one and we'll also have to have a self variable here for the root answer i'm just going to call that root and this begins with uh i believe that starts with zero all right so let's first call our debt first shirt or create our deferred search and what i'm going to do instead of using a visited set i'm going to keep track of the current and the parent okay so this will be current and this will be parent and the reason for that is we're doing that for search we just want to make sure we don't travel back up okay so as long as the current the next node is not equal to the parent we're just going to skip that and we also need to pass in the depth right here um and i'll show you why in a bit all right so uh first thing we'll initialize our output i'm just calling o just so we don't get confused and we're going to say for let's call it child and graph of current now if child does not equal parent then we're going to continue our debt for search and we want to add back to our output that we're going to return whatever returns here so therefore search of let's see child current and the depth but each time we travel down it's going to be depth plus one right and i'm going to add to the root here the depth plus one as well kind of like how we did it to in our first approach and this is going to keep track of our answer for the root node and that's going to come in handy later now once we finish this whole loop i believe then we could just calculate our current that's going to be count of current is now equal to the output and make sure to actually return the output here as well because you can see we have to add that up right okay so that for search let's call this uh the current will be zero parent at first will be nothing we'll call negative one and the depth will also start with zero right here so just to make sure i wanna see what this looks like um let's make sure this looks correct all right so this looks like all the counts right this is six nodes four nodes and the answer to zero root zero was eight so we have everything that we need now we just need to create another deferred search i'll call it deaf search two and this also we have to add in the current the parent as well as the answer to the parent i'm gonna call that answer parent and this one will be a little bit easier we just have to say okay output of the current is just equal to answer p that's a little that's actually not named very well but that's okay um and then you just have to say for child in let's see graph of current as long as the child is if child not equal to parents then we'll just call our deaf search two but this time pass in the child the current and the answer p though remember we have to pass in the answer p and we have to add n minus count of child or not child where is a child i guess it is yeah child and we also need to subtract count of child like this okay so let's call our deaf for search zero uh first parent and then our self.roots uh first parent and then our self.roots uh first parent and then our self.roots will be the answer at first and finally we turn our output okay so let's make sure this works okay that looks like it's working right so submit it ah there we go so time complexity this is gonna be of n right even though we make two passes that's still of n uh it's very tricky i think the hardest part is coming up with uh this answer here and really i'm not gonna pretend like i came up with this i had to look it up and even after looking it up it took me quite some time to figure out how this actually works um it's a really brilliant algorithm but i think it's pretty hard pressed to expect someone to come up with this on the spot but hey that's like one of the things we learn right and um yeah it's like we're kind of gathering up information in two steps and once we kind of figure out some partial information then we can do another step and like complete the information all right well i hope that helps thanks for watching my channel and remember do not trust me i know nothing
Sum of Distances in Tree
ambiguous-coordinates
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. Return an array `answer` of length `n` where `answer[i]` is the sum of the distances between the `ith` node in the tree and all other nodes. **Example 1:** **Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,3\],\[2,4\],\[2,5\]\] **Output:** \[8,12,6,10,10,10\] **Explanation:** The tree is shown above. We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer\[0\] = 8, and so on. **Example 2:** **Input:** n = 1, edges = \[\] **Output:** \[0\] **Example 3:** **Input:** n = 2, edges = \[\[1,0\]\] **Output:** \[1,1\] **Constraints:** * `1 <= n <= 3 * 104` * `edges.length == n - 1` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * The given input represents a valid tree.
null
String,Backtracking
Medium
null
918
Hello gas fashion review Agarwal welcome you assignment for you made by you so let's know today silicone problem nowadays name of problem of liquid is maximum sam circular medium level problems are very simple problem we don't have any talk so first of all our Let us see what is given to itself within this question and what is this question trying to say to itself, then within this question an era is given to itself which will be circular in nature, meaning its last element will be It will be connected to its first element and we have to tell ourselves that which is the subhere inside this circular formation whose sub is maximum and we have to return it to us with the same maximum. So if you understand this question then these 6 examples. I have given myself the error 1 - 2 3 and -2 myself the error 1 - 2 3 and -2 myself the error 1 - 2 3 and -2 which I must have written here to make my circular array and I have to tell myself that which is the substring inside this circular array whose sub will be maximum then if our Inside this Eric, start your element from 3 and end at van, then what will be the sum of this circular element, meaning this circular element is 3 - 2 meaning this circular element is 3 - 2 meaning this circular element is 3 - 2 and 1 and its sum will be that from your Eric element. Apna is small, that is, if we keep Apna Samvare sir of three, meaning even if Apna Samvare is of only one single element, then its relative will be three, which is bigger than Apna Tu, so what will we say that Apna maximum sum is three and Apna Ko is only three. If you return, then if you understand this question from this example, then in this example five minus three and five will be connected to the last money below it. So if you do this, then its sum will be 10, which is your 7. Will do and say that tan is our answer meaning 10 is our maximum sum is our answer means we have understood the question well. Now if we have understood our question well then let us see how our friends will solve this question. For this, I would first of all have found a conference whose sub would be maximum without considering the circularity, meaning if my area was not circular then I could have come up with such a conference from the cutting cell caller them whose sub would have been maximum then I would have been the first one. If I do that then the maximum time that will come to the alcosis due to my bite will be 7 which will be the same for its entire area because the maximum time for its entire area is the same. If we consider any of its mornings then that file will come which is Is it less than your consumption? Okay, so from reading alcohol, we all have passed a morning in which all is maximum and we will not come across a time in which all is minimum, then where will the minimum come from, we will compare the minimum with the algorithm of subtracting our maximum. The time was that it is bigger or if we subtract the minimum from our total sub i.e. the or if we subtract the minimum from our total sub i.e. the or if we subtract the minimum from our total sub i.e. the total sum of our area, then it will come out that our maximum will be more and we will return whatever our area is, that means the total number will be A. Apna's total sum is 7 A. If from inside this Apna is mined out then what was Apna's minimum - 3 If Apna has what was Apna's minimum - 3 If Apna has what was Apna's minimum - 3 If Apna has mined that then what will become Apna it will be plus three which will be 10 so Apna What did you do, was your total minimum element, meaning, if you have mined out the time in which the sub was at its minimum, then what is your area left, that is, your morning child is five and five, whose sub is being maximum, then what is your area? We will return the maximum and if Apna was not in such a case, Apna would have been in such a case that if Apna's maximum which we have come would have been rigorously solved by the algorithm, then it would have been late proposed. If Apna had been 12, then we would have considered it as our maximum in the case. If it happens then we return it to us in the maximum of our case, once we see our this one has our that case A, inside this was our Erica 1 - 2 3 and -2 inside this was our Erica 1 - 2 3 and -2 inside this was our Erica 1 - 2 3 and -2 inside this if our flat is from us Apna maximum time three maximum ko apna mines ok total sam apna kya hai plus four minus four means zero from within this if apna minimum sabir itko meaning this mines tu ko mines this month then understand that as yours. If there was three A, then we will say that whatever is three, we will return our maximum time to our C. This is a simple question, okay, first of all, I have created a total relation, inside this I will store the entire total, then I will calculate the maximum sub. For embroidering silk and we have made one cut currents and one such maximum savere because it will contain its maximum save with me i.e. with me i.e. with me i.e. any savere is fine to store our maximum samaye and one I have made such a current to make minimum savee. We have made you and I have made a minimum butter because a snake charmer will consider that which we will be minimum then I started completing and I have added all the elements inside the total sub, first and in the current element, meaning one, I have made the current. Is maximum element means we will store a morning whose sub will be maximum then its sub is minimum ok so what I did I added each element with its current and added the day of both C in sub and in C2 then I said inside it is initial brick I mean, mines will be infinite and inside it there will be plus and find out. Then I said that if your current number is greater than your maximum, then whatever value is inside it, add it to your maximum, then your maximum will be five. And I said that if whatever is in our Currents Hum Tu is smaller than our minimum then put it in the minimum. Minimum is infainight. If five and five nights is small then our minimum will be 5. Okay then I said that if our If C1 is less than zero, then make it equal to zero and if your answer is C2, it is greater than zero, that means there is a positive value inside it, then make it back to zero because you have to put the minimum possible value inside it, okay. Now I said that in the maximum, if the value of your maximum is less than C van, then make it equal to C1, but it was bigger than C1, so we will not make any change here and in the minimum, I said that if the value of minimum is If it is bigger than your seats, then make it equal to the seats, then what will you do? Make the minimum equal to the seats, that is, minus three. Then I said that if the value of the sea van is less than zero, then make it equal to zero. If the value of 2 is greater than zero then make it equal to zero but if both the cases are not like this then we will not do anything then we come back with the price so what if we make it equal to the maximum then what will be A in our maximum? 7 A will be and I said that if the value of C2 is more than the minimum, that is, if it is less than the minimum, then make it equal to the minimum, then if the value of C2 is more than the minimum, then you will not make any change in your minimum and will return to your account. We will reduce the Situ to zero and one of our creations will be finished here, so Apna said that the maximum value which has come from the algorithm by entering Apna means the one which I understand is 7, that is Apna's maximum whose sum will come in the morning, okay and Apna's Minimum Possible Sam used to jump, it could have been his -3, he is jump, it could have been his -3, he is following his completely, he is saying that what will happen in the last minimum, what is the minimum of his, there will come in the morning such a person whose all will be minimum, that maximum will be in the morning. A question will come which means there will be only one engagement whose sum is maximum then we will compare our consideration that if its total sum and minimum are equal then in which case it will come in the case when all its elements are negative. If all our elements are negative then they will become aderk. If the minimum comes in our minimum morning, then it will be the time of all these elements. The head of all these elements will become minus 13 and our total will also be in our total. So in this, what will we do with our total minus 13, we will return it to our maximum sabri in case, what will happen in our maximum sabri, it will be -3, meaning the smallest negative -3, meaning the smallest negative -3, meaning the smallest negative value will be in our minimum maximum sabri, okay. So Apna will return the same that her biggest sum which could be equal to her smallest negative element is ok and if it is not so, there is any positive value in Apna ATM and these two are not equal then what will Apna do Apna We will compare which is bigger, our maximum journey or our total submains. If we mine our minimum morning, that is, whatever was our minimum, like there was our minimum minus three A inside it, then if we eliminate it, then our total Out of the two, which one remains bigger, his maximum is bigger in the morning, then he is increasing his total kindness, minimum sabar, then whoever comes bigger, we will return him, this is our simple question, it is visible after submitting once. So han this is my absolutely accepted solution thank you so much
Maximum Sum Circular Subarray
reachable-nodes-in-subdivided-graph
Given a **circular integer array** `nums` of length `n`, return _the maximum possible sum of a non-empty **subarray** of_ `nums`. A **circular array** means the end of the array connects to the beginning of the array. Formally, the next element of `nums[i]` is `nums[(i + 1) % n]` and the previous element of `nums[i]` is `nums[(i - 1 + n) % n]`. A **subarray** may only include each element of the fixed buffer `nums` at most once. Formally, for a subarray `nums[i], nums[i + 1], ..., nums[j]`, there does not exist `i <= k1`, `k2 <= j` with `k1 % n == k2 % n`. **Example 1:** **Input:** nums = \[1,-2,3,-2\] **Output:** 3 **Explanation:** Subarray \[3\] has maximum sum 3. **Example 2:** **Input:** nums = \[5,-3,5\] **Output:** 10 **Explanation:** Subarray \[5,5\] has maximum sum 5 + 5 = 10. **Example 3:** **Input:** nums = \[-3,-2,-3\] **Output:** -2 **Explanation:** Subarray \[-2\] has maximum sum -2. **Constraints:** * `n == nums.length` * `1 <= n <= 3 * 104` * `-3 * 104 <= nums[i] <= 3 * 104`
null
Graph,Heap (Priority Queue),Shortest Path
Hard
2213,2218
1,572
now we're going to cover a coding interview question matrix diagonal sum here's the problem statement given a square matrix mat return the sum of the matrix diagonals only include the item of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal this is the problem statement if you are given this particular matrix as input the sum for this primary diagonal 9 plus 1 plus 5 that's equals to 15 and the sum for secondary diagonal 7 plus 5 plus 3 in this case we have an intersection so we have to exclude this element 5 for the second diagonal in this case 3 plus 7 is 10 plus 9 plus 5 plus 1 equals to 25 so we have to return 25 if you are given this particular matrix as input this is our primary diagonal and the sum for the primary diagonal is 1 plus 1 that equals to 4. for secondary diagonal this is our secondary diagonal the sum for secondary diagonal is 1 plus 1 equals to 4 plus 4 equals to 8. for this matrix we have to return eight for this matrix we see there is no intersection in between primary diagonal and secondary diagonal now how we can solve this problem in figure of in time complexity first this video right here try solving this problem in we go of end time complexity when you are done come back to this video first we are going to iterate through this matrix from 0 to the length of the matrix so in this case we'll iterate through from 0 to 2. we'll initialize a variable sum equals to zero for first iteration this zero will point to this element one right matrix zero and this is the element at the same time we're going to find the last element in this row and that is this element to get this element we have 0 and length minus 1 minus the current iteration len minus 1 is 2 to minus 0 for current iterations that's evaluated 2. so in this sketch we're going to add this to number 1 plus 3 equals to 4. so sum equals to 4 then for next iteration we'll have our value one okay here we'll have one and also here we'll have one this points to this value five then we're going to find the value for secondary diagonal len minus 1 minus current len minus 1 that is 2 minus 1 is 1 so in this case the value for secondary diagonal 5 so 5 plus 5 is 10 so 10 plus 4 then for next iteration will have the value 2 so in this case for primary diagonal 2 and 2 that is 9 this value nine plus then val first second to the diagonal okay so for secondary diagonal length minus one length is three minus one is two minus 2 is 0 so this value will change to 0 and this points to this value and that is 7 so 9 plus 7 equals to 16 plus 14 equals to 30 when we have the length for our given matrix odd then what we'll do we will subtract the value we can get by dividing the length by 2 so in this case we'll subtract this value 5 if we subtract 5 from 30 this will be evaluated 25 so in this case we'll return 25 if you're given this matrix as input then how we can find the answer first we have this value this is for primary diagonal and this is for secondary diagonal so sum of this 2 is 2. then for next iteration for primary diagonal this is our next value and for secondary diagonal this is our next value so 1 plus 1 is 2 so 2 plus 2 is 4 then for primary diagonal this is our next value and first secondary diagonal this is our next value if we add 1 plus 1 is 2 plus 4 is 6 so sum equals to 6. then for primary diagonal this is our next value and for secondary diagonal this is our next value if we add this two value we have two one plus one is two plus six is eight so we'll have some equals to 8 and we're done here when we have the length of the given matrix or you could say the width for the given matrix is even then we'll return whatever value we have at the sum variable and there is eight so in this case we'll return eight you clearly see that there is no intersection in the two diagonal so we have to do nothing here we have to just return the value we have at some variable now let me show you how my solution might look likes in pseudocode first i'm going to declare a function diagonal sum that takes a matrix as input let's suppose that this is our given matrix then we're going to find the length and the length for this matrix is 3 then we have sum equals to 0 after that we're going to run a loop i from zero to length minus one all right then sum equals to sum plus matrix i the matrix i in minus one minus i so for primary diagonal it points to this element for secondary diagonal this element and this is for primary diagonal and this is for secondary diagonal this sum variable evaluated for then for next iteration the next value for primary diagonal is five and for secondary diagonal is five so five plus five is ten so ten plus four is fourteen then for next iteration the value for primary diagonal 9 for secondary diagonal 7 9 plus 7 is 16 plus 14 equals to 30. when we have the width for a given matrix is odd we will subtract the value we can get by using this formula matrix length divided two then length divided to in this case this five so this will be evaluated for this matrix 30 minus 5 that is 25 at the end we'll return 25 for this given matrix if we're given a matrix that has the width of even number then we'll return the sum okay and this condition only for the matrix has width of odd numbers the solution will takes bigger of end time complexity in is the length or the width of the given matrix and the solution will takes constant space complexity since we're just using two variable length and sum alright guys hope this concept was clear if you have any question if you have any suggestion let us know thanks for watching this video
Matrix Diagonal Sum
subrectangle-queries
Given a square matrix `mat`, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. **Example 1:** **Input:** mat = \[\[**1**,2,**3**\], \[4,**5**,6\], \[**7**,8,**9**\]\] **Output:** 25 **Explanation:** Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 Notice that element mat\[1\]\[1\] = 5 is counted only once. **Example 2:** **Input:** mat = \[\[**1**,1,1,**1**\], \[1,**1**,**1**,1\], \[1,**1**,**1**,1\], \[**1**,1,1,**1**\]\] **Output:** 8 **Example 3:** **Input:** mat = \[\[**5**\]\] **Output:** 5 **Constraints:** * `n == mat.length == mat[i].length` * `1 <= n <= 100` * `1 <= mat[i][j] <= 100`
Use brute force to update a rectangle and, response to the queries in O(1).
Array,Design,Matrix
Medium
null
1,624
Hello everyone, so first of all, Happy New Year to you, today we have come to the daily practice problem of our lead code, so today's problem brings it in an AC category and says Question Largest substring between two equal characters question. You must have understood what is being said in this question. Let us understand this question through the example. I hope you must have read it. The question says that any two equal characters, as you see in the first example, A. And A, what is the equal character, so how many characters are there in between, total two, so any one in the string, two equal characters in the string, all the characters coming in between the two equal characters, you have to return the max of all the characters, okay. This is telling us a question, so for example, in this condition, if there was A B C, then the answer is two, then it is okay, and if such a condition comes that no two characters are equal, then it is okay, that is, any character in the string. Two characters are not appearing, okay, two equal characters are not appearing, so in that case you have to do minus and return, like you see C is there but there is no other C with C, which is at the other end, there is no other C with B. No, what is there at the end is the same scenario of XV is also the same. In this case, our answer will be 'Mive'. Okay, I In this case, our answer will be 'Mive'. Okay, I In this case, our answer will be 'Mive'. Okay, I hope you have understood this, let's look at it more carefully. Let's look at one more question: let's look at it more carefully. Let's look at one more question: let's look at it more carefully. Let's look at one more question: A B C D e. A BD A Okay, let's see this string, if we understand, what is your answer in this, what is our answer in this, what is coming, just look and tell, first of all, which two characters are equal, we are seeing, like if we talk about A first. If we go from a, then a and one, two are equal characters, then how many strings are there in between, three, four, one, our answer is a, possible after that, what can be the second one, that is, this and this is also equal, isn't it brother a? And a is equal, it is necessary to add that a cannot come between them, so how many are there in it, five are there, and then suppose I take a and this, how many are there, 3 4 5 6 7 8 9 nine. Okay, and then what other possibilities are there, this and this, we are seeing one two and four, then this and this can be A and A, that is our zero and one, it can be A and A. Ek doti ti so what do you have to take from this? Answer: Max is to be taken. what do you have to take from this? Answer: Max is to be taken. Similarly, it is possible for B too. Like in B also, if you see, how much B and B are 3 45. Okay, and there is something else possible in B and B. No. It is possible in D. Yes, one, two, three, four. There is no possibility in E, one, two, three, four. There is no possibility in C. So, what do you have to take in this? Max, you have to take the answer, how much did you get and which one was this character and this character? Whatever we are seeing in between is fine, so this is how we have to find our answer, so what approach should we take in this so that our answer comes, let's see, it is very simple, there is no need to take much tension in all these questions. First of all, whenever the character comes, let me tell you in the first constraint, the constraint has been given that the line of string max to max can go up to 300, okay, so it means we can comfortably play till O cube in 100, okay, so whenever. When it comes to strings and characters, you should always remember that there are only 26 characters, which means we can use them in a loop. Okay, let's do one thing, let's create a vector of all the characters, vector. Understand the size of 26, let's make a vector of vectors. Basically, it was 26 because there are 26 characters and we do one thing, we note down the position of each character, what does it mean, like I So how will you denote a for a, you will denote it by row because we are mapping row a with row, we are mapping one with a, we are mapping one with b, similarly we will go till 25 and what will that be, z will be okay. v of 0 in our in this vector in this position in this we return all the possible positions of a in the string. Look at a, which is the first position, which is one, which is the second position, which is two a 2 3 4 5 6 is seven is 8 9 10 11 is ok I have written all the a's similarly v ofv What will denote our B character will denote how many of its indexes will it come in which index will it come in second third fourth fifth sixth seventh eighth and It will not come in any, yes, then v out means when is my c coming, c is coming only once, okay in three, like that, how far will we go v of 25 irrelevant, assume that no character has come, z is as it is. No, there is no problem, how much will v of z become, zero means, you will calculate this, like you will calculate the size of v of 25, if this is MT, then it will directly return -1, which means one directly return -1, which means one directly return -1, which means one answer. This is possible, okay, so there is no problem, then if we have this data, what can we do after this, we can do a lot of things, after this we will do one thing, we have the starting point and end point of all the characters. This is important, if you have a starting point and an end point, that is, its minimum value and its maximum value, then you will get the value of all the characters in between, when you take the difference, what does this mean? 11 - If you take 1 -1, how many have come, nine has come 11 - If you take 1 -1, how many have come, nine has come 11 - If you take 1 -1, how many have come, nine has come which is 1 2 3 4 5 6 7 8 9 If this is your answer then similarly you have to do for all the characters whose size is v off size whose v is off size less then One means if one came like c is one then we can't return anything in that case so whose less then one is less then two is sorry less than two then what will we answer directly to that -1 and at the end Our answer will be -1 and at the end Our answer will be -1 and at the end Our answer will be max. All the values ​​that we will extract from here are max. All the values ​​that we will extract from here are max. All the values ​​that we will extract from here are fine and we do not need to identify everything, we just short its a which is last, already it will be shorted through each index in vector of vectors, so we will Last one means v of n - 1 we will Last one means v of n - 1 we will Last one means v of n - 1 - of v of 0 means v of 0 of n - 1 and v of - of v of 0 means v of 0 of n - 1 and v of - of v of 0 means v of 0 of n - 1 and v of 0 then we will calculate the last and 0 of 0 then we will calculate the last and first and its difference is we will find out the maximum of our answer so friend this was its logic. Because it falls in this category, the time will seem complicated and your 300 is off, it is going to be so much that you can comfortably develop your own complexion. Now let's meet with the next question. Bye.
Largest Substring Between Two Equal Characters
clone-binary-tree-with-random-pointer
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
133,138,1634
239
lead code problem 239 sliding window maximum so this problem gives us an array of integers and there is a sliding window of size k and basically what we have to do is to return the maximum number in the window for returning as an array right so something like this that is a great example right so this window the maximum V3 so 3 is a Max same thing for this one three is a Max same thing for this one five is the max and so on until we get the answer of three five six seven okay so my approach to this problem is to use a DQ and this DQ is basically for pouring the largest number in every window in descending order and now and I'll explain why in a bit but let's say I pay DQ here and I'll just run through how my code run right so I'm going to use this example to multiply visualization okay so the first thing first I initialize the size of the nums array and I have a empty vector that I prepared the size for so basically if you use size which in this case would be let me come one two three four five six seven eight minus okay so eight minus three plus one this is this will basically give us this is five and six so six which is the number of answers right one two three four five six yeah basically gives us the size of the output that we need and the reason why I do this instead of using pushback which I also can't do is this will improve the performance slightly right because if I use pushback then your vector has to keep reconstructing something small but you can definitely use pushback for this and you'll be less then you don't need this so you can just do Press Start push back and then DQ front like this doing the same thing but I prefer it to do it this way because of the slight performance in Improvement and now we have the DQ which I mentioned that we will store the numbers the biggest numbers in s in descending order okay pull in the for loop I have an i let me initialize I so I was back from the beginning and iterated through till the end of the array so at the first iteration nothing happens this two while loop does not run because the DQ is empty and I'll just push back I right so I now is one okay this part is basically checking whether I which is not zero if mod or equal than two which is not right that means I has not reached the right side of the window yet okay the next part then we continue on right and now that our DQ is not empty we are checking whether or not this number oh sorry I'm pushing back the indexer a bit I'm checking whether or not this index is less than I minus K plus okay so what is I minus K plus one so uh remember I is not one so 1 minus three plus one this will be basically give us negative uh all and then negative three right so is this lesser than negative three yes right actually is this lesser than negative three zero less than negative three no right so we don't do anything and yeah we don't do anything and we look at the next option so if this is this number the uh we're using the index at the back of the DQ but for this case we only have one so this is what we only do and then we are comparing it against our current number which is three right so is one less than three and in this case it is right so in order to maintain adq where the biggest number is stored from the where the number is stored from uh in descending order we have to plot this index and then the new index which is one and this one basically holds the number three which is currently our biggest number right okay after that after we push back then we check again since I is now one and it's still not more than equal to two so you don't need to put anything inside our result array let me check again now is one lesser or equal to I'm okay since I incremented so it's one lesson that negative two it is right so we don't need to do anything actually it is not one is more than negative two right so we do not do so we do not need to do anything here okay after that we're comparing numbers again number from the back and checking whether or not this three is lesser than our current number which is negative one didn't say it's not right since three is still bigger we don't need to do anything and we push back I right so with my I so this tool is storing our negative point okay after you push back is now two that means that we have three uh valid window so our result uh this will give us zero because 2 minus three plus one this is negative one and then plus one equals zero so our result at index 0 will be the nums at the front which is in this case the index is one this will be one and in one it is three right so our result is three for the first index of that we go into this wall loop again incremental I first okay then we go into this wallet again in fact whether or not up or one is lesser than three minus three plus one in this case we want so it is not we don't do anything and this while loop we have to check whether or not uh the number at the back right which in this case is two hey sorry this case is negative one right value is negative one is it less than negative three so it's not right since it's not then we don't have to do anything and we push back negative three okay that means for our next window our current largest is still three okay so now it is like this recommend I need to check on this wall Loop is different is one less than four minus three plus one you know I'm going to simplify this to minus two and then I think one is now less than two that means we have to remove this right so what this means is that this three has now this tree has now left our window right that means we that means the current maximum of these two number is negative one right that's why we have to sort the DQ in descending order okay let me check on our wall Loop is this negative 3 lesser than nums I is now 5 right now side is not five it is right this negative 3 is 103 sorry to pop back 3 so we remove this and now we're checking whether or not negative one is lesser than five and it is 2 is so we say remove right remember when we moved we removed negative one and negative three in order to make space for D5 right so that means our DQ is still sorted in descending order right if we didn't remove it then we'll have uh negative then we have a five like and this is basically not sorted anymore so that's why I have to remove it okay after that again right since is this window now so we know that the front this is the only one number so the value is five let's increment to five and then I will increment to now look at this tree again we look at it we look at the index to see whether or not we have left the window so is 4 less than 5 minus three plus one so four is more than three right we don't need to do anything and next one we have to check again whether or not five is lesser than three and it's not so we don't do anything that means even if we push back this DQ is still sorted right then we do this again okay the answer is five three plus so we add in five again and then we repeat the same step right it's four lesser than is more lesser than this need to be incremented fixed or lesser than six minus three plus one this will be two three four and since four uh since this evaluates to false right Things fall it's not less than four yeah so we don't even do anything and here we have to check wait let me make sure this 4 Less Than I is 6 3 4 5 6. minus three plus one three so okay so our second one look we check again for that number at the back whether or not three is lesser than six and in this case it is right it is less than six we have to pop back I'm going to pop this back and now we're gonna check whether or not five to seven six and it is so here to pop this back and then only put in six okay and then we click the answer for this current window it takes okay same thing we found another it's inside our window it is so you don't need to do anything and here we're checking whether or not six is lesser than seven right the seventh and since it is to pop this back push in seven and then check the answer again and put X Out of that our eye to increment to eight and basically get out of this basically has finished iterating through the entire list and when that happens we return the result which is this right result equals 3g5x67 and if you look at the output for the example given it is the same okay that's all I have to show thanks
Sliding Window Maximum
sliding-window-maximum
You are given an array of integers `nums`, there is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position. Return _the max sliding window_. **Example 1:** **Input:** nums = \[1,3,-1,-3,5,3,6,7\], k = 3 **Output:** \[3,3,5,5,6,7\] **Explanation:** Window position Max --------------- ----- \[1 3 -1\] -3 5 3 6 7 **3** 1 \[3 -1 -3\] 5 3 6 7 **3** 1 3 \[-1 -3 5\] 3 6 7 ** 5** 1 3 -1 \[-3 5 3\] 6 7 **5** 1 3 -1 -3 \[5 3 6\] 7 **6** 1 3 -1 -3 5 \[3 6 7\] **7** **Example 2:** **Input:** nums = \[1\], k = 1 **Output:** \[1\] **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` * `1 <= k <= nums.length`
How about using a data structure such as deque (double-ended queue)? The queue size need not be the same as the window’s size. Remove redundant elements and the queue should store only elements that need to be considered.
Array,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
Hard
76,155,159,265,1814
1,046
hello everyone so today in this video we are going to solve question of lead code that is last 200 this is 1046 question need code and this comes under easy category all right so let's start with the problem statement you are given an array of integer stones where stone i is the weight of it stone you are playing a game with the stones on each turn we choose the heaviest two stone and smash them together suppose the heaviest two stone have weight x and y where x is less than equal to y the result of this is smash is x like there are two condition if both the weight of the stones are equal then both the stones are destroyed if the weight of both the stones are not equal then the stone of red weight 8x is destroyed and the stone of weight y has a new weight y minus x so basically the stone with lesser weight or we can say like in this condition we have taken x is less than equal to y so if second case is true that is both are not equal so x is definitely less than y so the stone with lesser weight is destroyed and the stone with heavier weight is updated with the weight y minus x alright so these are the two conditions which we need to check in each iteration and at the end of the game there is at most one stone left return the smallest possible weight of the left stone if there is no stone left written zero all right so let's take the first example in the first example we have two seven four one eight one so let me take this example here so in the first example we have two seven four one each one so let's choose x and y all right so x is equal to one y is equal now let's choose x and y in this error so x and y we need to choose such that both the stones are heaviest in the ring so the heaviest in the array and we need to choose the such that x is less than equal to y all right so let's choose the two heaviest stones in this arrays seven and eight and we need to choose such that x is less than y so x will be 7 and y will be 8 now we need to check two conditions if both are equal then both the stones are destroyed in this case both are not equal then second condition is 2 that is x is not equal to y so the stone of weight x is destroyed and the stone of weight y has new weight x minus y minus x so this stone is destroyed and y will be updated to y minus x that is one all right so it is updated to one and seven is destroyed now let's check for other conditions now at this point of time there are two heaviest stone in this array that is two and four so let's update x to two and y to four now the second condition is again true so let's destroy x and update y two four minus two that is two so let's destroy two from here and update four to two now let's check the two heaviest stones again so two heaviest stone is two and one so let's update x to one and y two now again the second condition is true so let's destroy x and update y two x minus y minus x so 2 minus 1 is equal to 1 so let's just try one from here and update 2 to 1 now let's check in the remaining array now the two heaviest ones are one and one so let's update x and y two one and one now the first condition is two that is both are equal so both the stones are destroyed so let's destroy both the stones from here and at the end only one stone is remaining in there when one stone is remaining in the array let's directly written that stone all right so i hope the approach is clear to you so let's quickly code it up this is basically uh like we need to check the two heavy stones so to check the heaviest stone the approach which we are going to use here we will be using a priority queue is a type of data structure which store the heaviest element or we can say the largest or greatest element at the top of its view all right so let's take a small example here again and we will be understanding how can we use a priority queue here all right so let's take we are taking the same example again and x and y are same all right so let's let me make a priority queue here so what will happen in the priority queue it will always give the topmost element as the greatest element all right so let's say we are taking x as the top most element so topmost element would be 8 because it is greatest in the array so x will be 8 and y will be equal to let's say it is 7 so it's 7 let me just interchange x and y because according to quotient that is given x is less than equal to y so let's just interchange both of them so this will be x and this will be y all right so let me just code simultaneously so it would be more clear so what we will be doing we will be making a priority here so let's make priority q here of integers and let me name it q and let's update the element let's add the element of stones arrangements particular systems dot begin and stones dot and alright now what we will be doing in each iteration we will be checking the two topmost element all right so let's run our while loop until q dot size is greater than one because at the end at most one stone must be there all right so let's keep our element into the um q all right so what we will be checking here is let's take two integers in y is equal to q dot we are taking y first because the condition here is that x is less than equal to y so y must be greater here so q dot and let's pop it out from the queue and let's take another element in x is equal to q dot top and q dot pop now let's check if x is does not equal to y then we will be updating y to y minus x and let's push it into our let's first let's update y to y minus x and let's push it into our u so q dot push y all right so at the end what we will be doing we will be returning if you lost size is equal to 1 then we will be returning q dot top otherwise we will be returning 0 as it is given the smallest weight we need to return from here if no stone is left then we'll return zero so this is we are returning here so let's just run it yeah it's working fine so what we are basically doing here is that we are taking two elements y and x as our top most element because let's say we have taken y here so this in this statement y will be such that it is the greatest element or we can say the heaviest stone in this area so let's say we have taken the top most element of the cube that is 8 now the 8 is popped out from here now in the second statement x will be equal to the top most element so in this again it will be returning the greatest element out of this area so greatest element is 7 so 7 is popped again so x and y will be such that the greatest element now x and y is not equal so y will be updated to 8 minus 7 that will be equal to 1 now 1 is again pushed into our cube so one will be again pushed in the array all right so similarly this will this loop will go again and again until q dot size is greater than zero at the end q size will be equal to zero as we have seen few minutes earlier so at the end the area will become something like this or we can secure will become something like this and this will come to this return statement and it will return one from here all right so i hope the approach is clear to you it's running fine let's submit it's fine so let's calculate the time and space complexity of our solution so the time complexity of our solution is big o of n log of n because priority t q takes around n log n time complexity as it is solving the vector internally and if space complexity of our solution is big o of m because we are storing all the n elements into our queue and it is taking extra space here so i hope that don't just create and solution is clear to you if you still have an order this question feel free to comment down please like this video subscribe to our channel thank you
Last Stone Weight
max-consecutive-ones-iii
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone. We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is: * If `x == y`, both stones are destroyed, and * If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`. At the end of the game, there is **at most one** stone left. Return _the weight of the last remaining stone_. If there are no stones left, return `0`. **Example 1:** **Input:** stones = \[2,7,4,1,8,1\] **Output:** 1 **Explanation:** We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then, we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then, we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then, we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone. **Example 2:** **Input:** stones = \[1\] **Output:** 1 **Constraints:** * `1 <= stones.length <= 30` * `1 <= stones[i] <= 1000`
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
Array,Binary Search,Sliding Window,Prefix Sum
Medium
340,424,485,487,2134
1,675
hey everyone welcome back and let's write some more neat code today so today let's solve the problem minimize deviation in Array this one is going to blow your mind so we're given an integer array maybe something like one two three four the rules are pretty simple this time if a number in the input array is even then we can divide it by two we don't have to but we can if a number is odd then we can multiply it by two but we don't have to now our goal though is to minimize the maximum deviation the deviation is defined by taking the minimum element in the array and the maximum element in the array and getting the difference between those which in this case is four minus 1. now if you read this problem they describe the deviation differently but I think they're trying to make it more complicated to confuse you they say it's the maximum difference between any two elements in the array that makes it sound like you have to compare every two elements in the array you don't have to you just need the minimum and the maximum now even knowing that this problem is still pretty hard because there's so many things we could do at least that's what it seems like we have a one here so we can choose to multiply it by two we could take this even number divide it by two we could take this odd number and multiply it by two this even number and divide it by two and after we do those operations maybe we can do even more operations so how do we figure out how to minimize the maximum difference well obviously US changing maybe like the two or the three that's probably not going to decrease the difference between one and four if anything that'll end up increasing it maybe if we make this a bigger number like five or something then the maximum difference is even bigger so probably we want to operate either on the minimum or on the Mac maximum so that's one observation and this is probably the trickiest observation that you have to make there's a pattern to how we can multiply and divide these numbers let's take this odd number we can only multiply odd numbers by two so now let's multiply it by two what do we get a 2. let's take this odd number three and multiply it by two what do we get a six any number whether it's odd or even multiplied by two is going to be an even number it's kind of in the definition it's going to be divisible by two I mean two is clearly a factor of whatever number this is going to be this is not really programming this is just math so what we learned is any time we take an odd number the only thing we can do with it is multiply it by two and then we can't do anything with it ever again so for every odd number the a range of possible values that this could be is going to be either one or two for the three it's going to be either three or six now things get a little bit different with the even numbers with even numbers remember we divide them by two what happens with two we divide it by two we get one can't really divide it any further it's an odd number now so now the only thing we can do is multiply it by two what happens when we multiply one by two we get two well that's what we had over here so the possible range of values for this guy is actually the same as this guy what about the four when we divide it by two we get two divide it by two again because it's still even that's all we can do we get one now is there going to be a pattern with even numbers not necessarily because if we get an eight we can divide this by two four times and if we get a 16 we can divide that five times and we can get a 32 and then divide that so with even numbers we could get a long chain of Divisions but take a look at the list they're still going to be discrete like it's not going to be infinite they're going to end at one or before that actually for example a number like six divided by two we get three can't divide it any further it's an odd number now we can multiply it by two and get back to six but other than that can't really do anything the point is that each number has a defined list of values that it could be given these rules now on top of that we have to make another key observation here and that is that each of these numbers there's a possible set of values it could be we know that all these numbers are positive so the lowest possible value let's say they could be is one but there is some upper bound here and there is a max value for the integers in this input array it's something like 4000 or something like that so it isn't like a massive integer but let's just say this is like n or some Max integer this guy is going to have a range of possible values in this case it's one and two is also going to have a range of values that just happens to have the same range of values three is also going to have a range of values I believe it's going to be three and six four is going to have a range of values I think it's four two and one so when we visualize it as a number line it becomes a bit more simple not super simple but a slightly more simple because now we're just trying to minimize one of these but actually not necessarily one of these because for any possible set like we need to include all four values because remember what we were trying to do is get the difference between the a minimum and the maximum so we can't just say okay get the minimum between these two because we need all four values for example uh maybe this because this includes all four colors so in this what is the minimum difference but I guess even like this it's kind of hard to solve how do we compare every pair of values and how do we know if all four values are in a set this isn't simple either but since we know that every value will have some type of lower bound why don't we take every initial value and try to minimize them what I mean is if this is the initial value for four let's try to minimize it as much as we can try to push it all the way over there as we can and let's do the same thing for purple well purple is odd so we can't minimize it we can increase it but can't minimize it so we'll leave this here and with green we can minimize it once and with red we just leave it there because it's odd so we don't want to maximize it so we leave it there so quickly I'm going to take this red put it over here that's the minimum take this orange and also put it over here that is the minimum now among all of these minimum values how do we find the maximum difference well we would just take the maximum and the minimum in this case we can choose from any of these and then get the difference so here I think it's going to be 3 minus one which is going to give us two but how would we do that because we still have an array of 4 or n elements and to find the Min and the max is going to be a linear time algorithm so can we do it faster yes we can what we're going to do is we're gonna keep track of the maximum value we're going to have a separate variable for that and every value meaning every value like in the array once we've taken each of these and minimized it is going to actually be pushed to a heap specifically A Min Heap because if we're keeping track of the maximum then we can just pop to get the minimum or just look at the top of our Heap but we're going to want to pop because we specifically want one of these minimum values because just like I talked about at the beginning the only way we're going to decrease the maximum difference is by changing either the maximum value or the minimum value we already took the maximum value and tried to make each of these as small as we possibly could so we can't really take any of them and make them smaller but we can try to take the minimums and make them bigger that's what we're going to try to do so since all of these are the same size we can pop any of them but what we're going to do is pop one and then multiply it by two because odd numbers can be multiplied by two so then the Orange is going to go over here but we're still gonna end up popping from the minimum our maximum is not going to be changed it's still going to be three but we're going to be popping from here and for each of these two we're going to do the same thing pop each of them and then multiply it by two same for this guy pop it and multiply it by two now we get to a point where we have three of the values over here and the last one is over here now we're gonna pop one of these and we're gonna get a new minimum difference because these are now at two and our maximum so far is at three the difference between them is going to be one so that's going to be our new minimum and we're going to keep continuing this algorithm until each of these guys is at its maximum possible spot so for the green one we know it was two so it's gonna end at two for the one it started at one but odd numbers can be multiplied by two so it's going to end here at the two value because then with an even number we can't really multiply it by two we have to divide it by two and then we're just gonna get stuck in an infinite Loop so we're not going to do that and finally with the orange one it actually started at four so if we multiply it by two we're gonna get two but with a two value we can't multiply it by two again but that's a problem because it's possible that we'll miss an answer because two was four that's its original value it should be able to get back to four so I'm gonna take care of this in the code but I think this is probably getting really complicated at this point so I'll just make a couple more points the most important one is how long are we going to continue this until the Heap is empty maybe no we're gonna continue this until the Heap is less than the original size of the array let me show you why let's say this red value one it's originally one but we end up multiplying it by two and then it gets over here to the two spot and then it can't really go any further so maybe it is the minimum value maybe we popped all of these and maybe there's some values over here but then we want to pop this guy as well we pop it and we see we can't do anything with it so we're not gonna push it back to the Heap so it's not gonna be on our number line anymore so now should we continue we only have three values left on our number line we should not continue let me tell you why we're trying to take the difference between the Min and the maximum in the entire array we can't just choose to selectively ignore values that wasn't part of the rules so if we just ignore this guy We're not gonna get the correct answer potentially so at this point we would stop our algorithm but is it possible we're gonna miss a solution because we're stopping too early definitely not because remember we took all our values pushed them as far left as we could and now we're trying to push them to the right by prioritizing the minimum values and we found a minimum value we can't push to the right anymore maybe we can keep pushing these guys but this one is stuck over here so if we take this push it over here maybe then to find the maximum difference we would have to take this and subtract this one so it would basically be like this so clearly as we push these guys to the right we're not going to be decreasing our maximum difference we're going to be possibly increasing it so we're definitely not going to miss a solution by doing it this way this has gotten really complicated so I'll talk about the time complexity after we code it up which is going to be now so first I'm going to initialize our Min Heap and I'm going to keep track of what the maximum value is in our Heap so initially I'm just going to set that to zero but remember that's going to be important for actually finding the maximum difference next I'm going to initialize our Heap but remember how we're doing it we're going through every number in the input array but before we can append n to the Heap we have to try to minimize it we know that odd values can't really be minimized because we can only multiply those by two but if a number is even which we can check just like this then we're going to divide it by two so you can do that like this in pi Python and then we're gonna append it to the Heap but remember that catch I was talking about when we take a number like two and then divide it by two we get to one when we take a number like four and then divide it by two we get to two then we can divide it by two again and we get to one now these are the minimum for each of them but we should be able to take one and multiply it by two to get its original value we should be able to do the same for this one multiply it by two and get to two but at this point we would stop because usually with even numbers we don't multiply them by two but we know that this one had an original value of four we should be able to get back to that if we want to find the solution so we're going to actually keep track of every numbers original value so when we append n to the Heap we're actually going to append two values we're gonna append a pair n and its original value which I'm gonna get by saving it in a temporary variable called temp so now we're gonna append temp here but we actually have a problem here as well believe it or not because what about if we just started with a value of one in this case with our Heap we would append one and the temp which is its original value which is also one but we know a one odd numbers can be multiplied by two to get to an even number so with one we would want to actually hear append two times temp so here we would actually want to append two times the original value if it remains unchanged which will always be the case for odd numbers that's why we're taking the original value so here instead of appending temp I'm actually going to append the maximum of Temp and the original value multiplied by two anytime we have an even number we're going to end up dividing it by two at least once so this will end up appending to as well as temp but if we have an odd number it's never going to be divided by 2 in that case it's going to end up appending n as well as 2 times n that's kind of the maximum it will ever be pretty complicated stuff but this is a leak code hard for a reason so now let's get into the actual Heap oh I forgot up above we are going to be getting our heat Max as well the best way to do that is just to continuously get the max of itself as well as whatever current number we're at and we do want n in this case because we actually want what value is in the Heap we want the actual value in the Heap that's what's going to be used as the Heap key so now let's initialize our result I'm going to set it to a really big number because we're trying to minimize it and then when we created this Heap we actually didn't make it a heap it's just an array right now so to turn it into a heap we can say Heap Q dot heap of Phi run that on the Min Heap now we're actually ready for our Loop remember we're not doing this while the Min Heap is non-empty we're while the Min Heap is non-empty we're while the Min Heap is non-empty we're doing this while the Minh Heat is the same length as the input array nums and then we're going to pop from it so Heap Q dot Heap pop from the Min Heap and the values we're going to get from it are n and the maximum that this value can possibly be that pair of values that we ended up adding every time we pop a value we want to possibly update our result we already know what the max is we are saving that in a variable and we can subtract from an n and it's possible that this will be a new result we'll only know if we take the minimum of the current result and this and possibly update it now every time we pop a value we possibly want to append two times that value back onto the Heap but we're only gonna do it if the max possible value of it is actually greater than the current value that means we can multiply it by two so we're going to check exactly that if n is less than its possible maximum then push to the Heap that value n multiplied by two but don't forget we have a pair of values on that Heap we're not just storing a single value so let's make this a pair we're going to store the original value multiplied by two that's the first value and the second value is just going to be what its Max was that's not going to change the maximum it's allowed to be is not going to change so we're just going to append the same value though it's possible that now we have updated our maximum if we're appending two times some value it's possible that the heat Max is now an even greater value so let's possibly update it with n times two so now our Loop will keep running until we pop an element from the Heap for good and at that point we can't come up with a better solution so we will end up returning our results so now let's run the code to make sure that it works and as you can see yes it does and it's about as efficient as you can get but don't let the leak code runtime confuse you in terms of Big O time complexity this Loop over here is going to run in Big O of n let's say n is the number of elements in the input array appending here we're just appending to an array so that's not going to take any time complexity but here we have a while loop now how many times can you take a number and divide it by two until it equals one well that is the logarithm function but we're not going to be log ending because n is the size of the array here we would uh say log maybe M where m is like the max possible value in the input array nums so for a number like 16 how many times can you divide that by two I think it's four or five so log of 16 would be something like four or five the time complexity down here though is a bit different because even though the size of our Heap is always going to be n and popping from a heap of size n is going to be log n how many times are we going to pop from it are we going to pop n times that would be n log n not necessarily because we might take the same value pop it from the Heap and then push it back how many times are we going to push it back well same number of times as this in the worst case at least when we take a value and keep dividing it by two then in the opposite case we're going to take that same value and keep multiplying it by two so here the time complexity for the number of times we're going to pop and push from the Heap is going to be n times how many variations of that value we had so n Times log M Times log n is going to be the time complexity here kind of confusing this is the bigger term so we pretty much just ignore this one so this is the time complexity memory complexity is Big O of n because of the size of the Heap if this was helpful please like And subscribe if you're preparing for coding interviews check out neat code.io it has interviews check out neat code.io it has interviews check out neat code.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
Minimize Deviation in Array
magnetic-force-between-two-balls
You are given an array `nums` of `n` positive integers. You can perform two types of operations on any element of the array any number of times: * If the element is **even**, **divide** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].` * If the element is **odd**, **multiply** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].` The **deviation** of the array is the **maximum difference** between any two elements in the array. Return _the **minimum deviation** the array can have after performing some number of operations._ **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 1 **Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1. **Example 2:** **Input:** nums = \[4,1,5,20,3\] **Output:** 3 **Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3. **Example 3:** **Input:** nums = \[2,10,8\] **Output:** 3 **Constraints:** * `n == nums.length` * `2 <= n <= 5 * 104` * `1 <= nums[i] <= 109`
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
Array,Binary Search,Sorting
Medium
2188
797
today we're going to be solving lead code problem 797 all paths from source to Target before we go you guys know the drill please like the video and leave a comment helps me out a ton with the YouTube algorithm all right given directed acyclic graph a dag of end nodes labeled from 0 to n minus 1 find all possible paths from node 0 to node n minus 1 and return them in any order the graph is given as follows graph of I is the list of all nodes you can visit from node I IE there is a directed Edge from node I to node graph i j so let's look at a basic example we know that we want to start from the node 0 and we want to end at whatever node uh n minus 1 is so here it's going to be node for so we want to start at zero and we want to go to four so what are all the possible ways we can go there well we can start at zero we can go to one and then go to four so that's one because we have that connection so that's one total we could start at zero we could go to one we could then go to three and then four so that is another one so now we have two total we could go from zero to one to two to three to four so that's three total and then what we could do is we could also go from zero to three so that is four total or we can just go from zero to four directly so that is going to be a total of five different paths right pretty simple um essentially we just want to you know Traverse our graph and see how many ways starting from zero we can end up at four we don't have to worry about Cycles because as the problem tells us it's a dag which means that there are no cycles and all we have to do is do a simple DFS here but because we need to generate all the possible paths and basically at One path we can actually you know diverge we can either at this one go to the two or the three and we have to generate all those paths this actually tells us that we need to use backtracking here so we're going to be using depth first search with backtracking to basically uh generate all the paths because at the one we could take a three and then go to the four or we could do the two and then go to the four we basically have to try all the possible options from all the possible nodes and backtracking is the perfect way to do this so that's essentially what we're going to do first is actually build the graph because it's just given to us as a list so we need to actually build the graph um and you know this is quite simple we'll have a vertex and then we will map all of the other vertexes that you can actually um you know reach so basically all the places has an edge to and then from there we can Traverse this graph and then um you know basically build all of our uh paths using um backtracking so that's what we're going to do let's now go to the code editor and type this up it's relatively simple we just have to build a graph and apply our tried and tested uh backtracking template so I'll see you there we are back in the code editor let's type this up so we know that we need to build a graph from our kind of list here right so what we're going to do is we're going to say self.graph and do is we're going to say self.graph and do is we're going to say self.graph and this is going to equal to collections dot default uh dict and we're going to pass in a list here right because for every vertex we want to know all of the other vertexes we can reach uh from there so now what we want to do is actually build the graph so we're going to say 4i Edge in enumerate um graph remember that I um represents the node and then Edge represents all of the um the values that we can actually reach from our current uh I node so we're going to say self.graph of I and we're just going to self.graph of I and we're just going to self.graph of I and we're just going to set this equal to edges um now what we want to do is actually Define our results so we're going to say res just gonna be an empty list and now what we want to do is we actually want to Define our DFS function which is going to do the depth first search so let's just say def DFS and this is going to take our current path and it's going to take our current node right so what we want to do now is we essentially if we've reached the end of the graph which is essentially you know however many nodes we have minus one um then we know that we've actually reached our destination so we're going to say if the current node equals to Len of self dot graph um minus one so remember that we want to get to node n minus one so Len of graph minus one will give us whatever that note is so if the current node if it's that node then we just want to stop because we're actually finished so we want to say res dot append and since this is backtracking we need to say list of curve paths so basically we just need to make a copy because we don't want to accidentally overwrite things when we actually exit out of our DFS because the curb hop is actually shared between the invocations uh it will give us problems if we don't do this so um otherwise what we want to do is we want to say for Connection in self.graph want to say for Connection in self.graph want to say for Connection in self.graph of the current node uh what we want to do is we want to say the current oops current path so we want to add that new node that we're going to be visiting so we're going to add that connection node and then we're just going to call DFS on our current path and the current node is now the connection and then at the end once we finish our DFS we obviously want to get rid of it oops current path dot pop so we're going to pop our current node that we just appended so that way we can start clean on the next iteration of our for Loop that is the DFS function now what we want to do is we simply want to call DFS um starting from you know where we are so where do we start obviously we start at the zeroth node so our path will start at zero and what we want to do is the current node is also going to be zero right so we're going to call that DFS function and the last thing we need to do is simply return our result so once we do that we should be good to go I just want to run this make sure I didn't make any syntax uh Edge it of course I did okay edges for eye edges okay there we go that's why we run this and now we can submit and accepted perfect so let's now talk about the time and space complexity here so when we are traversing our graph we essentially whenever we have a node um we basically have the option for each one of its um connections whether or not we actually want to go down that path right so we can either go down the path or we cannot go down the path so essentially this means that there's two choices for every single node we reach which means that our time complexity is actually going to be Big O of 2 to the N to actually go down all the possible paths in our tree so to Traverse the tree is going to be you know two to the N um which actually you know go and find all the paths but remember that we actually need to call list on our current path which will require a copy and that's going to be Big O of n as well so our time complexity is going to be Big O of 2 to the N times n and for the space complexity we just need to store our graph here and because this is a dag and there's no um Cycles here um we can basically say that our space complexity is going to be Big O of N and then also we have to store um you know the results here so that's going to be also dependent on um the input so our time 2 to the N times n and our space is going to be Big O of n so that's how you solve this problem again pretty common uh thing on Lee code is you're given a graph in the form of like a list of lists you need to build the graph using some sort of dictionary typically we use a you know default dict with a list as the values and then you build the graph and then you perform some sort of depth first search this time we were doing in-depth search this time we were doing in-depth search this time we were doing in-depth first search that was really a backtracking and then you get your answer so very various common pattern only code definitely one to know especially like how to build the graph and then your DFS function that's going to vary from question to question but usually this is what you're going to get in most medium questions where you're given your graph like this so if you enjoyed the video please leave a like and a comment it really helps me out with the YouTube algorithm if you want to see more content like this then subscribe to the channel I have a ton of videos and I plan to make a whole lot more if you want to join a Discord Community where you can connect with like-minded people and chat about all like-minded people and chat about all like-minded people and chat about all things Fang systems design interview prep you can have your resume reviewed by me you can ask for referrals if that sounds interesting to you then please join the Discord I'll leave a link in the description below and I hope to see you there so otherwise thanks so much for watching and I'll catch you in the next one
All Paths From Source to Target
rabbits-in-forest
Given a directed acyclic graph (**DAG**) of `n` nodes labeled from `0` to `n - 1`, find all possible paths from node `0` to node `n - 1` and return them in **any order**. The graph is given as follows: `graph[i]` is a list of all nodes you can visit from node `i` (i.e., there is a directed edge from node `i` to node `graph[i][j]`). **Example 1:** **Input:** graph = \[\[1,2\],\[3\],\[3\],\[\]\] **Output:** \[\[0,1,3\],\[0,2,3\]\] **Explanation:** There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3. **Example 2:** **Input:** graph = \[\[4,3,1\],\[3,2,4\],\[3\],\[4\],\[\]\] **Output:** \[\[0,4\],\[0,3,4\],\[0,1,3,4\],\[0,1,2,3,4\],\[0,1,4\]\] **Constraints:** * `n == graph.length` * `2 <= n <= 15` * `0 <= graph[i][j] < n` * `graph[i][j] != i` (i.e., there will be no self-loops). * All the elements of `graph[i]` are **unique**. * The input graph is **guaranteed** to be a **DAG**.
null
Array,Hash Table,Math,Greedy
Medium
null
408
hello welcome back today we have leeco 408 valid word abbreviation so in here is a really long uh description but basically the idea of this question is we'll receive two string one string is called word and another string is abbreviation so we can go through this example here like the abbreviation is as 10 and so we have s matching s so whenever we see uh numbers we just keep 10 character in here after skipping 10 character and we're going to have end right here so substitution in here will totally matching this abbreviation same thing here sub 4 u 4. so that is the correct i mean you return true by that case example one here same thing word is internationalization operations like i and then we skip 12 character up to here and i z and then four and then last character is n so they will totally match uh exactly matching for this two word and that case is return true i mean you can go through this example again um because this doesn't match pp's after the and then we have le left but he doesn't have e so return false it's pretty straightforward by having two pointer in here and whenever we see uh a number then we just skip the first pointer by 12 in here and we just keep looping until the end of the string at the end if they both of them at the last i mean position of the string then that two word is match another little tiny edge case is we cannot have zero leading right here so that case um we will have to take care of that edge case and give me one second so now i think we will just go through the example and just write the code right away we know we have to have two pointer eight link sign from zero b link which is the second pointer sign from zero like if either of them equal to no then will return false that's one of the edge case we're gonna take here next one is another while loop so while eight lane and building is still within this laying of word and aberration like in this case indicate we have to do something so now we know the abbreviation here is the string that will contain the digit so we have to have a condition saying character is digit uh did legit what we're gonna check is abbreviation dot character at feeling which is b position if b position is a digit then we need to capture that digit but first we have to take care of this leading zero error so if apr dot character i mean that character cannot be zero so if it is zero then we turn false no leading zero so that case take care of it already and then we need to accumulate this uh number here so now we have five we capture five after five we have another five we'll time ten and add another five in there so by adding this we need to capture all this b-link position b-link position b-link position that has the character i mean digit while b playing less than a pbr dot bling and character dot s digit so if the current location is a digit then we need to add total time 10 so that will accumulate multiple digit plus abbr dot character at feeling minus zero what it means like if zero is right now total is zero right now then we add 0 times 10 plus 5 i mean this is the current digit right here plus 5 so now total is equal to 5. next time we see another 5 we will have totals equal to 15. 50. so we time 10 to add the zero here after here we have this digit to save it for another five so we equal to zip t plus the current digit which is 5 then equal to 55 and then just keep adding and ending after this we need to increase the b link by one by moving the billing to the next digit after this while loop will capture the whole digit which is in the total and what we're gonna do is eight link um plus equal to total okay so by pushing a link plus total will kind of cancel out this purpose like move the digit right here this is one character digit in v link is i mean it's digit if they're not digit then we need to check if word dot character at eight link not equal to abbr character at b lane in that case return false because they're different let's say if i is here and i is here if they're different we really know it's not good at that case it will return false if not it did the same we need to move eight lane and b link by one step after this the while loop is done the last thing we need to check if make sure eight lane and beetling is the end of the string they have to reach the end of the string in order to prove them exactly the same so we turn a link equal to word dot name and b link equal to the link so check them if they're the same at the last step so by that we just need to run the task and submit it so good yeah and then it looks really good and it passed this is pretty straightforward and just put them down because it's kind of to understand it at the point that if this one in it happened to be one of the individual questions might spend a lot of time by explaining asking all the edge cases understanding these edge cases that's why i don't think this is a good question in the interview but it happened and that's it i will see you in the next question bye
Valid Word Abbreviation
valid-word-abbreviation
A string can be **abbreviated** by replacing any number of **non-adjacent**, **non-empty** substrings with their lengths. The lengths **should not** have leading zeros. For example, a string such as `"substitution "` could be abbreviated as (but not limited to): * `"s10n "` ( `"s ubstitutio n "`) * `"sub4u4 "` ( `"sub stit u tion "`) * `"12 "` ( `"substitution "`) * `"su3i1u2on "` ( `"su bst i t u ti on "`) * `"substitution "` (no substrings replaced) The following are **not valid** abbreviations: * `"s55n "` ( `"s ubsti tutio n "`, the replaced substrings are adjacent) * `"s010n "` (has leading zeros) * `"s0ubstitution "` (replaces an empty substring) Given a string `word` and an abbreviation `abbr`, return _whether the string **matches** the given abbreviation_. A **substring** is a contiguous **non-empty** sequence of characters within a string. **Example 1:** **Input:** word = "internationalization ", abbr = "i12iz4n " **Output:** true **Explanation:** The word "internationalization " can be abbreviated as "i12iz4n " ( "i nternational iz atio n "). **Example 2:** **Input:** word = "apple ", abbr = "a2e " **Output:** false **Explanation:** The word "apple " cannot be abbreviated as "a2e ". **Constraints:** * `1 <= word.length <= 20` * `word` consists of only lowercase English letters. * `1 <= abbr.length <= 10` * `abbr` consists of lowercase English letters and digits. * All the integers in `abbr` will fit in a 32-bit integer.
null
Two Pointers,String
Easy
411,527,2184
81
hey what's up guys this is sean here so today let's take a look at the today's daily challenge problem number 81 search in rotated storage array number two so actually this one is like an extension of the uh searching rotate this rotated sorted array number one basically you know the only differences for this one is the it allows a duplicate numbers but let's try to refresh our memories about how can we solve it without a duplicate without duplicate numbers and so you're given like a sending a sorted array with it which is rotated at some pivot point unknown to you beforehand and it asks you to find the target okay so if we have a sorted number a sorted array here let's say we have a one two three four five six seven eight and nine so even if it's been rotated somewhere here for example if this one if instead of that we have seven eight one two three four five six right let's say we have a we have this example here right and still we need to use a binary search but to search this one we have to uh so the idea for this kind of rotated rotate like uh array here you know i mean the first option is we can simply find the pivot point right i mean that's similar like finding the uh a mountain right so we can do a another two binary search um on those two sides let's say we find like the pivot point at this location we can simply do a two binary search first one search from one to seven and then search from a to nine right but the time complexity for that is the we're gonna have like what to find the pivot point it's gonna take us o in time to find it and then we have a two with then we have two like log n search right that's definitely one options and the other options we can definitely just apply the direct the binary search directly but to do that is we're gonna need to check a few some few more conditions so every time when we have a middle point you know since the uh since the array is different since the rate could be rotated so the first thing we need to do is that we have to check from this middle point which side is sorted right and for example like let's say we're looking for five in this case right let's say we're looking for five and then the middle point is one two three four i think it's some somewhere here right that's the middle point and once we're at this middle point here we just need to check which part is sorted so how can we check which part is sorted right i mean we can either compare it with the right pointer where we can compare with the left pointer so let's say for example right now this is a left this is right let's say we use the left pointer to check which part is sorted and we compare this middle point this is the left pointer so remember it's a left pointer it's not the first it's the first number because we're trying to sort the current left to right if the current one is greater it's either is either equal or greater than the left pointer numbers and then we know okay the left side is sorted out otherwise the right side is sorted right and then once we have a sorted parts we'll just um and then we'll do we'll try to search in that part basically you know if the target is within this sorted range here right and then we know we can simply follow our follow the binary search rules to just the for example this one right we know okay so the right side is sorted and then we just go to the uh we'll just go to the we'll go to the right side and then we see okay five is right is it in between this sorted right the right sections here so we can simply move our pointer to the middle plot middle plus one the right sorry the left pointer to the middle plus one else we just need to go to the left side right for example if we instead of searching five here let's say we're searching eight right let's say we're searching eight here you know so even though the uh the right side is sorted but eight is not in that range so that's why we have to go to the left point the left side so same thing for the uh for the left part to be assorted okay all right so let's let me try to uh implement these things here you know maybe i'll try to explain a bit more there so we have numbers there like i said so we start from zero right and then right equals to m minus one right so templates is very similar let right while left is equal or smaller than the uh the left pointer right then we have middle equals to left plus right minus left divided by two right so the best case scenario is if the number middle is equal to the target right then we simply return true right so now we check okay if the nums of left pointer is equal either equal or smaller than the middle karnaughs the middle one so we do what we do is we need to do a equals check here because you know the left and middle could be the same right will be the same numbers all right so here like the left side it's sorted right and then if the left side is sorted then we can have like we can have a simple check here basically you know if the numbers of left is equal smaller than the target and within the range of the of within the range of this middle this is a sorted array then we know okay we can just we can safely put update the right pointer to the middle minus one right else it's not there and then it has to be on the other side right which is the left equals to middle plus one so we're doing this like uh less or equal to the left but only lies to the right side because for the middle point we have already checked that i mean if the target equals the middle it will simply return so there's no need to check uh check the uh the equal sign here right so that's that you know and else right else is like the similar thing right so else is the right side it's sorted right so basically we just use this assorted to help us to fix one scenario and then the house of course is the other scenario because this one okay so same similar thing right so for the right side and if the uh the nums of middle right smaller than the target then the uh the nums of right uh sorry this equal sign right then we know okay left it's gonna be middle class one and also we're gonna be a right that middle minus one so the reason we're doing this is because you know we because we know the rules for solid how do we find uh how do we move this pointer in a sorted array that's why for this kind of like complicated cases here we're gonna going to transform it into us into a case that we know how can we how to solve it and then we just use that as a base case which is the we find the uh the sorted parts and then within the sorted parts we know that if the target is within that sorted parts and then we and we can tell we know we saved it safely to just uh update the right pointer or the left pointer and for the other case we simply do after update the other half okay and that's that so in the end we simply return the uh return fast right if none of those if we never find a match okay yeah okay sorry about repeating myself i think i just want to emphasize this condition here because the uh only when we find assorted parts then we can use this range check here right because if the if this part is not sorted we can we simply cannot do a ring check right we only do a we can only be sure to do a range track here we when this part when the left to middle is sorted then we know if target is within this range then we know it has to be in that range right and then we uh if it's not there then it has to be on the other side we so we basically repeatedly doing this kind of stuff for the same for the left sorted array and for the right sorted array cool so this thing it will it'll work for the case where there's no duplicate numbers but for this problem for this question there is like a special case right so it allows duplicate numbers but for duplicate numbers we'll have an issue here so why is that let's say we have a one three one let's see that's the case and the middle point is one right as you guys can see here if we just follow the same logic here you know the uh so the middle point one is one and we see okay so one is smaller equal smaller than the left part right then it will assume okay so this part is sorted it will just follow that sorted logic it's going to be follow the uh assuming this is sort of the rate and they will try it will try to find the target within that range but the truth is it is not assorted right because we have one three and one so that's the uh that's the issue we need to fix here and so the easiest way to fix it is just it's like this right i mean before doing this kind of check here we just need to move either the left pointer or the right pointer to a place that is not equal to the middle point then we can we have we can convert this problem to a nine sorted to a non-duplicated number problem right to a non-duplicated number problem right to a non-duplicated number problem right something like this so while left is smaller than the middle right and what and the uh and the nums left is equal to the nums of middle then we simply move this left to the right and two until the left the num the left is not the same as the middle then we can safely apply this part okay and same thing for the right side right while right or middle right is smaller than the right and nums right is the same as the nums middle right we always we also try to shrink that right side so after these two steps here right so both the left side and right side they are they're not we don't have a duplicate at in terms of the middle left and right point then we can uh continue we can continue applying our binary search here so what's going to be the time complexity for this one right i mean for the you for the none non-duplicate number case non-duplicate number case non-duplicate number case of course it's a log n right it's a login but for if we duplicate numbers here you know the worst case scenario is what everything is the same numbers so what does it mean means that we have to go through everything we have to loop through all the numbers to decrease the left and right one by one so which means the worst case scenario for this search algorithm is going to be o of n but on average it should also still be log n cool yeah i think that's it for this problem and thank you so much for you guys to watch this video and stay tuned i'll be seeing you guys soon bye
Search in Rotated Sorted Array II
search-in-rotated-sorted-array-ii
There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values). Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`. Given the array `nums` **after** the rotation and an integer `target`, return `true` _if_ `target` _is in_ `nums`_, or_ `false` _if it is not in_ `nums`_._ You must decrease the overall operation steps as much as possible. **Example 1:** **Input:** nums = \[2,5,6,0,0,1,2\], target = 0 **Output:** true **Example 2:** **Input:** nums = \[2,5,6,0,0,1,2\], target = 3 **Output:** false **Constraints:** * `1 <= nums.length <= 5000` * `-104 <= nums[i] <= 104` * `nums` is guaranteed to be rotated at some pivot. * `-104 <= target <= 104` **Follow up:** This problem is similar to Search in Rotated Sorted Array, but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
null
Array,Binary Search
Medium
33
1,721
hello everyone welcome to day 14th of march lead code challenge and i hope all of you are doing really well uh let's go through the question together swapping nodes in a linked list but the question says you are given a linked list and that and an integer k what you need to do you need to swap the two nodes in this linked list one at the position k from the start and one from the end so the overall the question says you need to identify two nodes the ks node from the starting and the ks node from the ending and you need to swap those two values and return the updated list so let's understand this with an example this is the input list one two three four five and k here stands for two that means you first of all need to identify the k the second node from the beginning so this is the first index this is the second index and you need to identify the second node from the last so which is four as shown here so this is the second node from the end now you need to swap two with four and four bit two of the updated list becomes something like this so the problem reduces to identifying these two nodes in the linked list and then swapping the two values so let's quickly understand the algorithm that i have created for this let me just start the slideshow and let me just take a pen it seems like an easy question i have taken a slightly different example to what was specified in the question here the total number of elements in the linked list are six and let's assume k is given to us as two i'll explain two approaches here the first would be one would be the naive approach and the second would be slightly smarter approach so let's go for the first one in the first approach we will calculate the length of the linked list which would be n by traversing across the list and then what we can do we can take two pointers the first pointer and the second pointer we will move the first pointer up to k times and s the second pointer up to n minus k times and once we have these two uh these two pointers the first and the second one we will swap its data and return the updated list the only issue with the naive approach is that you need to traverse the list twice one for identification of the length of the linked list n and the second one for moving up to the first pointer up to k times and the second pointer up to n minus k times so if we can optimize it further to a single iteration that would be beneficial and let's move on to the second solution so let me just it is everything and let's talk about the second solution i'll be using the fast and the slow pointer approach that we need to do is to reduce k by 1 so because we are already at the first node so you don't need to move anywhere therefore or you need to reduce it by 1 and let's assume k is given to us as 2 so k gets reduced to 1 and you need to move the head of the linked list by virtue of the first pointer up to one time that means you just need to move to the next node so f moves to the next node and now let's take the second pointer s which gets initialized to the head of the linked list and you will move until the first node doesn't point to null so this is null and let's keep on moving first and second together so this gets here and second gets here first goes here second also goes here first goes here second goes here and now when you move first that then it reaches the terminal state which is null first dot next points to null that means you need to break the condition also this for the last iteration this moves to this position the second move to this position now we have five and two nodes at their respective instances also we catch this pointer value in some other variable f r before starting the operations together for f and s now we need to remove these two swap these two nodes f fr and s so you take a temporary variable you store the value of s in that and you update fr nodes value here so 2 goes there and this value gets updated with 5. the typical way of swapping two integers in the end the linked list is 1 5 3 4 2 6. hope this algorithm is clear to you and the time complexity for this approach would be order of n since you are traversing the linked list only once space complexity is constant time because you don't require any extra space for solving this so let's quickly move on to the coding part the first thing that i talked about is to update the value of k and reduce it by 1 and now let's define list node first n equals to head and let's move first node till the time k is greater than zero so first n points to first end.next n points to first end.next n points to first end.next why have we reduced k by 1 because the head is already at its first node the starting of the list and once we have done that let's define few more pointers list node f equals to force n so we'll use f for the further iteration and list node second n equals to head till the time f dot next is not equal to null move both the pointers together second node equals to second node dot next and f equals to f dot next once we have reached uh though when the first no f node reaches the end terminal state the second node delay pointing to the kth node from the end and let's just wrap fn with person for second node and the first nodes data integer temp equals to first n dot val first node dot val equals to second node.val and second node dot val equals to temp let's return the head back let me just try and submit this code null pointer at line number 16 what we have there oh k minus i forgot to reduce k looks great and let me just submit it accept it the time complexity is order of n and space complexity is order of one thanks for watching the video hope you enjoyed it
Swapping Nodes in a Linked List
maximum-profit-of-operating-a-centennial-wheel
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
Array,Simulation
Medium
null
39
hi all welcome back to cracking the fang interviews today i'm going to be talking about the combination sub problem uh this is lead code problem number 39 and the problem is popular at apple google amazon netflix amongst other top 10 tech company coding interviews so let's dive into the problem first understand it and see how we can approach it i really want to emphasize on the approach and again my method is not going to change um it's going to be things that we've already discussed in our previous videos i'm going to sort of induce that thought process of how do you approach a unknown problem or the first time you see you know this kind of a problem so this is a snippet from lead code i'll have a link to the problem in the description so you can try it out yourself i'm going to focus on explaining the concepts and fundamentals so the first thing you are given here is you are given a list of candidates and you are given a target seven and if you remember my previous problem if you haven't already i really encourage you to check out the subsets of some problem that i have solved this is going to be a direct application to that problem i'll put a link to the problem in the description below so if you know i'm assuming you'll you know what a subset is uh but dash quick summary for that is a subset of an array one two three four is any uh sub array that you can create um with elements from the original but they are in order so you can only have one after four you can't have four comma one so this is correct this is not so this is the definition of a subset right and what you're asked to do here is you're asked to create use these elements that are given to you and you can actually repeat them so you can have two comma two and maybe six for example or three um you're okay to repeat them to make these add up to this sum seven so what you're doing is essentially if i were to break what they're asking you to do is you're given a target which is also the total we saw in the subset sum problem we solved earlier and they are asking you to use these elements and create a subset with repeating l elements so create a subset with repeating elements that sums to the given target so in this example it could be two and three or it could be seven so both of these sum to seven uh similarly for this uh given candidates or array and a target of eight you can just keep using two four times to create eight you can use two ones and then use three twice then use three and five together so you are essentially creating i wanna really highlight this fact subset with uh repeating elements so if you haven't again already i encourage you to pause the video check out the subset sum problem and then come back to this problem it will make a lot more sense and make the concepts much more uh solid and clear so i'm gonna solve another example to make sure you know the concept is um clear what we are doing in the subset sum problem is we were going from left to right sorry right to left and we were going through each element subtracting uh it from the total if it was less than the total and um also doing cases with and without so we had this recursive tree if you remember in the last example and when the total hit zero we'd return one so it would be one way right so in the subset problem we were calculating the number of ways here we need the actual subsets and with the caveat that the subsets can be can have repeated elements that is the only change between these two problems so the subset problem was number of phase here we need actual subset but you can also repeat the elements in the subset so there is a level of complexity here um so with this in mind i'm gonna you know draw a direct analogy with uh the code um and start diving right in the so there are two things we need to do ah as the concept summary one create subsets and to store those and there's one caveat when i say create subsets and this becomes clear when you look at the examples given to you in the problem here the answer is 2 and 3 but it cannot be 2 3 2 so what this means is the subsets have to be unique also so the way we took this problem we looked at examples we sort of solved it we looked at what is expected of us we realized if you were to you know just repeat elements it wouldn't cut it because you know at that point this could be a valid solution but that's not the case so you cannot have uh you need unique subsets essentially and again this also violates the uh definition of a subset we discussed in the last video they need to be ordered meaning they need to fall follow the same order for example in this array 2 3 6 7 a subset can be 2 and 6 but not 6 comma 2. so this would violate that property because after you can first use 2 and then go to 3 but you cannot use 2 go to 3 and come back to 2 right because that's how they are ordered so i'm going to put a caveat here and call this create subsets and call it unique subsets and then you store the subsets repeat it sorry create repeated unique subsets then you store the services let's look at the code we first create this you know structure that's able to store all our solutions as i said here we are interested in the solutions themselves and not just number of ways however if you even if you store solutions and then calculate the length of solutions it's going to tell you number of ways exactly so they are sort of equivalent that's why the subset sum problem is an important prerequisite for this problem and this is the same base case as our previous problem if the sum or total uh goes less than zero we simply return it's not really a wave but if sum is equal 0 we stored the solution in the subset sum problem we were returning one but here we are actually interested in the solution so we stored the solution uh the next thing i do is very important what we do essentially is we look through each of the candidates but with an index pointer it's incorporated in the state what this index is telling you is where are you at so if you have this candidate array of 2 and 3 and the sorry 2 let me just make it 2 and 3 and you're at 2 what this index is going to help you with is keep exercising 2 and not go to 2 3 and then come back to 2 which is not a valid subset right uh the example we discussed in the previous slide hold the thought i'll explain this better with an example what you do is you take essentially take the solution you have so far you append the candidate uh to it and you also subtract that candidate value this is very similar to what we did in subset and you send the candidates back uh to the recursive stack you can keep this as a global variable also this is not really required and you send this solution uh to uh you know underneath so you can keep adding more to it and you also send this index i and i really want to emphasize on i and index uh to help you better understand the problem uh yeah so index and i so i is nothing but index right uh it's the same variable uh i think the better name for this uh this is it's equivalently starting from index going all the way to candidate so what this means is if you were to be you know solving an example to make the idea more concrete and you have two and three your index you know starting index if we start our call stack from the right and again i'm going to follow the same format as the subset sum problem start from here this is index 0 index 1 or you can also start from left to right now if you want i can do that just for a change uh we started index 0 what we'll end up doing is we'll pick a candidate 2 subtract that from the total which is for example 6. so you'll have 4 as your total your pick 2 and then you and you append 2 to as your solution i'm assuming and then you again make it 2 comma 2 and you make this update your total to 2 meaning you've picked another two and you keep exploring too right as idx so i is going to be 0 and here you'll have 2 and your total will be 0 and you'll end up in this case very open but if that's one solution how about the other solutions the way you'd figure that out is again um you could have for example uh i'm just gonna make this up if the total was seven uh you could have two comma three so you'd pick a two once i would allow you to check zero then you your eye would become one so this is what this piece of code is doing it's making sure you've exercised all your twos first and then you add the number three so this is a gatekeeper for order as i like to call it and again if you if the idea is not 100 clear i encourage you to draw the call stack um and this will really help you uh you know visualize what's happening and why this works and why this helps us keep the order and get unique uh repeated some elements in the subset awesome thank you for watching yet another video from cracking the fang interviews i really hope you liked the video please like share comment in the description
Combination Sum
combination-sum
Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**. The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different. The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input. **Example 1:** **Input:** candidates = \[2,3,6,7\], target = 7 **Output:** \[\[2,2,3\],\[7\]\] **Explanation:** 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. **Example 2:** **Input:** candidates = \[2,3,5\], target = 8 **Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\] **Example 3:** **Input:** candidates = \[2\], target = 1 **Output:** \[\] **Constraints:** * `1 <= candidates.length <= 30` * `2 <= candidates[i] <= 40` * All elements of `candidates` are **distinct**. * `1 <= target <= 40`
null
Array,Backtracking
Medium
17,40,77,216,254,377
396
okay welcome hello welcome back howdy here we are i wanted to work on a problem before i did anything else and i'm gonna meet up with a the bible study group for later today with my the i'm participating in a bible study later today i don't wanna it's i'm it's i mean it's not it's god it's right i don't know i want to say it's the body of christ i'm part of it but i'm it's not mine it's god's so it feels weird saying my group i don't know it's weird saying that so i'll just say i'm participating in a bible study and also judging my hair at the same time or later today i'm doing that yeah but um now i'm judging my hair later i'm going to be participating in bible study so i don't have a lot of time and seeing as these problems tend to take me more than an hour i uh i wanted to yeah kind of get going try this so the question we're gonna look at now is going to be let me see here rotate function and you know let's see i'll try my best see if we can get this solve this problem in an hour there was something else i want to talk about just as an aside which was and i might make a video about it possibly and that is um there's a church in canada that's been barricaded by the canadian government and it's like cartoonishly ridiculous what's going on with that and it kind of immediately makes you think because it's like well it's for your own safety it's for the greater good it's for your own good kind of think to yourself like who's safety whose health safety are we protecting here we're not following the rules which protect your safety and health what rule the rule we get have church yeah it's kind of what's going on right now in uh in canada land canadia okay canada land yeah they're uh shutting down churches because of um you know um reasons quite frankly because obviously if they're saying it's for health reasons it's like these people are freely going to church whose health is at risk here aside from their own somehow it's affecting somebody else that must be protected from these devious churchgoers something like that i don't know there's really there's no way to justify it's just deranged like there's no other way around it i thought about making a video about it but i'll talk about it here briefly and then i'll probably um maybe tomorrow i'll make a video anyway you're given an integer array nums of length n assume array sub k to be an array obtained by rotating nums by k positions clockwise so clockwise is right to left and then back to left again we define the rotation function f on nums as follows f of k equals zero times array of zero one times array of one and minus one times array of n minus one turn the maximum value of f of zero one et cetera f of n minus one oh well that's interesting oh that's kind of neat wow huh um whoa turn nums output so a few things to note here zero times this is the only right n is numbers number of length numbers length and it's less than 200 000 nums is they all fit in an integer so this is a really interesting problem um a few things so a rotation writing a rotation function in the first place is kind of interesting that's kind of its own you could sort of consider that its own problem and right like writing when it's efficient and i guess there really isn't a way to do it efficiently it's kind of it's always going to be at least linear time now this problem i think it's got to be at least linear time to solve because you have to visit each element to make to compute this value what's interesting though is you don't necessarily in other words there might be a way to find out which rotation you need excuse me in linear time and then compute that rotation also in linear time and then compute this result at the end also in linear time um actually you don't even need to do the step in between where you actually rotate because this function you can kind of rotate the computation in an abstract way around the um the array if that makes any sense so like basically you have an array index that like the value for i that you would multiply by the first index could be rotated that's basically the thing so like if you wanted to rotate all you know array of zero everything gets shifted to the right then zero would be for this and then one to and n minus two would be for every all the other things on the right side and that's sort of you would still this part wouldn't change um this part of the sum wouldn't change but these values would change you'd kind of rotate i guess the you would rotate the if it's like a dot product of two vectors you could rotate either vector if that makes sense and actually if you want to handle it that way you could actually take this number take the number modulo n minus one and then you could have an offset there so you could have like um hmm this really should be f array by the way f k doesn't really make sense here but you could do oh actually i guess it does yeah array of sub k okay i get something to take it back um you could do let me think here yeah i mean i guess you could have the starting value be the step could still be zero to n minus one so n minus one increments and each time you increment you also take the value modulo n minus one and then you have sort of an initials point that you start at and you can do it that way right that's how you could sort of calculate this so the so all you need to really find is the rotation and you can compute the rotation efficiently um what you would also want is now how do you figure out what the sort of optimal rotation would be that's a good question it looks like we from left to right so really this would be the most sorted rotation you can get kind of a thing something like that well i wouldn't say it's the most sorted like it seems kind of random right because the numbers don't really have any relation with each other this is sort of that's definitely an interesting question one two three four five right and they kind of just brute force this one right they just went through all three all four possibilities no rotation we got 25 rotate to the right yeah that's good quite four three two six so let's take a look at that four three two six no rotation we get zero three four right zero one two three eighteen twenty two plus three twenty five and one rotation how did they do it they said oh yeah rotate the other way okay so six is now where zero is so zero plus four two four it's fourteen to the right no i don't think so oh yeah i did it wrong six yeah i'm sorry that's right or rather i'm sorry about any mistake um been saying i'm sorry a lot lately i don't know why i'm apologizing um for no good reason 2 0 6 8 12 26 right 0 six zero six yeah okay and three also zero to twelve yeah if we put three at the end right threes at the end six is here four three six that is so confusing that's really confusing uh three is all the way to the left and following it is four is all the way on the right hold on this sounds all right i have to write it i can't the brain struggle with this um six goes over there two's over there two goes over there and six four three all right hold on we had two six four three becomes three two six four right um three two six four three actually this is really interesting um this is not as hard as i'm making it out to be the difference between each of these could be actually made to be take constant time so you would take one routine to find the first sum and then every calculation after that would just be another shift to the side and then you take just take the maximum of those things uh that's what i'm missing here i was gonna say i was like i think this is this has to be done in linear time i don't really have a choice there's got to be some clever way to do this and forget what i was saying before about uh about the vector basically you're um adding and subtracting like vectors something like that um dot product something like dot products adding and subtracting pieces oh i think it's well let's see let's just keep thinking about it because there's got to be some clever way to do this i'm not really there yet but i'm just i'm thinking there must be like a basically constant way to go from here to here efficient way to go from here to here something like that um so three two six four yeah so that's what i'm missing here is that this is also 26 because this is two one time six twice and then four three times yeah that's for 26. okay and that's what this should say and this okay largest is 26. all right um so yeah i mean this is interesting um can we go from zero times four plus one times three plus two times two plus three times six and then that jumps to zero times six i mean you could yeah we're rotating clockwise right i guess that's fine yeah it doesn't really matter necessarily we can rotate the other way too um actually i think it does matter uh i think it actually does matter rotating the other way is a different set of permutations to look at so we do have to go only strictly clock clockwise one times four two times three right and three times four i guess what's interesting is this last element disappears right that goes to zero everything on the inside basically you get another multiple right so the dot product you get like a like you get one three plus yeah actually excuse me so everything deals wait everything to the left basically you increment that the vector by that amount so this would be so yeah it really is it doesn't take much to change this for from to rotate um i want to say like here you would get okay so initially you have yeah zero times four plus one times three plus two times two and then that would jump to one times four plus two times three plus three times two which really is if you just add each of these elements three plus four plus two you just add all that's the difference right call this alpha i guess for now called alpha sub zero right zero rotation you just add alpha sub zero which you can compute that out you can compute all this up uh one once right and then you have this 18 right so now you add alpha sub 0 so you take um i don't know f of 0 we'll say is this sum which this is you know yeah sum of array of zero let's just say and then okay all right let's see okay so f of zero is the sum in our case 18 plus 4 22 25 alpha sub 0 is the sum of oh excuse me actually it's the dot product um what do you call that uh forget how you denote a dot product that vector with i don't know what you want to call this some vector or the let's call it n that's that vector of integers where n is oops one or zero one two dot to n minus one right so yeah see take so f of zero is this dot product of these two vectors alpha sub zero is actually the sum of array sub zero minus array of i really shouldn't use n we'll just call this v instead of n so i want to use n for like the uh plus v this is literally array of n minus one in our instance here right um where alpha sub i would be array of zero array of i minus the last element i guess which is also the same thing as array of zero adding all the elements and then just subtracting i guess it would be if you move this element here you would subtract one from n minus one so array of zero of n minus one minus i right um yeah and right because you're just shifting so now it's yeah you're just kind of shifting over which element gets removed so that's sort of each at each step alpha by alpha sub zero everyone look at it and we want to say f of one looks to be f of zero minus array of zero n minus one times n minus one plus alpha sub zero and what i want to say is you can actually use this relationship to didn't figure out f of two with respect to you can do that you can do um sort of make it sort of a dynamic programming kind of a thing something of a dynamic programming solution and i want to say yeah from 16 you have this is it's the same thing actually every time right because each of these are just rotations that's the difference between them is just a rotation so this guy is um what is this is four three two six move the six over here that's six four three two and this one is related to 2 6 4 3 okay so now to go from here to here from this one to this one it's got to be f of 2 is f of 1 minus array of one n minus one times n minus one plus alpha one if that makes sense all right we so we don't actually have to do any rotations to compute alpha sub i and this factor we'll call this beta which is beta of i is going to be or beta of zero we'll say is array of 0 n minus 1 times n minus 1 where beta of i would be array of 0 or array of i n minus 1 times n minus 1 which is also equal to array of zero of minus one minus i times n minus one hopefully that makes some sense so now each of these we can compute each of these values beta sub i we can compute directly right that's so that's always just um so like beta of i plus 1 would be beta of zero a beta of i over n minus one right or no excuse me it's beta of i plus i beta sub i is this here and actually do it this way so beta of i plus 1 is array of 0 n minus 1 minus i minus 1 times minus 1. and that's related to beta sub i because beta sub i is array of zero n minus one times n minus one so you could say n minus one is equal to this array of zero n minus one minus i excuse me actually excuse me um the other way around you'd say beta sub i over that right and now you can replace that here to give you beta by plus one is array of z array of zero n minus one minus i over array of zero actually i'm not sure this is really much better i think it's i was thinking like let's just see um yeah it's not much better this is but it's actually better probably to just use this directly because my thinking was that you could actually compute this with respect to this although you have to be somewhat careful because this is um this is actually this actually should be 2 n minus 1 minus i minus 1 modulo n that makes sense so that's going to be 2n minus i minus 3 mod n that's kind of what you want here um which is actually just more computation than necessary my thinking was that you could save on some computations by calculating this beta sub i recursively but that's not really true it's actually better just take beta there and then you would say that's b sub i can be calculated directly alpha is interesting so alpha sub i we said is this guy which again we can calculate that directly too each time right because this is a constant that never changes you just compute that each time so that's alpha sub i that's basically by both of those calculated pretty efficiently um and then f of i plus one basically or yeah f y plus one is then just f of i what do you say minus beta plus alpha base of i plus alpha sub i yeah that should be it that's all you need for freak out for your calculations so okay let's do that then so we'll say four i have an integer red equals zero try to maximize it right um these could be negative numbers right so actually we want to make this like then as small as possible so we're going to say for int i equals zero i is less than numbers.size let's numbers.size let's numbers.size let's increment i and we're going to say we want alpha in alpha and beta and then we have a previous value which we'll set initially in fact we can actually do it this way it's even better calculate the previous value first and then we don't have to set red we can say red equal to previous i like that so we'll say this constant so we'll say the sum in total is standard accumulate anonymous dot begin numbness.end i think zero numbness.end i think zero numbness.end i think zero is what you have there so that's the total we said um alpha is related to the total yeah alpha's really the total beta isn't that much isn't too difficult and let's do this too let's actually calculate n or use n i don't normally do that but i think it shows up in our calculations so it's useful so say alpha equals total minus nums dot and we're also assuming that there's at least one value here right yeah it's at least one value so nums of zero all right i said it's going to be n minus 1 minus i n minus 1 minus in this case i is 0 and beta is n minus 1 times n minus 1 minus i which is in this case just an n minus one is zero and we said this is n minus one so there's alpha beta and we're going to say previous is equal to alpha excuse me um oh yeah we have to calculate f of zero first right that's going to be actually we don't even care about alpha beta yet um that don't matter both of those you can compute on the spot and previous is actually going to be um i think we could easily accumulate here i want a binary operation um it's more like a yeah i don't have to do that's fine i'm thinking that's okay let's do it this way that's fine yeah okay fair enough i'm gonna say new previous minus beta plus alpha i did that totally by accident right like lose the beta get with the alpha please ditch the zero get with the hero forgive me i'm not about that life man not about all that but uh i did that was totally an accident i didn't subtract and debated dumb i realize it's dumb not uh just don't mind me um the previous set to this new value so you calculate this new value based off what the previous value was you take red compared to that new value take the larger the two and then set the previous value this new value and then calculate these numbers over and over again i perform each of those rotations and that should do it i should give you what you're looking for oh of course oops really okay what um oh no uh is this right shouldn't this be the same thing every time um maybe this doesn't work though it's alpha beta shenanigans i don't think it works i think it works um yeah so this is 25 we said which i could do math right 18 plus four plus three that's uh 25 yeah that's fine okay and then when we subtract 18 right that's the beta we subtract and then we add the alpha part so minus 18 gives you seven plus that alpha piece which is four plus three plus 2 which is 9 should give you 16. and then we're going to subtract again n minus 1 times instead of 6 now it's four oh no it's actually plus one mod two ah that's my mistake okay all right that's fine that's my mistake so the part we're subtracting the beta part the byte it's uh that's actually plus i mod n times n minus one my mistake and then at this point it would be six plus four plus three which is still the whole sum minus four which actually yeah the part we that's the part we subtract um that's also the part we subtract on the other side too on the alpha side too plus i mod n so that's my mistake yeah that's my mistake uh-huh plus i and you could probably uh-huh plus i and you could probably uh-huh plus i and you could probably optimize this slightly more by you'll notice the way this is set up um i'll get to that in a second but you could optimize this slightly too i'll explain shortly wrong i'm still wrong are you serious you what you are you were made you were you're kidding huh i don't believe it so the value subtract here is n minus 1 times n minus 1. this value is or you know n of uh array of n minus 1 times n minus 1. this is array of zero times n minus one and then when you go again we go again um four three four did i make a mistake six four three two no i got confused i got so confused i think that was right the first time let's go back what did i do what oh no um oops um doing something wrong here i am doing something wrong here also how much time we have it's been like 40 minutes this probably shouldn't take this much time realistically but i'm kind of getting tripped up a little bit here so uh bit of zero okay that's f of one oh that's why duh uh-huh oh yeah because this does start uh-huh oh yeah because this does start uh-huh oh yeah because this does start off at zero right um you go up to f of oh one two three you go up to f of so f of n there isn't an f of n right there's only f of n minus one which is then f of n minus 2 plus this would be beta of n minus 2 plus alpha and minus 2. and there's no such thing after that's what i'm doing wrong oh no kidding right that means that i is only going to be from zero to n minus two that's what i'm doing wrong got it i believe that's what i'm doing wrong there we go okay ah thought i had the right idea just didn't wasn't quite there also this is a there's a billion and seven they like to use this number because i've noticed that the authors here at lee code throw in some fun stuff man let's go nuts and throw some negative numbers in there i think we got it man i think we're in good shape a lot of two three fours um all right let's go for it see how we do oh i'm afraid excuse me the incident right all right let's go for it oh come on i was looking at it i literally had that thought i was like there's it fits in an end so we're not gonna have overflow nope that's not that works no that's not how that works it's like there won't be overflow right there won't be overflow wrong of course is overflow um because look how many numbers you have and you're adding a hundred thousand of them so clearly but somehow it all fits in an inch so i don't know why that would this is uh that gets me every time that always gets me there's always i'm always getting tripped up by that when uh because the total won't fit right it's pretty funny um okay so now this could always be an integer this part but the this might not always be an integer we'll just do all longs whatever that's fine really everything is a law um previous could be an end it doesn't matter new value will be alone and yeah how does that work so does that work oh okay i guess i'll make this along then it's fine and then just stuff that into an integer when we're done uh it's good it's very funny um right okay so yeah let's just take the why not do this i like i could feel it my bones that this was going to be one of those questions where we uh we get thrown off by integer sizes what come on really um yeah i was okay you're kidding really all right let's go for it hey 98 uh you know why we're slower than just a tiny fraction of them is because we're using long longs to deal with the overflow integer overflow we got to just keep submitting till we get 100 that's the only way no we're so close literally the reason is we're not 100 is because we're using longs instead of integers and the longs are like way more bits so it's just way more computation no come on say it ain't so ah all right so what we gotta do then is uh stuff everything into integers and they aren't necessarily they are not necessarily integers so i guess what you would do is this alpha and beta i guess you could combine it then um you kind of yeah i guess you kind of combine all this into one piece so the tricky thing is there is this previous total yeah you have like a previous value right like here's one way of calculating it but if we could break this up into calculations such that the calculations we're using are also were kind of getting over time but we could bring it up to calculate calculations such that each calculation is still within the balance of an integer but it's a lot easier to think about if we just make everything long and just kind of dump everything into a total um that kind of goes back to what we were doing before here going where do alpha sub i and of i plus 1 and beta sub y plus 1 and beta sub i plus 1. now we actually want alpha survivors one is um this thing it's a ray of zero minus ray of zero and oops n minus one minus i right and then we're just gonna delete that's fine gone and alpha sub i is this array zero minus array of zero n minus one plus minus one again minus i which is to say i need more space to let's write our solution here this a sum in terms of is equal to alpha i plus array of zero n minus one minus i which then gives you alpha i plus one is alpha one plus array of zero m minus one minus i minus array of zero minus one minus i minus one right and alpha zero we kind of calculate out the gate as a sum not including right this we should be able to calculate this kind of relatively easily right without too much hassle we don't actually have to calculate the total and this part we can actually just kind of calculate this i equals zero ray of zero by it's n minus one minus two right we can do that should fit in the buffer and then alpha i plus 1 is just this calculation over and over now the tricky thing is n minus i minus 1 all right minus i minus 2 really we don't want that to underflow right we want to have n minus i minus 2 be greater than or equal to zero which is to say that n is greater than equal to or i is yeah m is greater than equal to i plus 2 or that is to say that i is less than or equal to i minus 2 which it is which i actually already have that um yeah sort of good shape so that should be fine so that's how we're going to compute alpha using the previous alpha so we're going to say int alpha is going to be equal to we're going to calculate that um alpha equals alpha zero and then we're going to add nums of i excuse me so we're not going to use the total anymore because we don't need that and then now we're going to calculate alpha as previous alpha plus array of n minus i minus 1 minus i and minus so alpha first we subtract array of and minus i or one or really two minus i or msi minus two do two minus i and then add shouldn't really matter how we do this as long as we don't add first just we need to subtract we add these two and then subtract or we can yeah we'll just do it this way that's fine keep it this got to happen first that's gonna happen first and i don't need the total anymore and i think this still should work all right um oh numbs this is a really interesting problem i like this integer overflow really where does that happen when does that happen oh actually this is wrong um doesn't matter these are multiple loops you can actually do uh maybe better than that forget all that noise i'll try that i'll get wrong now though so it's good oh that's because that comes after yeah and then same thing beta is going to be nums of n minus one so the thing about beta is uh you could have this value you could potentially have a test case where somehow beta ends up being two overflows right because if n minus one is greater than one i think yeah because you could have like the negation and the subtract the addition in here somehow um so that beta is kind of tricky now the thing about the beta is you're subtracting that value so it shouldn't be that big of a deal there's definitely a way that this can happen where this beta doesn't fit but it's not it doesn't fit in a uh in a um let's go for this it's definitely a way that this beta doesn't fit in a long or it doesn't fit in a regular end that's the thing i'm kind of tripped up on right now if we just get beta to fit now previous minus beta definitely fits right no doubt that fits but we might want to um perform all these subtractions instead of performing the multiplication in other words to perform the subtraction n minus one times and then um you could try that i don't know if that's gonna be more efficient though you know it's like really it's kind of funny we can try it temp is going to be previous and then we're going to say 4 in i equals 0 is less than minus one um you're gonna say temp minus equals nums of n minus one minus i and then it's temp then its new valve is temp plus alpha that's quite the difference and then red it's got to be in it let's see how this goes now this won't necessarily work properly either because this actually could underflow the other way too which is really weird yeah i'll get a wrong answer just about right no kidding really oh because we're not oh no it shouldn't matter wait what hold on we're where weird place here oh um what if we make this an int that still work does that still work oh no kidding that doesn't overflow that's really weird wasn't expecting that at all that's kind of good you can just kind of go ahead and make all these since then there we go okay um so here's the thing i don't uh we don't need to name this beta anymore either we just call this new val pretty sure the compiler just optimizes that out anyway but um the thing i was hung up on is really this is still slow really it's faster if i did the other way no kidding what is it just completely random did i even need to optimize anything am i a crazy person does it even matter does anything even matter anymore oh you know what actually there's another there's an optimization that's even more important than any of these things which i completely forgot about this it's very minor optimization but it makes a big difference no guess not doesn't even matter wow you're kidding really i'm shocked i can't believe it um huh no kidding wow nothing i seem to do makes it faster um you don't need to type cast this anymore um i don't know man oh this is doesn't need to be long maybe that's why everything's working better than it should oh that's why this didn't matter i think i guess i don't know oh no just doesn't matter how long it's got to be along somewhere here no nothing am i crazy i got zero somehow i don't know how you got that just randomly what i did i don't know but um we're over an hour now um time for me to go yeah i mean wow interesting question i like this question um we almost did it man why what is happening why are we're just kind of like randomly faster or slower or using less memory why does it seem so strange to be it actually seems like it was faster before i think it was faster because we used um we were definitely using less calculations right it was just one subtraction it's pretty interesting um huh i don't know what to say here huh really i don't know what to think dude i don't know well we're really close right ninety percent of memory seven percent of the so close we hit that 100 one time somehow we can optimize this slightly it's got to be a way there's got to be a way man you could do you can actually um i gotta be careful doing that so you swap the indices for i you could use g instead of i so g is going to be n minus i minus one and g is going to be greater than or equal to when we say it goes up to n minus 2 right so n minus 1 minus n minus 2 is really negative one plus two is one and then we could do we could subtract g let me try that instead how about that what's that does that help at all i don't think so but it might i don't know how about that or yeah when i is zero it's n minus one i think it's minus two yeah i don't think it's a minus one something like this it seems like it might be a little bit faster no not really hardly at all i don't know man i think it's i think it was actually faster before we use the longs because we're using we're doing less operations because look at we're modifying alpha twice whereas before if we did long total and we did the whole sum and then we said alpha is total minus um nums of stuffed into an integer right array of n minus one ray of zero n minus one is n minus one minus i excuse me which is g let's move alpha that way and then we don't need to do these two calculations anymore and then we can say alpha hear it either the compiler would optimize that out i think something like this signed integer overflow cannot be represented type int really no kidding huh hmm oh that's the mistake we have before let's go for it okay that's correct however does that save us anything yeah a little more efficient i think our role is a little bit better right because we have one less operation going on here i mean now we have this kind of stuffing into the integer here which may or may not be good i wonder if converting between integers really matters here if it's good to do that each step or not that seems a little bit more efficient does it go slightly more efficient than that is it possible probably not um yeah i mean by the way we don't need this either about that how about that not much better that i think got optimized away anyway by the compiler i don't think i got a text message i uh waiting for maybe i should send the text um ah you know this could be changed to minus equals it shouldn't really matter but um or plus equals this minus this no you don't want it that way just keep it that way um hmm all right it's probably enough i think we spent too much time now like we did okay we did it right probably could do better somehow but not seeing it as of yet as of the moment ah you know man it's fine we did well we did okay we don't need to be 100 that's fine we did well all right let me um let me go so thank you for watching appreciate it i will talk to you soon hopefully that was interesting hopefully that was enjoyable and yeah i will uh i'll see you soon have a good rest of your day take care yeah okay all right bye
Rotate Function
rotate-function
You are given an integer array `nums` of length `n`. Assume `arrk` to be an array obtained by rotating `nums` by `k` positions clock-wise. We define the **rotation function** `F` on `nums` as follow: * `F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].` Return _the maximum value of_ `F(0), F(1), ..., F(n-1)`. The test cases are generated so that the answer fits in a **32-bit** integer. **Example 1:** **Input:** nums = \[4,3,2,6\] **Output:** 26 **Explanation:** F(0) = (0 \* 4) + (1 \* 3) + (2 \* 2) + (3 \* 6) = 0 + 3 + 4 + 18 = 25 F(1) = (0 \* 6) + (1 \* 4) + (2 \* 3) + (3 \* 2) = 0 + 4 + 6 + 6 = 16 F(2) = (0 \* 2) + (1 \* 6) + (2 \* 4) + (3 \* 3) = 0 + 6 + 8 + 9 = 23 F(3) = (0 \* 3) + (1 \* 2) + (2 \* 6) + (3 \* 4) = 0 + 2 + 12 + 12 = 26 So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26. **Example 2:** **Input:** nums = \[100\] **Output:** 0 **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `-100 <= nums[i] <= 100`
null
Array,Math,Dynamic Programming
Medium
null
1,186
hence today I'm going to talk about the decoder 1186 Mary Simmons sub-arrays Sam decoder 1186 Mary Simmons sub-arrays Sam decoder 1186 Mary Simmons sub-arrays Sam with one cognition the problem is given an array of integers return the maximum sum for sub array with at most one element in Asian you know also talento allow the sub array empathy so let's give an example here we have already you could manage to and the real sweet and you need we could meet her - - and you will need we could meet her - - and you will need we could meet her - - and you will become 1 0 &amp; 3 so this for this way we become 1 0 &amp; 3 so this for this way we become 1 0 &amp; 3 so this for this way we get the maximal subarray which is syria the same 1 0 3 so the sum of the maximal subarray mmm is for here so the problem is that actually means that her way are allowed to need one element at a most so that is the way can t need her one element oh wait don't you need any element from this sub from this array so there are two cases and for the four species that is the way is loaded the mission here that is else a that is so the same problem with the medicines way like some problem that say we can miss or done any programming here the idea of the time involving it's for this way we assume as actually the also follow the ways sweep here which is an element sub-array right and so wait what element sub-array right and so wait what element sub-array right and so wait what if I didn't it hits the madman if I what if I didn't it hits the madman son what sugar and I've to again there's a I from unit 0 so we are finally at the TPI the way that depends on the two situations the first situation is that if before the TP the paper assignment applause the current alignment elicits ego there's a chi hanumant they are beside this submission or else I swear we assign this so this actually we look at the whole because I'm the best always true so this is a transition function of this dynamic programming and the other photo will be the mass or teaching here so let's of having to solve addition problems and a second delay before there is a plant initial here so now you weigh that is Whitney's early and fungus away and call the example some teacher the array data each element from an array and call the atom about actually the algorithm are here this is a famous cutting algorithm if I to remember credit you can check it out I found out that it has a Polish name cream algorithm and so we can call then I wouldn't click here L say we can confuse them and this to visible steps together so we ratify or agree the called the alternator recorder 1385 and we called odium without you that is just same as here you get is a mess up until after this there's a in a half which without initiating any element and the other they are just indicate the medicine some of that's with one element so with one element each sheet therefore we can hmm update to this tip its second away and we updated a second first away so it's actually that for the first Timmy antenatal Odinson it already smells this one here so yes we can cause serious one plus time interval and also an appeal then all the way of this update to this is over here this is actually is depending on also define our toolkit is the for circuit is that there's a one element in it for the other why I'm under th here hmm we are so maximally well we are dependent on the previous though I management automation well okay and also if we the kind of animal is not a material oh you think if it'll matter brother is not Lisa it weird pants on the purist or women and you know no animal is in Egypt then we pass a kind of element here so we carry the medicine all these two elements lemons so this basically the functional here they're not for the way of being the mayor so is true here and they also we also have to consider the initialize the hard way initialized him it stories so the first way we could know cause we could you know as a force or a zero and for the father you for the automatic it'll actually be the energy hey but hope in this question we ask the way should be turned on and do away with it so it could also return were also defined for cement to tween it I did so basically this is the idea so we have just returned from for once beautiful n yeah so the tank velocity here is Wow Oh an here and so space is also 202 m you could om of course we can so we just usually use Vienna municipal we please listen to the press release yes the best way because it's only depending on the filament I'm a sauna so we can use if I knew where I was to replace this two days but here on okay who got a machine of this use this for is here so that's got a function here so first our weight defines this over here it's know it before it even way we made some cookies this is very tangible see only why I'm in here I get one this way as also we initialize the max the minimum value here then we'll initialize this to array1 weapons very nice night another reload anyway it is already well the only need to start from work here and we updated this so we can copy this function here and also Manomet here and we can to find home I was back the maximum hill so this where I get to Weekend Update during the process that's a mess on this three and really turn this mess okay yeah here this should be the float because it could be returned necrovalley was real so okay this one says trial not a test case file I cannot attest he's here yeah we made it
Maximum Subarray Sum with One Deletion
building-h2o
Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible. Note that the subarray needs to be **non-empty** after deleting one element. **Example 1:** **Input:** arr = \[1,-2,0,3\] **Output:** 4 **Explanation:** Because we can choose \[1, -2, 0, 3\] and drop -2, thus the subarray \[1, 0, 3\] becomes the maximum value. **Example 2:** **Input:** arr = \[1,-2,-2,3\] **Output:** 3 **Explanation:** We just choose \[3\] and it's the maximum sum. **Example 3:** **Input:** arr = \[-1,-1,-1,-1\] **Output:** -1 **Explanation:** The final subarray needs to be non-empty. You can't choose \[-1\] and delete -1 from it, then get an empty subarray to make the sum equals to 0. **Constraints:** * `1 <= arr.length <= 105` * `-104 <= arr[i] <= 104`
null
Concurrency
Medium
null
487
hello everyone so today we are going to solve Max consecutive ones second it says that given a binary array nums written the max number of consecutive ones in the array if you can flip at most one zero okay so basically what it says that you have to give the max number of consecutive ones and you can ignore one zero you can convert it into one so if we ignore convert this to one the max would be four and if you convert this to one your max would be three so the answer is 4. similarly here if you convert this to one you can have Max 4 if you convert this to zero one this will be Max 4 so the answer is 4. uh okay so one way to do this would be I can just count the number of ones first whenever I get a zero I can have an array which will keep track of number of ones so something like for this uh it would be a list with one then you can ignore zero and then a list of two and then you can ignore zero so what you can do is I think this is a better example in this case so for this example what we would have is one two and one and then what you can do is you can compare you can just sum up the two values and see which one is bigger and add one to it but I think this is using extra space o of an extra space one better way to do is I can think of like sliding window where what you can do is have a left and right pointer here you keep on going till the end so left and right you'll keep on going to the end and whenever you see that there's more than one zero in this window will keep decreasing this window right till you reach where you just have at Max 1 0. and you will have a Max variable which you'll keep track of the maximum window so this way you can find out the maximum number of consecutive ones yeah so it would be something like we'll have a left pointer starting from the beginning of the area and right part starting from this and what you're going to do is while right is less than my end until I reach the end of the array right what I'm going to do is if my number off right it is zero I'll keep track of the number of zeros so let's highlight end number of zeros at zero and then every time I see it I'm gonna add plus if it's not doesn't really matter at the end I'm going to write plus um so anytime when I see that my number of zeros is greater than equal to 2 right I want to start moving my left window I'll keep doing this till that's condition satisfied so it will be while my number of zeros is greater than equal to 2 right I'm gonna keep doing left minus and anytime I see that my nums of left a zero uh I'm going to decrease the count of my number of zeros so this way whenever I my left window removes one zero this now is a valid window and I'll get out of my for Loop while loop and here I can just keep track of my Max so let's say my Max initially is -1 I don't have anything -1 I don't have anything -1 I don't have anything and Max would be the max of that variable and write minus left plus one right uh yes and at the end of return on any ways to write plus and I'll return this Max so yes yeah I'll start from the left and right I'll keep track of the number of zeros whenever I see and I'll add it if I have more than two zeros in that window I'm gonna start moving my left pointer and whenever I remove a zero I'll get out of the loop and that is a value window I'll get the max of this over there and I'll return that yes cannot find number of zeros okay my bad index minus 1 out of bounds for length five okay let's see oh this has to be left plus that looks good submit awesome in terms of time and space complexity the time of this will be o of n because it will go on till my right reaches the end so it's of N and my space is over 1 because I'm not using anything extra it's just sliding window so that's it and we'll solve this
Max Consecutive Ones II
max-consecutive-ones-ii
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most one_ `0`. **Example 1:** **Input:** nums = \[1,0,1,1,0\] **Output:** 4 **Explanation:** - If we flip the first zero, nums becomes \[1,1,1,1,0\] and we have 4 consecutive ones. - If we flip the second zero, nums becomes \[1,0,1,1,1\] and we have 3 consecutive ones. The max number of consecutive ones is 4. **Example 2:** **Input:** nums = \[1,0,1,1,0,1\] **Output:** 4 **Explanation:** - If we flip the first zero, nums becomes \[1,1,1,1,0,1\] and we have 4 consecutive ones. - If we flip the second zero, nums becomes \[1,0,1,1,1,1\] and we have 4 consecutive ones. The max number of consecutive ones is 4. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`. **Follow up:** What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?
null
Array,Dynamic Programming,Sliding Window
Medium
485,1046,2261
1,014
Hello guys welcome to the video serum to deal problem call website singh pax let's get started tyun subscribe since point to you how to get the score of paramedical maximum what is quora self-motivated settings search tent quora self-motivated settings search tent quora self-motivated settings search tent business place value sub z plus i - When business place value sub z plus i - When business place value sub z plus i - When School Are Often Accused Of Peroxide Singh Sports And Understand With The Help Of Example For The Red Color Ones Of Values ​​And Green Color Wave With Us And Suna Values ​​And Green Color Wave With Us And Suna Values ​​And Green Color Wave With Us And Suna Darling Default Spotted With It Takes To Maximize What Is To Maximize School What Is Ko Laddu Calculates Ko For The Best Ones And Also Lets You Checked Into Passive Voice Of Course Admitted Students To Ruby Simply From The Two Value Se Features One Plus Two And When You Take The Sense Of Pride And Plus One Minus Three Gold Ore And 1231 - - 210 Course Three Gold Ore And 1231 - - 210 Course Three Gold Ore And 1231 - - 210 Course One Slips Side A Time Ago It's A B1 B2 S What Is The School Smoke 225 Classes Pest Minister - Phool Sudhir Vats Loop - Pest Minister - Phool Sudhir Vats Loop - Pest Minister - Phool Sudhir Vats Loop - 211 Miles 209 Sun Rise The Score Of The Particular Pack To Find The Maximum School That In This Course Will Be Watering Late From YouTube website and this feeling gives you reverse entry taking a half fried egg setting affair riding and chief justice subscribe and subscribe the Video then subscribe to the Page if plus minus subscribe plus minus maximize do pimp equal to maximize this particular quantity Paltan se doob 3121 in this possible to back to maximize your device to calculate the values ​​in plus minus example of how to maximize the latest flash light of plus to subscribe a profiler side it finally students s file and different size which celebs headed to Give it to the maximum age limit for example if you want to maximize your back side seriously subscribe to the Page if you liked The Video then subscribe to the quite ok and start hum sorry I have previously been celebrated it's maximizing chances of mudrs co subscribe 508 don't Want to see the country of the world to the maximum - - - - - Number 90 With The Kinnar Shoulder Special I Don't Have Any Value For The Next Element OK Provident Exam - Provident Exam - Provident Exam - 151 - - - - - - - - - 151 - - - - - - - - - - Love You To I Love You To Chanakya Kautilya Classes Water Better Maximum Severe Change And Maximum That Alarm Laga - OnePlus As Maximum That Alarm Laga - OnePlus As Maximum That Alarm Laga - OnePlus As Words Will Not Change Done And Will Not Change There Children In The Next Two Plus A Distant View Of water will change its water element latest co.no ki bihar samudra elements which was selected and will get number five statement from j - - - 50 answer the best possible sure subscribe - 6 - 1ST year 2ND year old is gold channel Subscribe to According to In This Element Answers Pay Later When Every Goodbye Transforming Change Ka Answer Starting Point of Equal to One I Love You I Love Later E Agree With U and Sunao Vihar Also Quality Heavy Fighter Place Now We Need To Give Me Answer Of What Appears In A Plus B Plus C Plus Minus Currently It Will Always Be A Great Example subscribe Channel Quote 8 Plus As The Answer I Don't See The Answer Years Old Same Element Fixed Price will be later updated and five plus only morning 12th update maximum against previous benefits year guarantee egg white color I will be maximum of high court and finally a that nurse vacancy such work on one message most different time turn C it's working fine Thank you
Best Sightseeing Pair
k-closest-points-to-origin
You are given an integer array `values` where values\[i\] represents the value of the `ith` sightseeing spot. Two sightseeing spots `i` and `j` have a **distance** `j - i` between them. The score of a pair (`i < j`) of sightseeing spots is `values[i] + values[j] + i - j`: the sum of the values of the sightseeing spots, minus the distance between them. Return _the maximum score of a pair of sightseeing spots_. **Example 1:** **Input:** values = \[8,1,5,2,6\] **Output:** 11 **Explanation:** i = 0, j = 2, values\[i\] + values\[j\] + i - j = 8 + 5 + 0 - 2 = 11 **Example 2:** **Input:** values = \[1,2\] **Output:** 2 **Constraints:** * `2 <= values.length <= 5 * 104` * `1 <= values[i] <= 1000`
null
Array,Math,Divide and Conquer,Geometry,Sorting,Heap (Priority Queue),Quickselect
Medium
215,347,692,1888
3
Open it and confirm that rather the height will increase, the money is for this, the rest is the code word, so you are net savvy, look at the hard work that has been put into this working, so the bigger it is here, the story kept changing in the last, then we made our plan accordingly. It worked fine Hi everyone how are you guys I hope you are well welcome to another new great problem statement and today we will learn Longest Serving Without Feeling Collector This is a medium type problem of List Court and we will fold it in this You will understand that I had a front interview in Product Base and this question was asked in it, so I said let's cover it in our series also and who knows, if you are giving an interview today or are going to give it tomorrow, then you too may face a problem. It increases a lot, in Amazon, Paytm, I have asked all these companies and or decree to anyone, if you are going, then ask, okay, so let's start and I have also opened my base and list. The code has also been opened, it is a medium type problem, call it only and understand that Kapoor and Vent, watch this video completely, it will not be a problem, you will understand completely, there will be some ups and downs in between, you will understand what is happening but No problem, after watching it completely, all those ups and downs will end, you will get complete confidence, you and the people who make zoological writers will be on their own - that's all, I will be on their own - that's all, I will be on their own - that's all, I will not say anything more, okay then like the video. Share it as much as possible in your college group on WhatsApp everywhere so that our Suji Lee can be seen by children and as far as most people can know that it is okay that YouTube works in this way. Share it a little more and it is done. He will take the study, it is not a problem, leave it inside this video, if the situation like this is fine, then let's start, if you understand, then to extract the long sub without hurting character, you have extracted the length, basically like suppose Varanasi Cantt is ABC BP. So what am I going to use, which data will I really use, let's go to all those things, see, you have a string that now if I find you most interesting, so I will take out something, I will make so many combinations of yours in ABC, if I talk about myself. So if I talk about property logic, if I think about the combination of what combination will be done in the bathroom, the problem will be that first became that food became this, oh brother how did this become AB, ABC became food and ABCL became There will be a lot of such people in Congress, how many will you take out? If you understand, then this process is called brute force approach in which you will be a little complex. We can also do this by pointing to me tomorrow how many combinations will be made. We can close all the settings, we can either go with this mission or use this approach but it will be a bit complex and so I will end your interview then okay, I mean I want to say that right now it is spring. Now what it is saying is that you should be out and which is ABC in it which is your substring which will not repeat like A B C D is light and unique character and sequence is maintained not sub sequence subscribe means what I picked up from here Took and removed from here he was right I will do it in the order ok so here ok I go to college give you the result here we have life in the list court like this is also one of the ones so I know that There will be only one like this one, a big example has been given, three persons and these W's etc. persons, war length of, this is ours who is traveling the longest without getting all the actors who developed, this is what you said PK who PW Same sequence, now sequence lots of string is correct, what is the meaning of all, you have taken pitha separately, then not like this, we have to maintain the sequence, it should be in this way of W, sequence should be maintained and tractor should be daughter, now we will understand more as soon as the video goes ahead. Your understanding of thinking will increase, your butt will increase, do n't leave the video, then your interest will be lost and the rest I am telling you, okay, this is a thing, that's why we will have sex, our mother will be something like this, so now I understand one thing. It is from Saurav's statement that we have definitely taken out the best but here, what we collectors have is to help you in creating a unique store and for that, which set of customers can we use? If you can use my set and the maple leaf video. If you haven't seen it then I have given the link in the description. If I cover it, when I set it up and use it, you will get it wrong. So, I am going to boot polish. If I go to A Root Polytechnic, I am going to the next process, it will take time. And company logical complex ok then to overcome that what can be the optimal solution hmm guide user data structure that if I go to office then it is a simple thing selected is this once a then understand there is reliance care ba that by dividing space congress What data success am I going to use, but okay, right now I am not going to take brute force, I am just going to figure out in this team, how many Samsungs will be made, okay, we are not doing that too, we will use sliding here. Window is fine, what happens in sliding window is that we are chatting, we take points, that is our work is done with that, we will take one window, we will make two points in that window and when my look is finished, like my will be united, final. So whatever account will be inside that window, whatever elements will be there, the element that will be mine will be electric and will have the same neck length. I told you quickly, so here I am going to use hot. Talking about the optimal solution, I am not in favor of brute force right now. I'm going to use here on the sliding window technique in which we will have two pointers left pointer and right for you can say end and start pointer and at its base like when the whole loop will keep going all the elements that are inside my spring. All these elements will be traveled, then in the last window, inside that window, there will be a rally of start key, value of end, my element is going to be found and my element will be ring with me and it will be without repeated character. And by commenting on it, we will find out the max length, so this is what we are going to do - help sliding window, going to do - help sliding window, going to do - help sliding window, so I hope you have clarity, we are going to know, so here I am going to use the data structure, that asset because the set which is there is the unique factors. So my work will become easier, I will be able to handle it, okay, so right now I am not using this boot, I am not coming out with many combinations and am not going to make such complex logic, otherwise you guys will get bored, when are you studying in 11th, okay? So let's do one thing like I said that I am sliding or do winters, here I mean whatever technique is being used, so do we have one in Dubai, would you like me to have one, your end tech is there and one is what we are going to use. Let's start, okay, so now I will show you the whole thing in detail, what are the introductions of thinking, what are they, I have seen this thing, guys, till now in my career, I write very good code in tea, I am very good in coding or I mean solve problems. I do it at the time of interview, I know that the question came and there is a possibility, I mean, I am wearing this, I have not done it, I have forgotten the logic, so no matter how good I am afraid, I will not pass the interview, his friend, you do not know and they can provide food. Court But sometimes this happens, so it is very important that you keep practicing because then it should be like this, it is very important to practice, if you do not practice then you will start refilling by mistake. Okay, so here we are, we have done it on June 1. Because the sliding doors are working as per the optimal solution, so we have to take all this technology without feeling, collectors and lets will take out the coins. Okay, so Android has started with us here and I am just starting here. Both the heroes will remain on time and here I would like a condition that if my spring is coming here and I am testing this which is going to come, then if this trick is not my trick, if Bajro does something then the link will ask this flame. But it will fall to zero. If nothing comes, then we should assume that for the quality, if the string is not coming, then in that case we will grow the returns. Then the matter is over. Secondly, let us find out the maximum length. This is the gym, I am doing the maximum length. Look, what I am saying is that I am making my pimples in this manner so that you can understand, so I have to zoom in on the plate, give me two houses, my zero is okay, it is going to be in right now, okay after that I have to create a set. Now how to create a set in JavaScript, what are we, who is this and what is this set of ours, what will this crystal stone do, so its name is something like this, I will give unique care and new set, okay, so what should we do here? I have made my own set which will have unique elements and settings, there will be no problem, you will have clarity, okay, this place is unique, caterers are going to go, Rafale will be doing loops, now what will we do, as per the way of doing Mari Springs Travels, it is okay now, the logic is Now a logic will come and I don't know where it will be understood, I will make it more effective, till now there will be no doubt with me that you have taken it from the unique collector, it is ok and you have made one, let us work on it and check the starting. And I am removing it from here and I live at your place. The approach door is going to be opened. Okay, so it is now a collector and we can do it. Okay, what should I do now? Here we have it and that You from my to we so if my this then first of all we will not be repeated ghrit for our meaning as soon as that is the first case no problem then come in you if inside my set now dot s in this manner do this inside the union Are I okay? Was it looted? Okay, what are you doing? Unique and even within the actors, the set is sometimes empty, I know it is empty and not by putting it on, which is the end only patience, so edit okay, my basically this is this. There is a character of mine, this is my secret, it is zero admiring, so what we will see is that it is in the express with cameras, if the cameras are not in the set, then what to do, brother will not ask, what will you do, add it, okay then we will add it, till then we will If you are using a set, then add it inside it and along with it we will make the end cube plus, we will just remove more macrame keys from this because now when you add any element in the set, your neck length will increase, otherwise we will do this. There is a function here i.e. dot max in which function here i.e. dot max in which function here i.e. dot max in which brother will put his neck length on the website and for comparison he will do the mirror dot size on the website of my alarm set, then its value will always keep changing as your measurement will always remain the same. As your set alarms will keep going, your size will be formed, it will come in the neck length, okay, but this condition looks good as long as the eyes element is unique, but as soon as the pimple or this element, then let this It will continue to do this again, now the work is done here, it has become a bad star, here what will we have to do, we will do like this, okay, we have to do this, I will have to help you to handle your character of coming again David. We are here with a tractor and are poor, I will tell you this, I am telling you something right now, you guys will laugh at the verification of the money, I will also show it to you when I travel, you will get clarity, don't worry, okay see. What do you do by coming here today that if there is an off butt character then will we delete whatever was there or will I remove it from the percentage and will make the sacrifice of start plus now this is because you are requesting, is n't it? No brother, it's okay, and as soon as I finish it, I will get it, which will be my Max Plank, my long-e-sub love will be my long-e-sub love will be my long-e-sub love will be without fitting characters, so we will return it. Yes brother, let's go, so let's do it, let's go for a while. Will we go to the conference or not? Then we will fix the laces. Okay, let's try first, so I am McClain first. Okay, so what is this, we will come first, whatever practice we have, as long as someone is unique, he will keep going in the set. End Max Planck will keep on increasing, Max Planck will also keep on being calculated, as the value of my set is now zero, Max Planck will keep on increasing, but in the case of duplicate character, which is found in the folder of the set, we will edit it and add the value of start plus. Okay, now I am talking about this tempered glass leaders, so this is based on using brute force technique where you will first remove a lot of stuffing, the logic will become very complex, then the comeback tweet using pointer which saffron which is inside our sliding window. A window is formed in which the stars will end and when the entire low is over which will be the rally of these toys, at that time she is going to be our mechanic, okay now we will understand from time to time, okay, something has happened now, we have not done anything yet. It's just starting, it's okay, we will keep running, let's satisfy it. Okay, I have n't made anything and let's see what the problem is, brother, that it will be 127. Okay, and tell me a long answer and JavaScript how to deactivate it. Okay Ok, I liked mixing it. Given that mine will start here, okay, it's fine because it will happen because we are fine here, now what should we do from the start because right now, suppose your elements are fine, show me, if I go into this, then ADC is here again. And my relative is inside my set, so click here and it is useless, it has come again, when it is first, we will have to paste it, I will take the form and submit the code once, okay, now we have it wrong, yes, right now. I am getting the value, I am not getting anything, we have done something wrong, it happened again while submitting Rs.100 here, again while submitting Rs.100 here, again while submitting Rs.100 here, OK, it is set, effective Sita has been picked up, so finally Bigg Boss has started, the voltage has also increased here. Everything is till the code is set, everything is fine, now what do we have to do, now we have to understand this, I go on my base coat, okay, so let's close it, do you understand what we did, whatever those actresses are, first we Let me put it in this set as if you started deleting the repeats, it is okay to start from your set and do one thing, then I turn it all on and take it to my Xavier School for more resources, so I can give you an example. It also means that I am assuming this mother acting thing and do her post-mortem one by one and do her post-mortem one by one and do her post-mortem one by one so that you can understand and if you can convince her with logic, then I will smoke her and I would like to pass this, it is the first stage disease, it is okay. It is very easy guys, if you understand then I will do it very well as I have given a condition and the description and I will join it is ok, so here we put this first rank is ok, let's take the width and do one thing with it. Here I give it a rec, okay, and control dot lock ARUC, okay, so here we also open the cold, let's see, let me run it here, it's running there, it's not greased, that's all. Some set up matter, live saturday kam and seeing that the recording is happening, no and it is happening, it is exactly like that, I brought the protection and recorded it, half an hour of recording was to be done, so the entire sentence was killed, will there be no problem in it? To understand how the work is being done according to this trick, I have imposed a little condition and post-mortem it, I am doing the same, it little condition and post-mortem it, I am doing the same, it little condition and post-mortem it, I am doing the same, it is okay and I understand the uniform, hence the next day I was tired from the Google account, so let's do the complete mathematics there. Show the change, how is the work, not a little bit in between, student friend, will I give you 10, turn on Ajay, a plate, here is this, which is this, by the way, ABC, now we will start on spare time. After 30 and more zeros are ok, I know it very well, it started soon in the open loop and validity length, how much is my length, Ajay is coming from 202 34567, if Zaki is 7, then the loop will run till zero seven, ok and first we will check. That it is not there in my set, it is not there, then we will keep doing plus, so if you see, these stairs will also go into your insert and then when your loop will run, 0 will go to exile, it means that our team will go right now, that is why I have made the judgment directly to the contractors. PIN has been set, the answer will be 359, there is peace friend in his juice, it will remain, now I am telling you what will be the value of start, it will definitely go and the value of end will break your face. If you do n't believe then believe this. Like the video if you don't like it at this time, then don't do it. If you do comment, you will be present in the beginning. Whatever is meant here for Aishwarya, where did he go just like this? The end has been placed, the match has fallen due to illegal connections, which must have been involved in it will be fine, hello viewers element will ask, but now you have come here, are you understanding this again, now the story is now strong, it is going to get spoiled, okay but will not. Will fix the bad, ok, so now it is said that it has passed ABC minutes and it has only two brilliants, mix it with three, that Bigg Boss Radhe-Radhe will be able to do 012 with this, so it is Radhe-Radhe will be able to do 012 with this, so it is 0123, now it is. What we have to do is this cross again, now what will happen if it comes then it will go inside it and will digit the starting position and if we press start then whatever is there will be created then what will happen if it has started then we will have space. What will happen if it is deleted, this will become, this is deleted and it is 2014 and the end vote will remain yours, okay, now like sorry, your end will increase, this end of Raghavendra Bade will become your free, so from now on, it is okay and mix yours. One two three one two three Major Percy will remain, it was decided that the return of many stars increased and those who were deleted, you are the first one, yours was removed, it is fine, but when you went to the woman, I have zero 1238, so that one, you are the scientific one, your this one. It is gone, you have removed it but it will be of your interest, but the Paytm app which is set controls them and when you checked here, it is stuck but still it will handle, so what are you are drowned after that. If it is yours, then it is okay. What is your repair? If this is your interest, then how will it be? Okay, this should not be a problem, now the appointment has been made, if it is okay, then what else do I have next, okay then zero. 1234 So maza-4 will become okay then zero. 1234 So maza-4 will become okay then zero. 1234 So maza-4 will become Forms of Badi Hai So what will happen inside the set a that now we have to remove this middle so I will have this will become four and this will become two Okay two three four will be mixed 2342 Intex Incident So This will go and this will remain as it will work, so it has not been found yet, let's go, you have this okay, then Sky is already ready, so what will happen and this is a and this scene will be shot okay. Yes, we are fine, but ABC has come, B's has also come again, okay, do you understand what is happening, now it has been filled again, this has been given, whatever is left, something is going on now, hit Shilu Peace, we are also mine to you. The back has not got the final toilet Hmm I gave plus curve now I know that the missing judge is mine which I have given inside the asset and I have given in the starting okay now the child who is near this tree is okay and Mary Start 12320 123, so now we are here, it will come on this, I have already listed it, so will we remove it or in the middle, if what we are saying is, now we will put it on MP3, then that which was just started was changing the scrap. If it remains the same then it will put it that you will move away from here and your starting value will be returned and it will be yours then you will be the mixer father and 5 6 again there will be the ingredients for which yours will also come back. Photo What is Zero 1234 This will be given and this will go to you Five and this will go to Seventh Storm has returned, father has gone for Max, then this is Bhind, we have finished the game from there, so this is the long one, without character Army Chief Stitches have been stitched in it is like that, how will your greed work, double the speed of Yagya, this problem, if you like it then first it will be grinded, then justice will be done, then W will go, then if it comes again, then this type of grind will be removed, look again, say this also. There have been many the length of history of this update of the software industry this is what we are talking about here we the person double all this sequence if you different sequence which the person if you like this see this message we have to see the sequence is being made good Okay, so here we have used it in this way, we smoked it on the website of the list, tried to understand us like this, how the work is going on, handed it over to the person that rather the height will increase, brother, this is the code word. So you people see on the net, this hard work is working, so much of the story made here kept changing, in the end the film has done its job accordingly, okay, thank you so much for watching this, if you liked it. To like is to share and what is the next problem that you want me to write, I will meet you very soon, Neck Switzerland, take care of your likes, definitely more.
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string `s`, find the length of the **longest** **substring** without repeating characters. **Example 1:** **Input:** s = "abcabcbb " **Output:** 3 **Explanation:** The answer is "abc ", with the length of 3. **Example 2:** **Input:** s = "bbbbb " **Output:** 1 **Explanation:** The answer is "b ", with the length of 1. **Example 3:** **Input:** s = "pwwkew " **Output:** 3 **Explanation:** The answer is "wke ", with the length of 3. Notice that the answer must be a substring, "pwke " is a subsequence and not a substring. **Constraints:** * `0 <= s.length <= 5 * 104` * `s` consists of English letters, digits, symbols and spaces.
null
Hash Table,String,Sliding Window
Medium
159,340,1034,1813,2209
91
hello welcome to my channel today we have leeco 91 decode ways so this question is really popular and uh often asked in the interviews so the question itself is pretty easy to understand and you can see the example right away we're trying to um decode this problem back to the abc character so now you can see we have input a string all integers right here and one is representing a b is representing i mean two is best where the presenting b then 12 itself representing l in this uh mapping right here um so there's two way you could write in a b or a single l for this 12. now uh another example right here you have three ways to uh write this problem pretty cool and also can start with zero so the zero is um no way so it could cannot be mapped to anything else so this question can be solved easily with the dp so let's take a look at that by writing some code first we make a table array that has a link yes.lane plus one yes.lane plus one yes.lane plus one we want to have we create one more space for the zero so if the problem is if the input is 26 and then we'll have a index that starts with zero always and let's take a look at the code again and we will make a table zero which is the index is equal to 1 there's one way that's default and table 1 have to depend on the first letter of the input which is 2. so if two is not zero that means there's one way to solve it so that dot chart is equal to zero or not at zero there's zero way to solve that problem otherwise it's one way so now we have let's see um we have one here and also one way to solve like that one way to solve the zero and one way to solve two that's cool and the dynamic programming is when you step on this right and if this fall into one to nine which means there's one way to solve this problem and if this is the case we copy the previous one number in here because at one definitely the same to the same way as a before the same way as before will be one here that is also one but also check another condition is to check the last second digit in here can is falling on 10 to 26 so that is another way to in decode this problem uh so at that time we'll add go back to this position -2 which is here this position -2 which is here this position -2 which is here have one way to solve it so we also add this one into the location current location so that's the so now we have two ways for this location if this two digit it doesn't fall into this range and that case we don't need to add anything because only one way and then keep copying the previous solution in here and that's how we saw this so as we know we have i equal to started with the this letter which is one actually two we look at two first and table only and starting from two starting from here we check um if check this one uh condition which is first and this is second so now we have end uh first will be integer start sub string that and minus one second to integer start sub string minus 2 actually first is current number six and second will be uh 26 this two digits so now we check if first bigger than or equal to 1 and less than or equal to 9 so which is falling in this range then we copy the previous one minus one if this is a valid uh number first and then copy the pearson if the second in here the second digit fall into the range 26 right and that's the time that i also plus or equal to table minus two so now uh if this is a valid one we copy the pearson if this two digit is valid one in this range we have to copy uh the current location -2 -2 -2 and plus and add it to the location this is a different between here and here so after you add all those solution and what we need to do we'll accumulate the maximum to the end of the table now the table we just return it how many ways we can decode that one so table dot lane minus one so that will be the last integer in that array okay in teacher cool and that's it for this question uh hopefully you get it and make you feel a little bit better if you have any questions please comment below and i will see you in the next video thank you so much bye
Decode Ways
decode-ways
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into: * `"AAJF "` with the grouping `(1 1 10 6)` * `"KJF "` with the grouping `(11 10 6)` Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`. Given a string `s` containing only digits, return _the **number** of ways to **decode** it_. The test cases are generated so that the answer fits in a **32-bit** integer. **Example 1:** **Input:** s = "12 " **Output:** 2 **Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12). **Example 2:** **Input:** s = "226 " **Output:** 3 **Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6). **Example 3:** **Input:** s = "06 " **Output:** 0 **Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 "). **Constraints:** * `1 <= s.length <= 100` * `s` contains only digits and may contain leading zero(s).
null
String,Dynamic Programming
Medium
639,2091
443
hello everyone let's talk about string compression it's lead code 443 question uh what it says we have a array and we should compress like A2 B2 C3 there is two A's so A2 then 2 B B2 and three C and but is uh one case like if there is a single element we should not write uh one here like here is a is single so we should not write one it should stay as it is and also if it's more than nine yeah you should write separately like one and zero not 10 or not 12 one and two uh what we will do uh firstly we will initialize two variables for write uh for read and write then we will Loop through the array Loop s the all the characters here and we will also initialize the starting point why uh what is red is a current character that we are reading right now and start is starting character like starting group of character it can be a start it can be B or C but read in our case it's a b we are reading and then we will Loop so each element and the count group only length chars and character that we are reading right now is equals to character that we have started we will increment the read to one why we are using same twice uh it can be like scenario like all of them a in this case we should here increment all the read elements and here we are checking if current reading element is equals to starting like starting is a and reading element is a our reading element is B for that use case we are checking here we will increment the red and then we will update our array chars right kills chars oops start and we will increment the right also here charge right charge start we are we here writing the starting element like a and then increment the right and then we should check if red minus start is more than one like if there is more than one element we should Loop all of them for digit in string we should convert to string so if there is like here more than nine we should separately append to array red minus start chars WR kills the digit you should update also right and then we return the length oops
String Compression
string-compression
Given an array of characters `chars`, compress it using the following algorithm: Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`: * If the group's length is `1`, append the character to `s`. * Otherwise, append the character followed by the group's length. The compressed string `s` **should not be returned separately**, but instead, be stored **in the input character array `chars`**. Note that group lengths that are `10` or longer will be split into multiple characters in `chars`. After you are done **modifying the input array,** return _the new length of the array_. You must write an algorithm that uses only constant extra space. **Example 1:** **Input:** chars = \[ "a ", "a ", "b ", "b ", "c ", "c ", "c "\] **Output:** Return 6, and the first 6 characters of the input array should be: \[ "a ", "2 ", "b ", "2 ", "c ", "3 "\] **Explanation:** The groups are "aa ", "bb ", and "ccc ". This compresses to "a2b2c3 ". **Example 2:** **Input:** chars = \[ "a "\] **Output:** Return 1, and the first character of the input array should be: \[ "a "\] **Explanation:** The only group is "a ", which remains uncompressed since it's a single character. **Example 3:** **Input:** chars = \[ "a ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b "\] **Output:** Return 4, and the first 4 characters of the input array should be: \[ "a ", "b ", "1 ", "2 "\]. **Explanation:** The groups are "a " and "bbbbbbbbbbbb ". This compresses to "ab12 ". **Constraints:** * `1 <= chars.length <= 2000` * `chars[i]` is a lowercase English letter, uppercase English letter, digit, or symbol.
How do you know if you are at the end of a consecutive group of characters?
Two Pointers,String
Medium
38,271,604,1241
106
hey guys welcome back to another video and today we're going to be solving the lead code question construct of binary tree from inorder and post-order tree from inorder and post-order tree from inorder and post-order traversal okay so before i get started with the question i just want to mention that if there are any lead code questions that you want me to solve specifically just let me know down in the comments and i'll try to get them solved for you okay so in this question we're given an inorder and a post-order traversal of a inorder and a post-order traversal of a inorder and a post-order traversal of a tree and we need to construct a binary tree using that information so let's first see what this actually means and how we can use it to construct a binary tree so let's say that this over here is the binary tree that we are given as an example so now let's see what it's uh in order traversal looks like so you have three types of traversals in order post order and pre-order and pre-order and pre-order so in this case we only care about in order and post order so in an inorder traversal you first visit the left node then you go to the root node and then you go to the right node so let's see what that looks like for this tree we're always going to start off with our root so we're going to start off at 3. now we're going to look at its left so it's left child is a 9. so 9 temporarily becomes our root so now we're going to look to see if the 9 has any children so if it has a left child and it does not have a left child now we're going to go back to the root which in this case is 9 and we're going to add that to our list now after root we need to look at the right so now we're gonna look if nine has any uh right child and it doesn't so now we can go back to our three so we've covered nine now we're gonna go back to our three and we're to add that to our list so now we need to look at three's right child which is a 20. so right now we're at 20 and so 20 is going to be our root for now again we look at a 20's left child if it has one and it does 20 does have a left child of 15. now again 15 is going to be our route for now and we're going to look to see if it has a left child it doesn't so we're going to add 15 and now we need to look at 15's right child which also doesn't exist so now we're done with this and now we're going to go back to our 20 and we're going to add that to our list so now that we have 20 now we look at its right children so it does have a right child of seven so seven is going to be our root for now so now we look at seven's left child which does not exist seven does uh so then we add seven then we look for its right child which also does not exist and we're done so now we have the whole tree so this is what our in order traversal for this tree is going to look like so now let's see the same thing but let's look at its post order traversal so i'm just going to be using the color blue to represent everything done regarding to post order traversal okay so in our post order traversal post means after so we're going to look at our root at the ending so first we go to the left node then we're going to go to the right node and the root comes at the end so then at the very ending we look at the root okay so let's start again so we start off at the three and we always start off with the root now we're going to look at its left node so we go to nine and now we look to see so nine becomes our root for now we look to see if right has a left node doesn't it does not have a right node so now we're going to add the root which in this case is nine so now that we're done with that we're gonna go back to three but we're not going to add three because we need to look at its right child so now we're going to look at 3's right child which is 20. so now we're at the 20 and now we're going to look at 20 left child so that's 15. so now we're at 15 and now we're going to look for a 15th left child which does not exist it does not have a right child either so now we're going to add the root which is 15. so now we're going to add 15 to our answers then after that we're going to go back to 20 but we're not going to add it since now we need to go back to its right child so 20's right child is 7. and at 7 we do the same thing we look at its left child does not exist right child does not exist so then we add the root so now we're gonna add seven and since we got twenty's left and right child now we can add the root which is twenty so now we can add twenty and now finally we can add the root which is three so this is going to be our post order traversal and you can look at the difference and now let's see how can given both of them how we can construct a binary tree using this information so now let's see how we can create a binary tree given an inorder and post order traversal so over here i have an inorder traversal and over here i have a post order and just to remind ourselves uh inorder has left then you look at the root and then you look at the right and for post order you look at the left then you look at the right and then you look at the root so let's now see how we can create our tree using this information now since we have left right and root we know that no matter what the last element in our post order traversal is going to be the root of the binary tree so in this case a is the root so we have the root over here which is a now what can we do with this so what we can do is we can take this root and look for it in our in order list so we found a over here and what does this tell us so inorder is left right and root so everything to the left is going to be part of the left part of our binary tree so d b and e are all going to be part of the left and f c and g are all going to be part of the right so first let's just solve or find out the left part of our binary tree so we know that it's going to have d b and e but we don't know at what in which order we're going to find them right so how can we find that so in order to find out the order we're going to be using our post order so what we're going to do is look we're going to look for d b or e inside of our post order traversal and whatever comes first is going to be our root so first so we can we need to look for either of these db or e so not year and we came across b so the first thing we came across is b so we're going to make that our root and its children are going to be so we're going to cross out b since we already have it and the children are either going to be d or e and again we don't know in what order so to find out the order we're going to look for the b inside of our inorder traversal so we found it over here and again remember it follows left right left root and right so in this case the left is d so that's our left child the root is b as we found it and e is the right child so now we solve the left-hand child so now we solve the left-hand child so now we solve the left-hand part of our binary tree now we're going to do the same thing but for the right hand side so again our right hand side is going to consider consists of f c and g but we do not know in which order so in order to find out what comes is going to be our root we need to look for f c or g and whatever comes first is going to be our root again i forgot to mention this earlier we're going to iterate from the right to the left so we're going to go in this direction okay so as you can see the first thing we find is c so c is going to become our root now we can cross that off and we know its children are going to be either f or g but we don't know what is what so in order to find out which one is the left child and which one is the right child we're going to look for c which is the root in this case in our inorder list so we found it here so c and again in order for us left root right so what is to the left of c f so f is going to be the left node then we have c which is the root and then we have g over here which is going to be our right node and this is how we can find out a binary tree given an inorder or and a post-order post-order post-order traversal of it so let's now put this into code and see how we can solve it using python as with most tree based questions we're going to use recursion to solve this one as well okay so we're first going to see if our in order or post order list is empty and if there is no nothing inside of it we're just going to return none so if not post order or you could also do or not in order it honestly doesn't matter because if one of them is not there the other one is not there either okay so in that case we're just going to return none okay so now that we have this we can establish a few variables so we're going to have our value which is going to be whatever is the last element inside of the post order list so in our first iteration this is going to be the root so that's going to be the value of the root to be precise so now we're going to create this into an object so we're going to make it called root and so now we're going to use the tree node class and if you're confused where this class is coming from it's already predefined for us so we're just using that definition again so we're going to have the tree node class and we're going to give it the value all right so now we're going to have an index so this index is going to be the index of where the value is in our in order list so to do that it's just going to be inorder dot index val so that'll give us the index of where this value is in the inorder list so now you might be asking why are we doing that so let me just go to our example over here and let's just look at the case of our first iteration so in the first iteration our root is going to be whatever the last element is for our post order so that's three so now we're going to look for three in our inorder list so three has an index of one so in order to find everything that's to the left so that's the same as looking at everything up to the index of one for our post order list so we're going to use this as our po in order list so everything to the left of three as our in order list left of whatever is at the first index for our post order list to find the left children of our tree and to find the right children we're gonna find everything uh starting from the next element of where we have three so from 15 all the way to the ending and we're also gonna do the same for the post order list so we're gonna go to the first index of our post ordered list we're gonna first index because the root is at the first index for our inorder list so we're going to start off from the first index and we're going to go all the way up to the last but one element so we're not going to consider last element here because that is our root and we already took it into consideration so now that we understand that we can go back to our code and continue writing it okay so now what we're going to do is we're going to find the left children of our root so we're going to do root.left and we're so we're going to do root.left and we're so we're going to do root.left and we're going to call the function on if on itself so self dot build tree okay and what are we going to call this function on we're calling it for the left side so we're going to call in order everything up to the index so everything up to the index but not including the index and similarly for our pre post order so for our post order list we're gonna call everything up to the index as well so everything starting from zero all the way up to the index now similarly for our root dot right so the right children we're going to do the same thing again self dot build tree okay and now for our inorder list we're going to call everything from one element to the right of the root all the way to the ending so in other words it's going to be in order so we're going to start off with index plus 1 so the next element and we're going to go until the ending so do we do that and now for our post order list we're going to start off at whatever our index is at so that's going to be our starting point and we're going to go until the last element so we're going to go until the last element but not including the last element so that's why we need to specify negative one over here okay so this is going to find our left and right children recursively and then after that we can just return our root which is a tree object and now let's submit this okay it says val is okay sorry this is supposed to be value and submit that again all right 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 a better solution to solve this question and if there is any lead code question that you want me to answer just let me know down in the comments and i'll try to get them answered for you and thanks a lot for watching and do don't forget to like and subscribe thank you
Construct Binary Tree from Inorder and Postorder Traversal
construct-binary-tree-from-inorder-and-postorder-traversal
Given two integer arrays `inorder` and `postorder` where `inorder` is the inorder traversal of a binary tree and `postorder` is the postorder traversal of the same tree, construct and return _the binary tree_. **Example 1:** **Input:** inorder = \[9,3,15,20,7\], postorder = \[9,15,7,20,3\] **Output:** \[3,9,20,null,null,15,7\] **Example 2:** **Input:** inorder = \[-1\], postorder = \[-1\] **Output:** \[-1\] **Constraints:** * `1 <= inorder.length <= 3000` * `postorder.length == inorder.length` * `-3000 <= inorder[i], postorder[i] <= 3000` * `inorder` and `postorder` consist of **unique** values. * Each value of `postorder` also appears in `inorder`. * `inorder` is **guaranteed** to be the inorder traversal of the tree. * `postorder` is **guaranteed** to be the postorder traversal of the tree.
null
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
Medium
105
1,716
hi everyone welcome back to a new video today's lead code daily challenges calculate money in a lead code Bank this is an easy level question so let's see what they have told us to do in this question they are telling that hery is a person okay and he wants to save money for his car and he puts some money away every day okay so on the first day he starts by Saving with $1 and every day starts by Saving with $1 and every day starts by Saving with $1 and every day he increments the value of the dollar by one that is on the first day if it is putting away $1 on second day it will putting away $1 on second day it will putting away $1 on second day it will increase by 1 to two and the on wedness if it is on right it is starting from Monday so on uh Tuesday it is $2 Monday so on uh Tuesday it is $2 Monday so on uh Tuesday it is $2 wednessday it will become $3 in the same wednessday it will become $3 in the same wednessday it will become $3 in the same way till Sunday it will go to $7 now if the value of one week is to $7 now if the value of one week is to $7 now if the value of one week is going from 1 to 7 right now when the new week starts he increases the value by one okay he increases the value of the dollar that he is putting away by one from the previous week okay that means that if on the previous week he had put away $1 in the new week he will had put away $1 in the new week he will had put away $1 in the new week he will be putting away $2 okay so what he is be putting away $2 okay so what he is be putting away $2 okay so what he is doing here he will put away $2 $3 and in the here he will put away $2 $3 and in the here he will put away $2 $3 and in the same way it will keep on in increasing and it will go till 8 now if he is putting away money for the third week also then it will start from $3 okay also then it will start from $3 okay also then it will start from $3 okay same way every week he's increasing the value by one from the previous Monday and on the subsequent days he's putting away $1 greater than the previous day so away $1 greater than the previous day so away $1 greater than the previous day so whatever the basics what we have to do here we have some values given to us and we need to find the total sum of it like if it is four days okay then we need to find the sum of 1 2 4 okay and now this is only applicable for the days which are less than or equals to seven right because what we can do here we can just find the sum of 1 to 7 but what happens when the value is greater than seven like we have n isal to 10 or here we have n isal to 20 then what we are supposed to do what we have to do here is basically we have some total weeks here and some remaining weeks right like here what we have here we have 10 now in this we have some complete week the complete week what we have here is one complete week right and some remaining days that is if we have 10 days okay in that one we have one week and 3 days exceptionally so the remainder days are left is if n is equals to 10 then we have one complete week and six remaining days sorry not 6 three so we have three remaining days now what we have to do here we will be finding the sum of 1 to 7 right which it is the base in all of the problem means all of the series right if we have 1 to 7 here and let's say we had 14 days right now 1 127 was available in this also the extra value that was increased by one was added afterwards right we can add it afterwards also basically we have 14 days and we can get the value from that also so following that what we will do we have a complete week and we have remaining weeks now for complete week we know that uh the value is seven right we have seven days and what we can do here is we can get the sum for this s days right from the uh formula n into n + 1 by 2 we from the uh formula n into n + 1 by 2 we from the uh formula n into n + 1 by 2 we can get the sum of 1 to 7 for 7 Days 1 to 7 sum so what we will do here we will do 7 into 7 + into 7 + into 7 + 1 by 2 which gives us if it is it becomes eight right so we will get here 28 now we have 28 as the sum for 7 days so what we can do here for whatever complete week we have we can just multiply with 28 right 28 into complete V right now we have the sum for uh 7 days here that is one complete week so what we will get here 28 right now if we are taking the uh value where we are storing um storing the total amount that is stored by the end of the given number of days then if we are using total to store it then what we have to do we have to keep on adding the value whatever we are getting so if in total week what we got here we have 28 into complete weeks right now we have some remainder days also left right we have three days here so what we can do here if we have 1 2 3 right in the pre we are just adding one to all of them we can ignore that now we can take the base idea for that so what we have here we have 3 into 3 + 1 by 2 we have here we have 3 into 3 + 1 by 2 we have here we have 3 into 3 + 1 by 2 right we can do this and we can get the sum as 3 + 3 into 4 by 2 so we will get here six right so for the base that is 1 to 3 we can get the sum as six right so what we will do here we will get remainder multiplied by remainder + 1 by 2 okay we have this now remainder + 1 by 2 okay we have this now remainder + 1 by 2 okay we have this now and we will add it in the total so now we have the sum as 28 + 6 which is as 28 + 6 which is as 28 + 6 which is 34 now we have some remain uh remaining value left right here the sum that was supposed to be there was 37 right and what we are getting here is 34 what we are missing here the value that was increased by one in the upcoming week right so it is basically n right so what we can do here if we have total number of weeks as one right for the contribution of remainder weeks what we can do here we can just multiply it by remainder days so if we have one here then what we can get here 1 into 3 what is getting here we will get here three so now we have 34 + + 3 which is 37 we so now we have 34 + + 3 which is 37 we so now we have 34 + + 3 which is 37 we have our answer that was supposed we were supposed to get right now if it is applicable for 10 now if we have n is equals to 20 then the total complete weeks what we will get two weeks right because 20 by 7 we will get two and remainder days we will be getting a six right now if we are doing total here so according to Total what we had to do 28 into the complete weeks so we have here 28 into 2 we are getting here 56 right and for remainder days what we had to do here 56 this is the previous one previous total and we were doing remainder days into remainder + one right 6 into remainder + one right 6 into remainder + one right 6 into 7 by 2 we will do here and we will do number of week present into remainder days this week into remainder will give us the count of sum that was left out in the remaining days right we were we had left out the sum in the remaining days that only we are getting by multiplying the week with remainder so here what we will get 2 into 6 right so we have here 56 + 20 21 + 12 which gives us 89 right now we see that we have n the output as 96 when we have n is equal to 20 right using the previous values what we were suggested we found out the total value for the remaining days right we got the count of whatever the left out days were in the remaining days but for the full weeks right here when we had week is equals to two now we got the sum as 56 but one week has seven extra left out till now right because if it was starting from 1 to 7 it was going from 1 to 7 then the next week which started it was starting from 2 right and it continued till 8 and for this week what we did we only took the sum from 1 to 7 and for each of them one got left out right in order to get that sum what we will do we will take total and this 89 will be added and the total number of weeks whatever we have we will do n uh sorry n not weak multiplied by weak minus one by 2 into 7 now the what this will do this will give us the contribution of week when value is greater than one or when the week is greater complete week when the complete week is greater than one so like here we had two weeks right so what it will become 2 * 1 by 2 into become 2 * 1 by 2 into become 2 * 1 by 2 into 7 so we will get here 7 now 89 + 7 will 7 so we will get here 7 now 89 + 7 will 7 so we will get here 7 now 89 + 7 will give us 96 so this was the expected answer right so what is basically Happening Here is we have the we take the sum okay we take the sum for complete week then remainder days considering that it is starting from 1 to n one to n or we can say 1 to7 uh 1 to 7 will go for um complete weeks and for the remainder days whatever the value is 1 to n that is n is less than 7even right now we start the uh we do the sum for one to the value given till end okay now every time since the value is getting upgraded by one in every new week now we need to get the sum for that so for that what we are doing some extra steps like we are adding this week into week - 1 by 2 multiply by 7 what this week - 1 by 2 multiply by 7 what this week - 1 by 2 multiply by 7 what this will do this will give us the contribution of complete week contribution of complete we with value of complete week greater than one right so it basically starts when we have complete week as two or three right because then what we will get every time the value keeps on increasing by one in the first week it was starting from one right in the second week it will go from 2 to uh whatever the value comes that is8 here then for third week it will start from three so to keep track with that what we are doing for the complete weeks we are just adding up um adding up one right so for that we are doing using this formula and for the remainder weeks what we uh remainder day is what we are doing we are taking the sum for remainder days using the normal formula remainder into remainder 1 by two this will give us the value for one to whatever remainder days is like if we have six then 1 to six it will give us the sum and since now this uh this remainder has the value increased uh by whatever value is like in the uh in when n is n was equals to 20 so for the remainder days the value had increased from 1 to three right so in order to get that what we were doing we were taking the weeks that was provided to us like the complete weeks that we got and multiplying it with the remainder days so this would give us the uh extra time that was Pro uh that we were getting in this remainder days right here what we were getting now in this uh extra remainder days we had 3 + 4 + 5 + extra remainder days we had 3 + 4 + 5 + extra remainder days we had 3 + 4 + 5 + 6 + 7 and + 8 so every value had two 6 + 7 and + 8 so every value had two 6 + 7 and + 8 so every value had two increase to it so what that means we had six days and every value was increased by two right that's why we are taking the weeks here because how many weeks we are increasing by that value the remainder days will be multiplied because every time we are adding one to the new week the remainder week will have the same value or the increased value as the number of complete weeks we had right here in the when the value was 10 we had complete weeks when the value was 10 then we had one complete week and the total number of uh remaining days were three so the value for this was increased by one only right so what we did basically we multiplied it by week so that we don't need to keep the track for the last week or the remainder days every time so uh let's move on to the code so whatever little doubts are there will be cleared with it so let's see the code now so first what we were doing we have we will declare a variable which will store the total value okay now we have to get the complete weeks and the remainder weeks in order to get the complete weeks what we will do we will uh divide the N by 7 and in order to get the remaining days what we will do the value of mod 7 right this will give us the remaining days now what we will do we will take total and we will multiply it by 20 we will take total and now we need to get the sum for n number of weeks right so we have 28 as the sum for one week and we will multiply it with week to get the sum with n number of week and now what we will do we have remaining days left now for that remaining days what we will do we will get the sum for that by using the formula RM into n + 1 by 2 the formula RM into n + 1 by 2 the formula RM into n + 1 by 2 that is the formula and since we need for the remaining days then what therefore what we will do RM into RM + 1 divided by 2 and now this will give us the remaining days right and for that the sum that they are calculating will be from one to whatever one uh one remaining day or two remaining days we need the contribution of the extra week also so for that what we were doing we were multiplying it with week right so whatever the extra week we are having uh the value for the remaining week will be increased by that only so this will give us the contribution of the remaining week now we have some complete weeks also AP like when we have one week it is fine but when we uh when we have the week greater than one we need the extra contribution what that was provided to us by that extra week also or the week that was greater than one so for that what we will do we will we were using the formula we n into N - 1 by 2 right so we will do n into N - 1 by 2 right so we will do n into N - 1 by 2 right so we will do that only week into week -1 by 2 so this will give us the total sum now in this line we got the sum of N number of weeks which is starting from 1 to n and here we got the contribution of remaining days and this will give us the extra contribution that was provided by each week right complete weeks now what we will do we will return the total value that we had so here what we are doing we are not using any Loop and we are using only one variable so the time complexity and the space complexity both will be o of one let's try to run this code now sorry uh we had to multiply here by seven because this will give us uh the week contribution uh the number of weeks right and here by using this uh we will get the week contribution each and every week right so let's try to run it now so that sample test cases have passed let's try to submit it so this code has been accepted that's it for today guys thank you for watching if you found this video helpful even a little bit please let me know on the comments and also to continue with me on this lead code daily challenge Journey please subscribe to the channel and hit the Bell notification so you will be notified every time I post a new video thank you for watching
Calculate Money in Leetcode Bank
maximum-non-negative-product-in-a-matrix
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Array,Dynamic Programming,Matrix
Medium
null
384
hey everyone welcome to my channel so in this video i'm going to briefly cover the solution to this question at the same time do some live coding work also i'm going to follow the general interview steps while trying to solve this problem so first of all let's race through this question uh shuffle array so given integer array numbers design an algorithm to randomly shuffle the array so implement the solution class has one constructor called initialized object with integer randoms it has a reset it says the shuffle api through slide essentially is just to reset the array to its original configuration and returns it and the shuffle api is going to return a random shuffling of the jewelry so let's see the constraints first it says that the length of the array could be anywhere between one to two hundred each number is anywhere between minus one billion 1 million to positive 1 million so all the elements of the nums are unique at most 50k costs will be made to reset and shuffle all right so let's see how to solve this problem so um for this one not too much of the room to think about hatch case so if you think there's only one number within the array it can also be cached i think we can also catch this because in our general solution so let's just try to find the general solution for this one so for this uh there is a uh so we can do a shuffling using a pretty famous algorithm i think no shuffling so that one uh what we are going to do is um i mean i just know the algorithm so i'll just talk uh from my brief memory um yeah so i mean for this kind of question if it is asked within a interview you just need to i think you better need to memorize this algorithm so that you can come up with the algorithm quickly within the interview so it's something like um you're going to generate a random index and try to so it is going to be do one pass through the array for each of the current index you're going to try to generate another uh another random index to be uh to be potentially replaced uh like do a swap with the current number with the generally random index number do a swap on top of that so that's essentially the intuitive idea how to do that so essentially what we are going to do is uh we are going to generate something like we are going to do have a for loop uh from i t 0 and smaller than uh and every time you're going to uh generate a random index so the rand by dx it's something like i plus uh rand random from actually this from zero to this would be nums that plus minus i and then you're going to do a swap on top of num between i and the random idx so that's essentially the idea so run time is going to be all of n which is linear and is uh the number of the elements within the nums array and for the reset uh we just need to so every time for the shuffle we are going to create a new in new interarray and for the reset we are just going to just return the nums array that is passed into the constructor so let's do some coding work on top of this so we are going to have the nums of course to be stored here for this constructor we have the nums and for the resets you're just going to return knobs and uh for the shuffle initially are going to have like a rend do a copy first so random i finally we are going to return rand nums but uh here you're doing to do one pass just so like this piece of code here you're going to have in i is equal to zero high smaller than uh plus i ran idx is equal to i plus uh random.n um this will be something like this all right so here we could potentially do a swap i would just uh define a helper function here called swap on top of the systems so you're going to call this uh swap on top of nouns very sorry it should be run numbs um i and run idx so let's run this piece of code okay so we have an arrow here i cannot find symbol is it something like write it okay so let me check some api here so it's something like we have java random java all right so this is okay so it's next ins right it's next uh next in okay it's called the next hint is not a okay so it's not a static function so here we go this will be random accent all right so it's accepted let's try to do a submission on top of it all right so everything works well and that's it for this question so if you have any questions regarding the solution or regarding whatever uh feel free to leave some comments below if you like this video please help subscribe this channel i'll see you next time thanks for watching
Shuffle an Array
shuffle-an-array
Given an integer array `nums`, design an algorithm to randomly shuffle the array. All permutations of the array should be **equally likely** as a result of the shuffling. Implement the `Solution` class: * `Solution(int[] nums)` Initializes the object with the integer array `nums`. * `int[] reset()` Resets the array to its original configuration and returns it. * `int[] shuffle()` Returns a random shuffling of the array. **Example 1:** **Input** \[ "Solution ", "shuffle ", "reset ", "shuffle "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\]\] **Output** \[null, \[3, 1, 2\], \[1, 2, 3\], \[1, 3, 2\]\] **Explanation** Solution solution = new Solution(\[1, 2, 3\]); solution.shuffle(); // Shuffle the array \[1,2,3\] and return its result. // Any permutation of \[1,2,3\] must be equally likely to be returned. // Example: return \[3, 1, 2\] solution.reset(); // Resets the array back to its original configuration \[1,2,3\]. Return \[1, 2, 3\] solution.shuffle(); // Returns the random shuffling of array \[1,2,3\]. Example: return \[1, 3, 2\] **Constraints:** * `1 <= nums.length <= 50` * `-106 <= nums[i] <= 106` * All the elements of `nums` are **unique**. * At most `104` calls **in total** will be made to `reset` and `shuffle`.
The solution expects that we always use the original array to shuffle() else some of the test cases fail. (Credits; @snehasingh31)
Array,Math,Randomized
Medium
null
1,834
hi guys welcome to algorithms Made Easy my name is khushboo and in this video we are going to see the question single threaded CPU so let's go and take a look at what the question says you are given n tasks labeled from 0 to n minus 1 represented by a 2d integer array tasks where task of I is the combination of two values NQ time and the processing time which means that the ith task will be available to process at the NQ time of I and will take the processing time as processing time of I to finish its processing you have a single threaded CPU that can process at most one task at a time and will act in a following way if the CPU is idle and there are no available tasks CPU remains ID if the CPU is idle and there are available tasks CPU will choose the one with the shortest processing time and if there are multiple tasks that have the same shortest processing time it will choose the task based on the smallest index once the task is started the CPU will process the entire task without stopping the CPU can finish a task and then start a new one instantly return the order in which the CPU will process the tasks so here we are given a few examples but rather than looking and reading out the explanation that is given along with them let's take a look at one of the examples in a graphical manner which will make us understand this example much more clearly so we are going to mimic the single threaded CPU as per the given conditions in the question for that let's take a few things with us which includes the processor itself that is the CPU and a clock that is going to tell us the time the processor will have two areas one is the processing area wherein there will be a task that is currently being processed and the second is the waiting area where all the tasks that are waiting to be processed will be there this clock is going to show the current time or the current T at which we are and then we will have a task this represents a task for us wherein the first value is the NQ time and the second value will represent the processing time so over here the NQ time is 1 and the processing time is 3. if the clock shows 1 we can happily move this into our waiting area but since the clock over here now is telling 0 we cannot enqueue it right away so we need to wait till the time turns one so now time is one unit and this is the NQ time for this task as well so the task can be moved into the CPU and since the processing area is empty this task will move into the processing area and the end time for this task will be the time at which it entered plus the processing time that is 1 plus 3 that is equivalent to 4. so till the time equal to 4 this task will occupy the processing area and all the tasks that are coming in by then will wait in the waiting area so let's see how this goes now at time t equal to 2 Suppose there is no task coming in so we'll happily move forward to time equal to 3. now at 3 there is one task that is coming in which is 3 comma 5 so this will get n cubed in our waiting area because the processing area is still occupied till t equal to 4. now when T is equal to 4 there is one more task that is coming in which is 4 comma 1. so this also gets n cubed over here and at t equal to 4 this task is finished so the CPU or the processing area becomes empty now we need to decide which task we need to pick from these two waiting tasks so according to the rule that was mentioned in the question the task with the smallest processing time is going to get picked processing time of this is 5 for this is 1 so this is going to get picked and will go in the processing area now the end time of this will be the time at which it started plus the processing time so this becomes 5. now at time t equal to 5 Suppose there is one more task that is coming in with the processing time of 5 it will go to the waiting area and this task was finished so it came out now the processing area becomes empty so we need to choose one of these tasks now over here the processing time of both these tasks are same so what we need to consider in order to select the task is the index of that task now since we have not considered the index with these values let's suppose that this came first so in that case 3 comma 5 will go into the processor and get processed the end time will be the current time plus the processing time which is 5 plus 5 that is 10. now at 6 there is nothing coming in similar to that 7p there is nothing coming in on 8 9 and 10 nothing came in but at 10 this task got finished and now there is only one task that is remaining in the waiting area so now this task will get processed so this task will take the time 10 plus 5 that is 15 units to get process in between that if there is some other task coming in again that will go into the waiting area for Simplicity let's take that this is the last task and so at t equal to 15 this will also move out of the processor and this is the sequence in which we have processed the task so now this becomes the output sequence of the task being processed by the CPU so now the question that we need to ask ourselves is what are the data structures that are going to fulfill our need in order to solve this question before that just for Simplicity we excluded the index part from this demonstration so we need to even take care of that while we are choosing the data structures of how we are going to store these tasks and how this task is going to get picked so now there are two things that we need to consider to solve this problem one of them is to store these tasks data and the second is the process that we are going to use to pick these tasks now the questions that we need to ask over here are where and how that is where to store the task data and how to store the task data whether we need a sorting or we can just store as in we are getting second is where are we going to keep the task that are to be processed and how are we going to pick the task that are to be processed so these two questions will give you the answer to how we are going to code this particular problem to store the data you can either use something that will give you a container to hold all the three data that you need to know while processing a task that is the index the processing time and the enqueue time apart from that how you are going to store the data is to ask the question that whether you want to do any ordering on the data now to enter into the waiting area you need to know the NQ time the task that has a least and queue time will go in the waiting area before the one that has the higher NQ time so that says that you need to do some sort of ordering on that data now second question is the process by which you are going to pick that particular task from the waiting area now for that we need to know that what is the data structure that is going to depict the waiting area because we need to fetch the one with the lowest processing time or the lowest Index this kind of functionality where we want to get the top most element or smallest element or top K elements or frequent elements is given to us By Priority queue so that is what we are going to use in this particular second thing is how we are going to access this on what basis is this priority queue going to be sorted so this is something that you need to think of according to the question the picking of the task depends upon the processing time and if the processing time is same it is going to depend on the index so these are the two parameters on which the priority queue is going to be sorted so now that we know what are the data structures that we are going to use and what are the things that we need to keep in mind in order to solve this question let's go ahead and code it so let's first think about how we are going to store these tasks in order to get processed so we need a task that will comprise of index and queue time or the start time and the processing time so this gives us how we are going to store the task and we also need to see whether we need to sort this particular task or not so sorting will be needed because we need to First enqueue the time which has a lower start time so sorting will be based on start time now what happens when the start time is same in that case we need to do a second level sorting based on the processing time now the question arrives do we really need the processing time because the priority queue will pick the task based on the processing time but initially when you are putting the first task at that point of time if there is a task that starts at time equal to 1 and has a processing time of 10 and there is a second task which is at a later index which has a start time of 1 and the processing time of 1 comma 10 will go into the processor first if we do not consider this processing time because we have not sorted it correctly so for that purpose we are going to have a two level sorting on this particular task so let's quickly take a class task and write to create an array of this task rather than the array that is given to us which will be sorted so this is simply the task class that we are going to have and now we are going to iterate over the task and create an array of this task and sort it foreign so this will give us the Sorting of the data now let's go to the second part of how to pick the task so for that we are going to take a priority queue and the Sorting on which the priority queue is going to process the task will be firstly based on the processing time which is going to be ascending that is lowest first and if these are equal it is going to process on the index which is also going to be ascending order so for that first let's take a priority queue now what this priority queue is going to hold the task secondly what is the Sorting that is going to be there so let's give a comparator over here let's take a few more index variables that we are going to need and then we'll loop on the tasks that we have firstly that we are going to need is a result array that we are going to return and let's just return that as well now there will be an index for the task that will keep moving and there will be an index to put the data into the result that is going to be moving and both of these are going to be 0. next we'll also be needing an end time to see when our next task is going to end its processing so that we can put another task into processing so now let's take a while loop and we are going to iterate while my index that is the task index is less than n so I still have some task to be processed in this there can be two scenarios whether my waiting list or the waiting tasks are empty or not so this represents that if this waiting tasks are non-empty that means I need to tasks are non-empty that means I need to tasks are non-empty that means I need to process one of the tasks and calculate a new end time so I need to otherwise I just need to add the task in waiting list now in order to calculate this particular thing we need to pick the next task calculate the new end time and fill the waiting tasks we'll talk about this part in a moment let's first see how we are going to pick the new task and how we are going to calculate the end time initially the end time will be zero now in order to pick the new task we are just going to get a task from our priority queue so the task that is we are going to wait is going to be 1 from the waiting tasks the remove function will give us the task according to the logic that we have given so this current task will have an index that we are going to put into a result with that it also has a processing time which will be helpful in calculating the end time so first let's calculate the end time now will be the maximum of either the start time of this current task plus the processing time or the end time at which the previous task was going to finish plus the processing time for the current task correct so we will write math dot Max of either current task dot start time or the end time so this is going to be the time at which this particular current task is going to start and for it to end it will take the processing time of this current task now we have the processing time or the end time for the next task between this end time we also need to put all the tasks that are coming to us before that into the waiting area so for that we'll again run a while loop but before that we also need to put this particular index into our result as well so let's do that for result we have a result index that we had taken while we are adding this we'll also increment it now let's take a while loop so over here we are seeing whether my end time is still greater than the next task in my task list start time if that is the case we are going to add that particular task in our waiting task list or the waiting task queue and we are going to increment the index fairly straightforward so that will take care of processing the task now if we were not having any waiting task what we need to do is we just need to take this line and add dough here because we are just going to add that particular task in the waiting Zone this particular condition will take care of the rest of the processing part now once this Loop is executed there might still be some of the tasks that are there in the priority queue or this waiting task list which are not pulled from the list while this index ran out so for that we are going to remove those tasks from the list and add it into our result so simple while loop we are again going to fill it over here and then at the end we are going to return the result so that's it for the coding part we are done let's run this and this variable is already taken so let's take another variable and it's giving a perfect result let's submit this code and it got submitted now what is the time complexity and the space complexity for this particular approach since we are going to sort this data the time complexity becomes o of n log n the maximum time complexity is going to be captured by this sort function which is n log n space complexity is going to be o of n because we are taking this task array over here so in this question we understood more about how to sort a particular data which is given to us in order to get the results that are required and how the priority queue works and how we can do sorting and how we can create a user different priority queue with this we also learned how to break down the question and then try to come up to an intuition to solve this kind of problems so that's it for this video guys I hope you like the explanation I hope you understood the problem and if you still have any doubt please put a comment and we'll try to reply to it and also if you have any other question in mind that you want us to make a video please drop that in the comment section as well and we'll try to take it up as soon as possible so thank you for watching and I'll see you in the next one
Single-Threaded CPU
minimum-number-of-people-to-teach
You are given `n`​​​​​​ tasks labeled from `0` to `n - 1` represented by a 2D integer array `tasks`, where `tasks[i] = [enqueueTimei, processingTimei]` means that the `i​​​​​​th`​​​​ task will be available to process at `enqueueTimei` and will take `processingTimei` to finish processing. You have a single-threaded CPU that can process **at most one** task at a time and will act in the following way: * If the CPU is idle and there are no available tasks to process, the CPU remains idle. * If the CPU is idle and there are available tasks, the CPU will choose the one with the **shortest processing time**. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index. * Once a task is started, the CPU will **process the entire task** without stopping. * The CPU can finish a task then start a new one instantly. Return _the order in which the CPU will process the tasks._ **Example 1:** **Input:** tasks = \[\[1,2\],\[2,4\],\[3,2\],\[4,1\]\] **Output:** \[0,2,3,1\] **Explanation:** The events go as follows: - At time = 1, task 0 is available to process. Available tasks = {0}. - Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}. - At time = 2, task 1 is available to process. Available tasks = {1}. - At time = 3, task 2 is available to process. Available tasks = {1, 2}. - Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}. - At time = 4, task 3 is available to process. Available tasks = {1, 3}. - At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}. - At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}. - At time = 10, the CPU finishes task 1 and becomes idle. **Example 2:** **Input:** tasks = \[\[7,10\],\[7,12\],\[7,5\],\[7,4\],\[7,2\]\] **Output:** \[4,3,2,0,1\] **Explanation****:** The events go as follows: - At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}. - Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}. - At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}. - At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}. - At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}. - At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}. - At time = 40, the CPU finishes task 1 and becomes idle. **Constraints:** * `tasks.length == n` * `1 <= n <= 105` * `1 <= enqueueTimei, processingTimei <= 109`
You can just use brute force and find out for each language the number of users you need to teach Note that a user can appear in multiple friendships but you need to teach that user only once
Array,Greedy
Medium
null
769
hey everybody this is Larry this is February 15 2024 and here I am trying to do a random problem that I haven't done before so let's YOLO let's go orang 6 or 769 I can't even read the 769 Mass Max chunks to make sorted all right so given iner array of length end that represents a peration of inte in the range zero n minus one we split our away into some chunks of chunks some number of chunks and individually s each chunk you have to can the res to S away return the lock s away what does that even mean we swim chunk I see that's kind of awkward h I mean so basically uh you can think about this as intervals but I don't know if that's the easiest way that's why I'm thinking about it first um feel like I've done something similar recently what was I doing but basically the idea is that okay um this is a permutation so every number you know where it's supposed to be so four in zero and four means that there's a you can say there's a zero you know oh yeah this was wasn't this one but a variation of this was in um was in uh whatam call it Josh Chen's contest the other day um I think that was like the q1 that's why I felt similar I was like I think where I remember it from but uh but yeah but basically this number means that there's a segment from 4 to zero right so that you have to sort them and yeah and that's pretty much the idea um yeah I mean hm yeah it's basically exactly the same prom as that prom trying to think where it is different but um maybe I'll paint Josh afterwards and be like hey oh n also n is equal to 10 which makes this well I mean this is way easier because n is equal to 10 but it is a little bit awkward huh unless I'm like really misunderstanding some parts of it but um but yeah but basically the idea is that okay uh let's say there's this four here right if there's this four here that means that um an index zero that means that well this number has to sort with the fourth position no matter what so then you kind of create a SE a line segment from 0 to four and if you kind of create all these segments then you can kind of merge them together to um to put them as chunks because if because you have to merge them uh as one chunk because otherwise there's no way to uh um there's no way to uh whatam call you can't because if you don't put them in the same chunk like you have two overlapping segments then um I don't even I can't even English anymore if they're not in the same chunk then it just doesn't get through the boundary right because you can also prove by contradiction I guess um just because then otherwise you need like a other sorting thing which for this PR doesn't work so yeah so with that said so we can do something like for index uh X in enumerate aray right so maybe we can have something like uh and actually Josh taught me this I mean he reminded me of this trick um because I actually usually you know this is segment type things but you actually have an optimization with just counting the ins and outs of the segment so you have something like a pre right U times n + one maybe I think it's n+ one and then here that means that if X is not equal to index just double checking with zero index CU I think on chares it's not then now you write um you know so then now this is the start so we add one and then you subtract one and this is just like uh writing the segment frame right um in terms of prefix some with a difference array but yeah and then after that we can aggregate that all up so let me double check in my head hang on yeah so maybe chunks is you go to I just Z one I guess it doesn't matter right and then current is equal zero and then for X in prefix right um current to do X and then if current is equal to zero then we increment chunks and then that's pretty much it I think I may be off by one but I think that's the general idea um here we probably benefit from having more test cases uh right so that would be two and then maybe like we just do even this it would be also two um but then if you had something like this then that would be one again something like that uh okay so this is why we test this expected three oh the two counts as one I forget but so I thought it would be two but then that was one um and this is this not one oh no this is two all right let me double check then maybe I have an off by one somewhere this feels a little bit weird that should be good okay so zero and one right so then this should be uh one chunk right um I'm having an off by one yeah I didn't know if I needed the plus one to be to keep it exclusive so maybe that's why oh but now everything's wrong okay well H okay so zero is the beginning of two line segments here 0 one so then two it ends but then it should count twice uh because here now it means that this segment chunks but then this one is zero right but I'm not doing that right maybe this should beat this but then now why is this wall four oh because then now I don't need the extra number at the end okay fine because now I'm not going plus one all right fine uh let's give a spin and that's pretty much it I mean I guess I a littleit it's always tough for me to know whether I need inclusive or exclusion still a little bit lazy about this one but yeah uh but the funny thing is that I literally did do just this contest or this prom with in Josh's contest though his end is like 10 to the 15 or something not 15 10 to the 5 or 10 to 6 um because as you see from this algorithm it's just linear right so it's pretty straightforward um I do wonder what people write yeah okay so I people did use the o n type thing so I don't know why this is um yeah I don't know why this is I don't know why n is 10 here to be honest that's why I was like curious if anyone did it some weird sloppy way I guess you can also do it with n Square um like n square is a little bit I mean I don't even n Cube really like n squar subarray and then n Cube or n check so then I guess it's n cubed that way I don't know it's a really weird problem for that reason but uh but yeah that's I have for this one let me know what you think stay good stay healthy to your mental health I'll see youall later and take care bye-bye
Max Chunks To Make Sorted
largest-plus-sign
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[4,3,2,1,0\] **Output:** 1 **Explanation:** Splitting into two or more chunks will not return the required result. For example, splitting into \[4, 3\], \[2, 1, 0\] will result in \[3, 4, 0, 1, 2\], which isn't sorted. **Example 2:** **Input:** arr = \[1,0,2,3,4\] **Output:** 4 **Explanation:** We can split into two chunks, such as \[1, 0\], \[2, 3, 4\]. However, splitting into \[1, 0\], \[2\], \[3\], \[4\] is the highest number of chunks possible. **Constraints:** * `n == arr.length` * `1 <= n <= 10` * `0 <= arr[i] < n` * All the elements of `arr` are **unique**.
For each direction such as "left", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.
Array,Dynamic Programming
Medium
221
84
lead quote problem 84 largest rectangle in histogram right so the problem gives us an array of integer Heights and basically there are just a bunch of bar Heights and our job is to return the area of the largest rectangle that can be created from the histogram like for example for this array of integers the greatest one will be 10 right to keep in mind that the base can also be considered but since this base is of area 8 only so the largest is still 10. right so yeah see in this example it shows that database can also be considered if it's the largest area so the approach I had to this problem was to use a stack to store the starting index of where it could something in X of where it where the height started and the actual height of that index is started so it can be quite complicated but hopefully I can explain it well I'm using a for Loop to iterate through every number in the histogram and uh yeah so I have a variable called start here that I initialized to I'll be using start later on to save the value of where the starting position of that height could have been now right so since my stack is empty I'll just push it right so I'll push the start which is zero and then the height I right height I is 2. so these are my stack notes like now and then I increment I should start so start because I and now since my stack is not empty I Can Begin checking whether or not the top of my stack the height is larger than the current height right but for instance this instance it is right since 2 is more than one so we enter this while loop right so I have the variable top here to keep track of the top of the stack right so now our top looks like this and now I compute the uh area right the area you had made because uh so because I need a two here currently extend forward anymore so we know for the height the area ends here right so there is basically height right top dot second which is this times the base right so in this case the base is I is 1 minus uh top first zero right where it started so what minus zero so this will become two right for now our largest is two I already stuck with the top first zero and then I pop this right so right now I then can push a news variable in that has a start which is zero and then height I right which is one right so what this means is now I have a height of one that starts at index 0 right because uh if this I have a height of one here that is still extending forward right okay next off I increment I again so if two and start is re-initialized to two re-initialized to two re-initialized to two and since my stack is not empty so we hack right and since one is not larger than five so I will just push right so let's push start two and five okay then increment start and I and now we have six and since 5 is not more than six so we push as well so this would be 3 6 and then we increment and now we are looking at uh two right and now things six right six the top of our stack six is more than two which means uh from this point onwards six cannot be push forward anymore right so the max height basically ends here right so we calculate the area right replace top again so top is three and six so the max will be uh 40 seconds which is six times I is four minus total four is three right so this one is basically uh six right so our largest is now six so we pop this and since this is a while loop then we check again right and since 5 is more than one F5 is more than two again so we have to repeat the same thing there we go like this and then we compute the area so it will be top dot second so it'll be five times I is 4 minus top left first is two right so this is the two which in turns gave us 10. so now our largest is replaced once again with 10 right so you can see the index starts at two and then it ends at I right so we have uh we have this big box here and then we pop this and then uh two is more than one so we can't really do anything here but to push right oh uh before you push remember that we uh update start right so since start is now top that first is two so V2 and then uh yes and then only we push right so we're pushing two with two yeah so what this means once again is that here from starting from this index two I have a height of two that can still be pushed forward right so the max height has not ended yet okay this is to prepare for yeah another preparing thing but this is uh just to indicate that a height of two that starts off from index two uh is basically is possible to compute the area down here moving on we are looking at the last element which is five right starting to get re-initialized re-initialized re-initialized and since 2 is lesser than 3. so we can do it much about it but to just push it by pushing this again so it will be five and three right so right now our largest is 10. based only from our height loan only right so we have not considered the base yet right so there's a chance that it could be there could be a Max size down here like a base right so to do that for the rest of the stack we will calculate from the size right when it says from the on the back right because for it to still stay at the stack means that the height has reached all the way to the end of the array so likewise we have another variable top here and then I replace it with five three right of this so we compute this uh the area so this five three comes from this right so zero one two three four five for this and has a height of three so we compute it will be three times size is the amount of uh integers in the array so in this case it'll be six minus uh five right so this is one and this is three right and since three is lesser than ten we don't do anything after that we pop it so this gets deleted and now we replace it with two and we count again right so top second times six minus first is two right so remember these two comes from here right these two comes from here from the start of the uh from index two so we can't we calculate the size this will be eight right once again since 8 is less than ten so it won't be updated and this will be popped and for the last one which is zero one that started all the way from the beginning right so we compute will be one times six minus zero so basically this will give us area of six right so one two three four five six right and thin six is also less than ten uh the largest state the same and then uh we just returned right so return 10. so that's how my algorithm works that's all I have to show thanks
Largest Rectangle in Histogram
largest-rectangle-in-histogram
Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_. **Example 1:** **Input:** heights = \[2,1,5,6,2,3\] **Output:** 10 **Explanation:** The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area, which has an area = 10 units. **Example 2:** **Input:** heights = \[2,4\] **Output:** 4 **Constraints:** * `1 <= heights.length <= 105` * `0 <= heights[i] <= 104`
null
Array,Stack,Monotonic Stack
Hard
85,1918
27
Hello everyone so in this video where going to discuss a lead code problem remove element show friends of date value from wait are and date you in place so what do you mean by in place and this is our input are and this is d Value of this value which is de of this value they can't use additional data structure and additional you do they have you perform in de life erect self and this problem after removal of which de of de value it is ok tha order of on the elements Example in d second they are get zero one four zero three also return something like 0003 so d order of d element change but and task you just remove which d of d live value and finally they have tu return value so every in d first example Acharsh of well in are and date tu in place d problem three d number of elements which are not equal tu value tu one directly return let it tu get password check d jevan are date we have removed which d e of d jevan value from d Jeevan is the solution of this problem so on example output should be five because d total number of element which is not equal tu are five one tu three four five and d remaining element is black because d test and look beyond our output which is five So every ho you can approach this problem this way you can get these points from late I come so late suppose if this is inferior and they have you remove which is from this is inferior well no these points bill move through this are in true date one is slow painter and inside what do you duet over complete is not equal tu it min they have found and element which they need tu cup in d are so they simply take date value and assign it tu d rectangle index and give they Actually increment I so let's see the same an example so currently Bill helps in keeping date value in d are start we bill essence zero to d next index this value on stage every and we increment i to d next index so it bill also get increment no we again check value g also move to d second index This 2 and 2 this actually removes d element you remove they don't move d next they only move da root index because i actually helping that you remove this value so every i stage date d from place and j moves so come every d value tu it's next because tu remove which d e of d given value and go so fifth index value zero and zero is not equal tu 2 so henceforth bill assign this value bill vice versa zero and no both de pointers bill move it no date index something like This So Three Bill B Gan And Her It Bill B Four So I Bill Come Her And K Bill Come Her Listen D Value Index Bill B Our Answer Because D Last Place Where They Need You Remove And Element But They Didn't Find Other More Elements So After Removal of tu our output come out tu be five so we put de index its zero one tu three four and five so this five and another so in this problem d basic idea we are using these tu pointers i n k d purpose of Which is you simply traverse d are compare d value of h industries with d value you want to remove and d purpose of is you actually remove d element they are assignment when they actually find n value come h index note equal to d value which you want Tu remove no let move id and cd demonstration of this algorithm step by step so friends before we start in how if your new tu mi channel please subscribe tu mi channel and click the bell icon so date you never miss other updates so this is This is the code and let's live with this which we discussed in our previous slide. We are calling removal element method passing in this here and we have values ​​here which we in this here and we have values ​​here which we in this here and we have values ​​here which we want to remove which are in this are so we are not creating. This tu painter as they know d purpose of jj2 simply traverse d are and compare d value of j d index with d actual value you want to remove so we are using a simple per loop so j Tara from zero so come d start elements one tu three four five six seven come and zero is give 8 so this on loop bill execute and so you already discussed they have you simply provide one if check date weather value it index weather it is equal tu value not so currently valued change zero and Zero is not equal tu d par this condition come out tu be true it mains date they have found a value which is not equal tu and which they need tu cup in d are so d they cup in d and it is the same rectangle painter S of i so number d elements and cup only dose elements which are not equal tu software Next Like This Comment Equal tu d value wich u want tu remove so d condition in floc tu be true and value d se index because i and ju pitting You de se index and after 14 value which is not equal you they simply increment came increment j value so this you actually finding de value you want you remove simply increment this question because in the future your cold be a value which you want you migrate you This index because they want tu remove this tu so let send future there is three zero four three should come every and this tu should get removed so this I should study from place tu know value of three li den aate so lubil execute on this No value index against you and you are equal to you are on de condition and they do nothing value which is not equal to you live well and they need you cup this value in de are and this index is not on de right place on de value helper And shifting of these three from every tu every they are just assignment so d condition a block come out tu be true they assign d value and these three bill come every like this come every so they simply increment execute n value note on equal tu and value assignment and give they simply increment i because seven comes so look on this execute so no every valid index note return d value which is being hall by i which is five over this anyway d last place where they continuously remove d e and before date They have removed which d e and d arrest on zero index they have tu return value which is d total number of elements which are not equal tu our live well so every they head 013 04 visual note equal tu and if you count dem they have One Two Three Four Five So Whatever Value I Holds Date Bill B Your Answer So They Simply Return 5 And They Have Also Modified D Are In Place Me Removing Which D E
Remove Element
remove-element
Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The order of the elements may be changed. Then return _the number of elements in_ `nums` _which are not equal to_ `val`. Consider the number of elements in `nums` which are not equal to `val` be `k`, to get accepted, you need to do the following things: * Change the array `nums` such that the first `k` elements of `nums` contain the elements which are not equal to `val`. The remaining elements of `nums` are not important as well as the size of `nums`. * Return `k`. **Custom Judge:** The judge will test your solution with the following code: int\[\] nums = \[...\]; // Input array int val = ...; // Value to remove int\[\] expectedNums = \[...\]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i < actualLength; i++) { assert nums\[i\] == expectedNums\[i\]; } If all assertions pass, then your solution will be **accepted**. **Example 1:** **Input:** nums = \[3,2,2,3\], val = 3 **Output:** 2, nums = \[2,2,\_,\_\] **Explanation:** Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). **Example 2:** **Input:** nums = \[0,1,2,2,3,0,4,2\], val = 2 **Output:** 5, nums = \[0,1,4,0,3,\_,\_,\_\] **Explanation:** Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). **Constraints:** * `0 <= nums.length <= 100` * `0 <= nums[i] <= 50` * `0 <= val <= 100`
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
Array,Two Pointers
Easy
26,203,283
61
Hello Hi Everyone Welcome To My Channel It's All The Problem Rotate List A Very Famous In Terms Of Interviews And Learning Do Subscribe Online And Basic Important Questions Giving Roti Ke Play List 12345 and subscribe the Video then subscribe to subscribe our 200 paas dry When Solving Problems So Very Simple 200 First of All What You Will Find Details Not So If Start From Near By Using a Point at Which Includes Pay Will Go This Tell What Makes Is Not Done Also One Spiritual Not Obscene Disti Don't Believe in What Is the number of this so like a good number of it's something 12345 Show the setting of can we do Well this is oil Are not willing to this time Not to back side 900 Will make little daughter Will start from airtel to lotus Notes Life in Total K Mode On Ki K Moat Length Notification Mode Landlord And This Ain't Been Those Who Died In Time Road Rights Will Go In That End Total Note - K Malik Pic Note - K Malik Pic Note - K Malik Pic 8 - Total - K Mode Languid Mood Detail 8 - Total - K Mode Languid Mood Detail 8 - Total - K Mode Languid Mood Detail Point To That Was Not Willing 7.5 Scam Point To That Was Not Willing 7.5 Scam Point To That Was Not Willing 7.5 Scam Affidavit And Know He 0.25 - 263 Language Affidavit And Know He 0.25 - 263 Language Affidavit And Know He 0.25 - 263 Language Shift Detail Pointer In Sector 53 Notes13 6This Will Be Our New Carotid List Has Been Exaggerated And Will Not End With Radish Is So Instinct Of Briggs Are Not Display Of Wealth Insisted Of We Will Just Look For The Not Previous Will Tell Her And Total Not Mean That Point Will Avoid A Key And Make Detail Dot Addition Anil Bread So Day Will Discover New Bread 109 Africa's Test Ride Soft Implementation Subscribe Cylinders 2019 2013 Otherwise World's Number One 90 Node From And Will Run Wild Water Is Not Ban Torch Light Plus And Also Update Detail What And What Next Services After But Elva Edison Adherents Of Doing This You Will Be Amazed That Not Added To Had Basically Joint Loop The List Is A Love Eastern Will Get Available Number Of Throat End Points And Phase Points To Rotate Point Which Will Be Easy Language - Rotate Point Which Will Be Easy Language - Rotate Point Which Will Be Easy Language - K Mode Like A Man With Login Start By Telling Her From Behind And Don't Middle Point 8 - - Greater Than One Will Get That Byte 8 - - Greater Than One Will Get That Byte 8 - - Greater Than One Will Get That Byte Pimppoint By Taking This Point Se Pimppoint By Taking This Point Se Pimppoint By Taking This Point Se Secretary Veer Vid U Ko Hang Till Dawn Next Wife Husband Darling So One Should Visit Rawat New Head Cheese And subscribe The Amazing List Play List Wishes Celebs Caught Off-Guard 200 G Code Is Compiled And Were Getting Affected Answer Sunao Ve Can Confide and Submit Solution or Antiseptic What is the Time Complexity Subscribe Time Complexity of Total Subscribe and Complexity of Life This Video Related Problems Play List for the Time of 2008 Must Subscribe My Channel subscribe To My Channel Share So That Everyone Got Some Help Thanks for Watching
Rotate List
rotate-list
Given the `head` of a linked list, rotate the list to the right by `k` places. **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[4,5,1,2,3\] **Example 2:** **Input:** head = \[0,1,2\], k = 4 **Output:** \[2,0,1\] **Constraints:** * The number of nodes in the list is in the range `[0, 500]`. * `-100 <= Node.val <= 100` * `0 <= k <= 2 * 109`
null
Linked List,Two Pointers
Medium
189,725
1,184
hey guys welcome back to my channel and i'm back again with another really interesting coding interview question video and this time guys we are going to solve question number 10184 or lead code called distance between bus stops before i start with the video guys if you have not yet subscribed to my channel then please do subscribe and hit the bell icon for future notifications of more such programming encoding later videos let's get started with the problem statement now so basically guys we have a bus which has got n steps so you can see here in this example there is a bus and it has got like four stops here the bus can either go in a clockwise direction like this or it can go in an anti-clockwise direction like this anti-clockwise direction like this anti-clockwise direction like this we are given a starting bus stop and a destination budget and we are given a distance array so in this distance array we are given a distance between each bus stop uh so from stop zero to bus stop one the distance is one uh from bus job the one to two the distance is two three and then so forth four but because this bus can go in both clockwise and anti-clockwise direction clockwise and anti-clockwise direction clockwise and anti-clockwise direction so for example if i have to go uh from bus stop zero to one the distance will be one but if i have to go from bus stop zero to bus stop three then either the distance could be one plus two plus three which is five or uh which is six or it could be uh directly going from burst of zero anti-clockwise to bus stop three then anti-clockwise to bus stop three then anti-clockwise to bus stop three then the distance would be four okay so we have to find out the distance between the starting desktop and the destination bus stop uh such that it's the minimum distance so basically we have to find out the distance both in clockwise direction and in anti-clockwise direction and return the anti-clockwise direction and return the anti-clockwise direction and return the minimum distance okay so these are the other examples guys and i hope they are also clear so here you can see that we are going from burst of 0 to 3 and the distance is 4 instead of 6 okay because we have to return the minimum distance constraints are pretty straightforward guys the total number of bus stops range from 1 to 10 to the power 4 the distance length is 10 to the power 4 maximum the starting and destination values are ranging from 0 to n distance value could be from 0 to 10 to the power 4 okay so i hope the problem statement is clear to you guys let's jump to the solution approach so to solve this problem guys what we are going to do we are going to actually just find out the clockwise distance okay so the clockwise distance i mean the distance between the smaller stop to the bigger stop okay for example if the stop is given to me the starting stop is given to me is 2 and the ending stop is given to me 0 then i would just find out the distance between 0 to 2 instead of 2 to 0 okay so what i'm going to do i'm going to find out the clockwise distance and then i am going to find a total distance between all the first off so just going to sum up all the distances and anti-clockwise and anti-clockwise and anti-clockwise distance is going to be just the subtraction of total distance with the clockwise distance okay and finally i'm just going to return the minimum value so i hope the solution approaches clear to you guys let's jump to the coding part is really uh really simple guys all we have to do is first of all find out if uh starting destination is greater than the ending destination or not so sorry if starting bus stop is greater than the destination bus stop or not so if start is greater than uh destination we're just going to swap the two values together so 10 becomes equals to destination becomes equals to start becomes equals to 10. now that both the values are swapped we can actually go forward with our distance calculation so i'm just going to write here clockwise distance which is going to be initialized to 0 and then the total distance which is going to be initialized to 0 as well so for integer equals to start to i sorry for integer equals to 0 to i less than distance dot length i plus 1 okay so if the value of the i is ranging between starting and destination so if i is greater than equals to start and i is less than equals to destination that means that bus stop lies between our journey okay sorry not less than equal to just less than because here we can see that the destination bus stop is excluded from the actual bus stop so if i is greater than equals to start and less than equals to destination it means that the ith burst of lies in our journey so i would just add that burst of in my clockwise distance so i plus equals to distance i otherwise i am just going to increment the total distance with the if distance value finally the anti-clockwise distance so nt the anti-clockwise distance so nt the anti-clockwise distance so nt clock distance is just going to be total distance minus the clockwise distance and just going to return math dot minimum off and t clock or clockwise okay let's run this code guys let's see if this works so you can see guys that one example is pass and hopefully the others will pass as well and there you go let's talk about the time complexity guys so the time complexity is order of n because we are going through all the bus stops only once and the space complexity is order of one because we are not using any extra space so that was the solution guys i hope the solution was clear to you and i hope you like the solution and if you do then please do like this video and share this video with your friends as well please do subscribe to my channel and hit the bell icon for future notifications uh if you have any questions comment suggestions for me write down in the comment section below definitely gonna address them as soon as possible also guys i make your videos everyday from monday to friday so thank you so much for watching i'll see you guys in the next video until then take care and bye
Distance Between Bus Stops
car-pooling
A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`. The bus goes along both directions i.e. clockwise and counterclockwise. Return the shortest distance between the given `start` and `destination` stops. **Example 1:** **Input:** distance = \[1,2,3,4\], start = 0, destination = 1 **Output:** 1 **Explanation:** Distance between 0 and 1 is 1 or 9, minimum is 1. **Example 2:** **Input:** distance = \[1,2,3,4\], start = 0, destination = 2 **Output:** 3 **Explanation:** Distance between 0 and 2 is 3 or 7, minimum is 3. **Example 3:** **Input:** distance = \[1,2,3,4\], start = 0, destination = 3 **Output:** 4 **Explanation:** Distance between 0 and 3 is 6 or 4, minimum is 4. **Constraints:** * `1 <= n <= 10^4` * `distance.length == n` * `0 <= start, destination < n` * `0 <= distance[i] <= 10^4`
Sort the pickup and dropoff events by location, then process them in order.
Array,Sorting,Heap (Priority Queue),Simulation,Prefix Sum
Medium
253
413
So Hai Gas Welcome Back Tu Me Channel Hi Elements And Difference Between It Tu Consecutive Element Is D Se Meaning Arithmetic Kab Bolenge Se Hai Ab Confusion What Is The Meaning Of Difference Look One Tu Three Four Taking One Tu Three Tu One Ke Mein Kitna Hai Difference What is the difference between one three and one? Our difference from one is ok and these consecutive numbers are also possible. This is how we have to tell how many times the total is possible. We have to tell. Suppose I am taking 2 3 4 so what I am getting. Three and you have a different effect. Four and three have a similar effect. Take these numbers also in 1 2 3 4. Why did I take your card number because what is written in it. Please group of three is three. These can be more than three and what is written can be different, okay, what is there in this, there is three in both of them and there is tax in this, meaning 4 inches, please three is present, isn't it so this is also velvet group, so how many of our total? Answer: Aaye Teen Aaye Hai means how many of our total? Answer: Aaye Teen Aaye Hai means how many of our total? Answer: Aaye Teen Aaye Hai means three total sa I have possible here I have D number of element have a list three and D difference of D conspiratorial element is D se ok possible so date so no suppose ever I have D number with name date is One two three four no if I want you find d Hello friends okay so what you can see every if I have these numbers one two three if I take 2 3 4 then this is also a then take 1 2 3 4 also So this is also a sub A, then I propose, then I take it, if you play one, three, four, A, he will not come, then what will I do, after breaking it, I will take it on 2, 3, 4, 8, still he will not come, even if I take 348, he will not come. Then I take 45, still it won't come, then what do I do, I take 856, still it wo n't come, then what do I do, I take 5 6 7, this is how it is, this is also possible because the difference of others Tu consecutive number is this from each it mains they have total four group and force is our possible tha have d difference from is ok so now let's go to our example so I just took the example in it we have found out ok What do we have, one you three, how many elements did you come in time, one you three, neither I am considering in the morning, what approach we can take, we were given 83 eggs, three elements should be present, I According to that, I am telling you that these are our three elements, you can take anything, be it 5-6 level here, at can take anything, be it 5-6 level here, at can take anything, be it 5-6 level here, at nine, you are fine, take these also, I will just tell you the approach, what do we have to do, so what can you think of each. Simply D What is the last element - 1 U Celebrate Okay if the difference of the consecutive means the difference of these two and the difference of these two should be from meaning what is this D condition every tha if I will do this subtraction then how much should it come means difference this is this I is consecutive Okay, what does it mean, support, let's see. 1 2 3 4 Okay, if I am talking about these three, then how much will be the value of current? How much will be the value of total also? Here is one because how much time have I got till now. But when I come here, you will come above the three-four, then what will happen to me, come above the three-four, then what will happen to me, come above the three-four, then what will happen to me, how much will be the value of one current, I got the face but the current but how much is the total, you mean contributing, you are me, final means the value of the final has to be counted, will it not come in it? Meaning, what is the meaning of total, now all of us who have met me are telling us what is the total and current, the present one is only telling him like one, you have taken it in three, four, I am telling you what is the current, tell me the current. Right now we had only 1 2 3, further we have 2345, right, you are telling in the big three four current whether this is with us or not, hey I, but what is the total, told that I also have 1 2 3 2 total, told that I also have 1 2 3 4 There is also and one you are three four also I have me total equal you three link current how much was here current equal you were ok so this is telling we have ok now what do I do simply I did it here only If this condition is fulfilled then the current also has to be incremented and the value of current has to be included in the total. If this does not happen then what will be done in S. We will keep the value of current at zero. Okay, what did I do after that? So, we have taken this example here, so what have I done, current equal to zero, total in the value of total, please connect equal to zero, okay, initially the value of both, what have I taken, zero, then what have I done, look at the gesture. In this matter, I am telling you dry and I am telling you, look, 1 2 3, first I am one, you are three, first leg, how much value of current will come in it, one is okay, we will have to start only from I = 2, we will have to start only from I = 2, we will have to start only from I = 2, you are What is the reason because I have used here every minus one and every minus you means there should be an element before also okay so what I did is starting from i = 2 so what I did is starting from i = 2 what does I bill do mean that here the question elementary start If I do this, I found one 1 2 3 0, so I took 1 2 3, what is the value of current, why is it one, because if we get one time, which means our commission is fulfilled, then the difference of the consecutive is coming from ours, okay. Then what is the value of total? Total plus current total. How much was the relation. Zero and zero plus one. I made plus one. How much did we get? Our total went to 1. So I wrote here how much was the total. One. Similarly, I went ahead and then what? As soon as I went to 2 3 4, what did I get? What is the value of the current? What is the increment? By one means how much has become from one. Because I have found one more. Par with me current value ok now I have to find the total how much is the previous plus current previous our how much was the value one a was going now no I have no tu move tear I have then how much will a be 1 + 2 = tear I have then how much will a be 1 + 2 = tear I have then how much will a be 1 + 2 = 3 2 mode plus half Because what do I have 1 2 3 And as soon as I got 2 3 4 As soon as I got it, along with that I also got a leg of one two three So how much is this done How much is already one If the condition was I have guessed that it should come from the computer's difference, so I have taken the value of current plus the value of total and simply, if it is not so, then the value of the arrangement is made zero and what will be the value of total, okay then I am simply this is the total, son. I will get it done, okay, so let me see what I did after that with current and total zero, here I have simply started from length and in this simple condition, you have become current, did not date it from D, think total, I hope you guys. Would have explained thank you
Arithmetic Slices
arithmetic-slices
An integer array is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same. * For example, `[1,3,5,7,9]`, `[7,7,7,7]`, and `[3,-1,-5,-9]` are arithmetic sequences. Given an integer array `nums`, return _the number of arithmetic **subarrays** of_ `nums`. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 3 **Explanation:** We have 3 arithmetic slices in nums: \[1, 2, 3\], \[2, 3, 4\] and \[1,2,3,4\] itself. **Example 2:** **Input:** nums = \[1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 5000` * `-1000 <= nums[i] <= 1000`
null
Array,Dynamic Programming
Medium
446,1752
724
in this video we are going to solve one very famous index let me explain you what is the use case here so you have been given one array and you have to find out one index one number from where all the web edition of all the website element must be equal to addition of the right side of element so in this case I am giving you direct answer if you see this element right so if you add 1 7 3 it is the available right if you add here all those three it become Diagon 1 plus 7 plus 3. and if you also add here five plus six so everybody so in this case I can see this 6 is the pivot in pivot element so this is called the pivot element but I need the index so what is the index of that so index is 3 so I can say the output is t take this example so if you see here I'm just straight forward giving the answer so if you see here this is the pivot index how what is the website is nothing so some of the left side is equal to 0 and some of the right side is equal to 1 plus minus 1 is equal to 0. so in this case this 2 is the pivot element and the index is zero so I can say output is you right in this case if you see here the same element but in the different sequence you could not find out any such index via website and right side elements are equal after addition those elements so in this case if you see if it is if you suppose consider this is one is an index element then addition of this is the one but left side is nothing if you consider 2 is the in pivot index so website is the 1 and Y is equal to minus one which is not possible if you think this is the pivot index so the website is the three right size no so we cannot able to find out the pivot index in this given example so I can say output is equal to -1 if you could not find out the pivot -1 if you could not find out the pivot -1 if you could not find out the pivot you have to return the minus one in this case here too I think here also there is no any possibilities so return would be the minus 1. let me check this one so here is the 2 5 okay yeah so if you kiss see this is the pivot element right how two plus three five minus 1 4 so this side addition is also for this side direction is also four so this is the pi part element and what is the index of that index is 3 so output this is the use case how you are going to solve that so if you take the first example here this one which we discussed with this example so they are the many way to solve that one is a very basic way to solve whatever you do we will run the data from jio index if the numps length and this is my first Index right 5 volt so you are here so then do one thing from here you run the another two for Loop one for the website and one for the right side and take the sum of the web and take the sum of the right side and check if website equal to the right side sum you can return the index I right you can return the index but if you see the complexity is high right so this is obviously the o n Square because they are the two for group is running on that so this is we can further optimize and we can directly jump into the one of the good approach foreign so the basic thing is that before we start the code you take the sum and sum would be have the of the all the element so in this case IV sum would be the 8th 11 plus 7 11 plus 6 17 70 plus 5 22 and 28. right so 2028 right so whatever you do first we will keep the web sum is equal to zero if you want to consider from here if you take the first element here so that right now for this index what is the left sum web sum is zero nothing is there and what is the right sum write sum is equal to Total sum minus the first right so minus the num size if both are equal I can say it's okay we can return the index if it is not then what I will do I will increase the then I this in this then I will check this element right in that case for the seven if you consider the seven then what is the web in website sum then website sum would be the foreign because this first element and then this I should be minus from the right side right so we will do the right sum minus this one that might be a Vex kind of thing so let me take one example how it works and then if you see if something have to update in the code so this is a basic logic so whatever you do first you write one method and that method will return the sum of the L that's okay after that we after that take one variable that is the web sum keep the Geo write some time being keep the sum so now according to this case we have some had to be 0 and write some would be the 28 right iterate 1 from 0 to all the elements event okay now so we are in the first element so for the first element of yes if one is the pivot then web is the zero but right side all the element accept the first element right if you see this is the pivot element then website is nothing and right side is from here to here except this one so you have to correct your right side so what you have to do right side minus right side sum minus current number so in this case your right side become the 28 minus 27 now we have the website 0 right side 27. now check if wrap sum equal to write sum then and there it say if we return the index I if that is not the case then if we move the I become the here in that case my web sum should be incremented by the first element right so then you have to do the left sum equal to react sum plus num I okay let me check so now once it is go up right now I is equal to 1 0 in that case sum is equal to 0 this become the 27 that is not the condition correct this reaction becomes the plus 1 so it becomes the one now I is equal to 1 I become here you start from here so write sum is called to write some minus num1 what is the num I now I is equal to 7 right so U again minus 7 it become the 20. is 20 equal to 1 no again if we come here what is the reaction we have some increase by the num I is 7 so it become the it again it will go up I is equal to 2 num I is equal to 2 is equal to 3 right sum will be minus by the num I is 3 so minus 3 17 this 17 equal to 8 no then come here left some increment by the num I is 3 so this becomes the 3 available go up I is equal to 3 means 6 so this becomes the six come here sum should be reduced by the current number is 6 so 17 minus 6 now check left sum is going to write some yes left sum is equal to rights because website is variable and right side is also available and then we return the I what is the i is equal to 3 and you will get the answer okay so let me see in the code how it works it's very easy things you can solve in many ways by let me do the code and show you people uh so what if you do first make one method that we will tell you some of the elements right you can pass there in here you take one variable and then we use it to decrease it we can directly take the sum of that so sum equal to I it will tell you some of the elements now come here we take one variable uh reaction that I be K upon 0 as we discussed write some starting time for this method and pass this array now we have the right side we have all the sums for the evening and then we will start and go through the all the elements right and first I have to reduce the lights and because I have taken the total element some of the total element of the table so minus equal to the current element right so I do the minus here or you can also do the right sum is going to add some minus plus Stitch I'll keep this end here and now if you check that sum equal to write sum then here only we return the index otherwise we have to increment we have some right we have to implementation you can add never mind and if it is not able to find any pivot index they will return minus 1. that's what sufficients would work but we check whether working or not so it should work so it is saying that uh sum is equal to some type who is here right yeah it's working fine right and also what you can do instead of this having the this method you can use the Java 8 functionality and here you can directly call the average dot stream you pass your average it will give the sum so you can save one method no need to add the method here okay that should work yeah and submit the code that's it let me just wait for submitting the things you should work I have already tested you can see this is the I'm going to use that you can get it and if you yeah um you just check whether this who is giving the good widget whether having this method or adding one separate image of other stuff but thank you very much foreign
Find Pivot Index
find-pivot-index
Given an array of integers `nums`, calculate the **pivot index** of this array. The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right. If the index is on the left edge of the array, then the left sum is `0` because there are no elements to the left. This also applies to the right edge of the array. Return _the **leftmost pivot index**_. If no such index exists, return `-1`. **Example 1:** **Input:** nums = \[1,7,3,6,5,6\] **Output:** 3 **Explanation:** The pivot index is 3. Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11 Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11 **Example 2:** **Input:** nums = \[1,2,3\] **Output:** -1 **Explanation:** There is no index that satisfies the conditions in the problem statement. **Example 3:** **Input:** nums = \[2,1,-1\] **Output:** 0 **Explanation:** The pivot index is 0. Left sum = 0 (no elements to the left of index 0) Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0 **Constraints:** * `1 <= nums.length <= 104` * `-1000 <= nums[i] <= 1000` **Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/)
We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1]. Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i].
Array,Prefix Sum
Easy
560,2102,2369
3
Hello guys welcome to bana de video mein seedhi sub heading code viewers problem waste oil will subscribe without feeling character suryavanshi rings to find the length of the longest without editing characters means all the characters with unique in the left side example support zoom string events Which you can observe fasting baby seeervi all characters which is no different from being a you can also observed all characters maximum subscribe quote 10 answer so let's do you think about this a b c d a b c b i ko subscribe The Channel and subscribe the Channel subscribe 2030 to the first subscribe to the Shivam Length of the most beautiful Aisi 909 Maximum equal to one which consists of strands after submission a Wick consisting of unique character and stored in data structure which is State Civil Service Sector Egg OK Subscribe to Forward Quest for Another Clue 2012 Phone No of the incident which substring is Ajna unique and how to make no difference Aaya usne character b saver of the character of baroda ball style statement by citizens have been so ifin singh character of time ok Come Back To My Channel Don't Forget To Subscribe I Know The Character Of All The States 2019 9 Points 1199 E Who Is Looking In Set I Have Never Found Correct 80 As Per Traffic Jam Day Vishal Sundha Festivals In This Will Obviously Also Unique Pattern Storage Device set cnn directly subsidy and subsidy subscribe now to the bca bba bca and bsc in repeating this question on half repeat these don't know the amazing okay from previous please directly so ifine element directly menu subscribe and also unique point this point Subscribe Now That Irfan Have Dashrath Singh Behind Go Into Unicode New Voice Turn On The Go For My Apps Subscribe Do n't Forget To Subscribe The Channel 02-02-2014 02-02-2014 02-02-2014 To Agar Sabme Badnaam Karenge Looking At This Simple See Baby So Not Have All Characters Unique And Subscribe And This Point When The Skin Is This Is Again Hawa Subsidy Is Having All Characters Disrupting Life Events And Painting With See So I Don't Want To Is Just For Ca Students Went To See You Can Move 15232 Subscribe Elements In Subscribe My Subscribe to the channel now reduce it to the lowest possible Nokia 1020 Pandit Already There Must Be A Solid State How Can Reception Also Unique Character Suid For This Point To Point Se Meanwhile Election It's Something Is Consistent Unique Characters Class Ninth Twisters Begin With Saturn Will Have All Characters Unique In All School 1639 Change Subscribe Button Subscribe Forward 619 Your Statement And Points Snowman Controls Whole Solar Equivalent To Sit Investigation Has Been Able To This Element Also Interest Subscribe To My Channel To Hai To Initially What Doing Sam Declaring All Assets and Akunth Points So I Will Scholarship Withdrawal Variable and Returns to Give Equal to the Length of the Longest Points 208 That Vijendra Tight Ratios Until They Are the End of the Thing E That Navdeep Singh Bhatti Benefits Will Have to OK You Find Different Elements Parinda Set and Not So Let's Testing for a Winning Will Significantly But Soldier in the Central Not So Let's Describe Center for the Set So Let's Not Remove Its Elements Point to the Chart Always Give Subscribe Example for Example Looking at This Place for Elements Which will give you a very unique for this apni voice on this image will not be directed towards opposing elements in the world will initially 6 maths how to check the current subscribe example will subscribe The Channel and subscribe the Channel 12023 is the length of the current Subscribe Tuesday handed over to * Check Gift handed over to * Check Gift handed over to * Check Gift to Start - And Plus One So This Great to Start - And Plus One So This Great to Start - And Plus One So This Great Dane Maths in Whatever Equals to Start - Dane Maths in Whatever Equals to Start - Dane Maths in Whatever Equals to Start - The Video then subscribe to the Page if you liked The Video Cost Effective on Tiger Set Already Found in These Pictures Beach Condition Software Writing And Condition And Without Test Positive For Venus And Saturn Which Were To Eager Character And What Position Divya Tourist Places From The Information And Vital And Mental Health And Winter Sid And Finally Bigg Boss Twitter Mix It Means Just A Little Bit And Vid Uh yesterday morning Justin use your army schemes time fog 221 how to learn this thing don't let me just refresh this page for taking longer than usual so let's run code end after 10 minutes according to * work out flat summit that end Developed as a passing thanks for information
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string `s`, find the length of the **longest** **substring** without repeating characters. **Example 1:** **Input:** s = "abcabcbb " **Output:** 3 **Explanation:** The answer is "abc ", with the length of 3. **Example 2:** **Input:** s = "bbbbb " **Output:** 1 **Explanation:** The answer is "b ", with the length of 1. **Example 3:** **Input:** s = "pwwkew " **Output:** 3 **Explanation:** The answer is "wke ", with the length of 3. Notice that the answer must be a substring, "pwke " is a subsequence and not a substring. **Constraints:** * `0 <= s.length <= 5 * 104` * `s` consists of English letters, digits, symbols and spaces.
null
Hash Table,String,Sliding Window
Medium
159,340,1034,1813,2209
32
That Hello friends, welcome in this video, question number 32 is the longest first parents, this defeat level question is in read and which category is this question, if you see, dip has been said in the read court, but parents, if we are talking about this, then from the track. It can be said that on a very real question let us understand what is the given string content director is either the opening racket or the closing black is perfect in testing and what is the extract find the length of long s well and wealth for parents the substring let us understand There is only opening and closing racket in the ring and to remove all of us, this is that what you have to return is the length which is complete parents, which is for in this case and if I put it in a way, then one There is four and 1 is two and this small one is engrossed in himself, but the maximum that is being made in petrol should be continued, there should be a break in between and the continuation is for 5-day, so for continuation is for 5-day, so for continuation is for 5-day, so for return, how will we use this tag? And if you want to do it in a simple way, then you will use two stocks, then which one will you take, you can also tax this and these future signals, I would like to tell you this problem, Rahul Singh IG suggested it to me, he said please suggest please. Solve list code is 3215 time is their comment show it then ok let's come to the question or give now let's come to the question and understand first the approach let's understand what problem can be set all this then if you apply it daily then you will apply lean approach. In this, will this be the case for the distance travelers or will it be an open obstacle? I said that if we make 24 then I would like to say that I will make two stocks, one is character stock and mine is 11 inches extra. You people will get to know from the name that this track will do both, so what? If my ice cream is, then we can take the string like this, if my spring is a and friend 12, this is the string. Okay, so in the character stock, we store the character village that if the first integer is zero, you will get an open bracket. If that open racket comes, then we will store it in the character step, okay, after that if we will put standard in the closing and index tag also, why will we put it because we are assuming that who knows, in future we may not get its partner, we may not get the closing, okay but hey. If we go ahead and get closing then clear this track and also clear this index track and in this case we got one on perfect like if we got one on one perfect then one on - we will do the perfect then one on - we will do the perfect then one on - we will do the last index where There was a problem Meena where we were not getting anything done, so in this case we are not able to see anything, even on computers, the complete leg is cut off, so we will have to go with a default minus one. There is a small trick - one will give you the small trick - one will give you the small trick - one will give you the index. This is what will have to be stored in the track and the one which is complete in this too, find the length on this index and then move ahead. August closing goes back, so never store it in character state because before that there was no back door opening. So we will not update the character step and will say our index track, brother, there was a problem here, so this problem is that our index got updated, so I added it to it, let me understand it, let's add a big example and understand it well. Let's take an example like this, we take the first index where nothing is being made, then a pair is being made, then we make another pair, after that, we do one here and make one leg, then the answer will be one. Longest is seeing my substring of size four which is the complete value from parent s and is waiting for 1 minute then my answer which will be talent is four to two I am getting the length I will keep updating so quickly attract you I will do a process and show you, if ever closing rapid comes, then there are two cases, then check that your partner is being found. If you are not getting it, first of all, when the closing racket came, I saw - become, then closing racket came, I saw - become, then closing racket came, I saw - become, then you know, you have to put the default in the index side. Now we They are starting zero index, ok closing date has come but he has no partner, in this case, that tractor is not mt6588, so this is the problem index, so update zero in it, do not update the check, move the phone track forward, now this If the open racket has come then put open bread in the state and update the index test as one because we are assuming that its clothing may not be knotted. Go ahead, font up, closing racket has come. Now if you want to calculate the total length then calculate the length. As soon as you go back to How To, delete that bed open racket from the text and also delete its index which we had stored unnecessarily. Now calculate the length on this two, then we will do two - and after that, do two - and after that, do two - and after that, how will we calculate the length of ours? If it happens then the last index track is intact because the problem here is also the last problem was here. You will index the last index and you will get this lunch. This is a small calculation, repeat it and you will get the answer and it is not so difficult either. There is a problem and the strategy was not right. Let's move ahead. If you don't understand, then it does n't matter. Moving towards index three. If you get an open bracket in index three, then start the induction like this in the index track. Who knows, if you don't find a footing in the future, then let's accept it. This is the problem index, the problem was then go ahead index for but as soon as we got the closing racket and we also saw that it has a pair already, the stock is not empty, there is no agreement, it has got open red in the test, so we empty it from the open racket. And we will delete this index and if it was completing at index for then we will do index for - we will then we will do index for - we will see where was the previous problem in index for. If the problem was at zero then we will do zero at index for - we will at zero then we will do zero at index for - we will at zero then we will do zero at index for - we will do this new length is found. Let's keep updating us in length. Okay, come on index five. Index pipe closing racket. Check in the hashtag. It is open rapid. If no one is found for its pair, do n't send a text message to the office. Put it in the index track that there is a problem at number five here. There is a problem index here, you have to find the closing racket, it did not have a leg, then go ahead, look at the index tax, the closing opening racket has come, the front bracket is the opening racket, but store it in the index tag, index, because who knows, its tree may not be found, it is okay further. Then go ahead index seven Got a closing wicket on index seven and we checked there was an open racket in the last on the peak of the step so it was completed we index removed all the sky decks and in these tax havens above we took out the length Seven - last index we took out the length Seven - last index we took out the length Seven - last index Where was the last problem index in the track? This is 350 500. So in this case return - Do it to get the This is 350 500. So in this case return - Do it to get the This is 350 500. So in this case return - Do it to get the size. So this size is fine. Find out its max. Mechanical would be coming either. Let's do the code. There is more in this question. Make two stock sets. Make a characteristic, okay, name my tab CT, okay, name it CT and it had to be made constructive, the second step was to create an index track, a friend extract, so this is of interior type, I have made it, I had told in the industry - Let's break it once, the default in the industry - Let's break it once, the default in the industry - Let's break it once, the default is that we will do it in the one which does not face even a single problem and there are such test cases in which you will get complete completeness, in such a case, minus one will be required to calculate the calendar, is there any problem in that simple logic? There were no indexes. Try the default things that I have set up for you to process. One by one. We will have to process. We will be two. What will we have to process. Spring will have to be processed. A string will have to be processed. Phone and 21 will be two types of spellings. Either our string is A, either in testing we have this character which is open bracket, it is correct, either in this trick, it is open racket, or in the string, the health of vals, our closing bracket here is 21, it is correct, it is open bracket. What I told you is that if it sits open then save it in that track. I told you to save it in the tag and put its contact so that in the future we will know. Who knows, there may be a problem in it, so let's keep it intact. Now who knows, if its foot is not found, okay? Hey my friend, in the first character step, fill the open racket and in the index track, fill its index. The big wish is to do it in the closing racket. There are two cases in the closing date. When the close back comes, we check whether the step is complete. In the first step, we are getting an open bread, we are not getting a house, so we are deleting this and we are also deleting this, the index of both, the last and we are calculating the lens, how are we calculating the land like for In this we have got the complete, you will see from the four, where was the last problem in the index track, so if you look in the case in the four, then the last problem was at zero, so whatever is there in the back of the index track, find out the length. Close Singh Rathore 2 How is the first case first check that the crossing racket is arrived now step right check that the last is the open racket if there is an open racket then our work is done and if there is any null pointer exception then once this also See if the step is empty stock somewhere then you are not checking it is ok first put the condition that steno MTS is fine then what to do now there was daily bracket now opening racket came so stock was added in closing rank exam Remove it from and also remove its index which we had added. It is simple, very simple code and calculate the length here, let's come down a bit and see for example, on this for index, we got it at complete, so here we are. If you are calculating for and explain, then how are you calculating the length? We are doing it, let's take a max because I write it, there is no need of confusion, a view to matic leaves, the number of times we will calculate its mechanical type, then calculate the length here. We used to calculate the length which is the current index which is for our four three in that we - let's do the last for our four three in that we - let's do the last for our four three in that we - let's do the last problem inducts so that is the last problem index our index dot pick was at the top of our index this is the last problem index so when you test this one of mine If you look at the case, the max value will be 2.2 look at the case, the max value will be 2.2 look at the case, the max value will be 2.2 because three times a big two is being formed and four are one, once this two is being formed then it will be the maximum highest and simple employment maths class has been used. Now, if by mistake he saw that there was no open racket in the stock, like here and in Heroines, there was no open racket before and he wanted to make a pair of it, then just updating the indexed. We were like, brother, add its index, there is a problem here, this problem is the index, it is breaking here, this is what we were doing, she is a very simple girl to me, I thought it was very simple, she knows the logic, the problem is not hard, it is very simple, no one else Hair is such a festival, I check it. Compiler has to be there, what has to be returned in the last, max has to be returned, comment here, give this tie, run it once and check that maths spoon, sorry, we have not made it. I will make Max, I am ok and now let's run it once and see if there is any compiler. Ok ok, I will submit the code and I will see the final whether it is getting submitted, it is not happening, I have to submit, let's see after submitting. Our code is accepted and if there is any such problem in it, if you are facing some problem in this video, then you can go back in the video and see once more, how to solve it is simple, it is not difficult, no. If you watch it again and again, you will understand. See you again with a new video, thank you very much.
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters `'('` and `')'`, return _the length of the longest valid (well-formed) parentheses_ _substring_. **Example 1:** **Input:** s = "(() " **Output:** 2 **Explanation:** The longest valid parentheses substring is "() ". **Example 2:** **Input:** s = ")()()) " **Output:** 4 **Explanation:** The longest valid parentheses substring is "()() ". **Example 3:** **Input:** s = " " **Output:** 0 **Constraints:** * `0 <= s.length <= 3 * 104` * `s[i]` is `'('`, or `')'`.
null
String,Dynamic Programming,Stack
Hard
20
1,020
Hello Hi Friends Welcome Back Today We Are Going To Solid Code Problem 1020 Number Of Enclaves Of Very Rudra Description Example Sub Problem Is Just Want To Mention That My Channel Dedicated To Helping People Were Preparing For Coding Interviews And Shower Interviews All My Channel More And More Then to Harold Examples Petraeus Coding Questions by Tech Company Like Amazon Apple Facebook Google Microsoft Yahoo and Manya Rate Companies and 200 Institute Different Varieties of Problems True Religious Program in Graph - Tricks - Tricks - Tricks Benefits Matrix Related Problems Ali Related Interview Questions So IF YOU Are you preparing for coding interviews and job interviews? This channel can definitely be able to help you. Please subscribe this Channel So let's you know the problem statement you are in. Remember N Canary Matric Screen 2003 Presents Itself and Only Dream Projects Land Sale Now Mohan Stocking From One Length into Another Attraction for Absolute Sale and Walking Off the Model of the Great Return Number of Land Sale in Grief for Which You Cannot Work in the Country of the World in Any Number of Marks for This Is the Statement Problem Statement and Have Two Examples Of Its Usage Examples For Over A Year And Will Understand What The You Know Problem Subscribe And Will Go With Solution To Reduce Color Hair Water Problems So For Example Which One Can Live With Those Directions To Here Right Side To Download Ujjain Right If there is 1 0 on the side then someone can go on the late start like pass turn on this landslide on in England hui can go for cold and witch can visit seen again hui chain of good witch can be field within self and from hair oil Can work of the great vision come outside of the great from fear basically similarly common lift a this inside like this noddy celluloid us fear from this and work of the country lights of the great souls have to figure out how many a sensor Dare Land Sell Sardar Treatment Inside This Of Our Greater Matrix Which They Can Not Work Of Right Means You Can Not Work Of The Founder Of The Great You To Front Part In This Case Is Rewarded Red Color Dream This What You Want You Can Stand Hui Can Always work of the great because her [ __ ] Always work of the great because her [ __ ] Always work of the great because her [ __ ] Buddha Badri all the sellout possibly connected to this element like this to the only this channel is connected to the boundaries and disturbance of already in the boundaries of which can always work of the great value of world in which Offer of freedom to format research the answer 34009 land sale senior right of which you can work of the great if you look at the second example so this is another example types of hui aa lift se this affair setting on this and right vision go and visit this Helps Fight Aa Download 350 Liters Grade Increment Se Left Side Patna Upaya Ko On Off The Direction Suicide Note Book Of The Great Because You Were The Different Directions Of Water Cycle Not Go To The Water And Is Not Go Back End Qualities And 109 Rates On those Ujjain work of the great that all 2030 site for which this disease one cell third ac second cell and decit third flight Swadesh internal three to four drops e can not work of the great last not get out of this greed that should have to return Free Adnan Sir Clear Pati Adarsh ​​Which They Can Not Work Sir Clear Pati Adarsh ​​Which They Can Not Work Sir Clear Pati Adarsh ​​Which They Can Not Work Of The Great And This But Its Called S And Clears Basic Telephone Number Enclave Located Year So That You Can See The Ardhaansh Hui Apps Plate And Download This Year For The Great You Know Yudh Can Work Of the great for innovative work so I will just returned 34 solve this problem video practice color sweater into to solve this problem will now go and check from Dadri Menu Subscribe Lut Vinod and all the boundary sales basically height Shuddhi sales every oil on the Bonder Still Enjoy Doing So Just Thoughts Last Column And Stroke And Subscribe Must Subscribe And Wherever Oo That Rajasthan Se Karna Solve Wearon In Every Sale Wool And Wear In Countering And Even Here Right When Will Start Giving Gifts For Example For Encounter One Here This Is A Boundary Cell Option This Is The First Prove Solve Vigilance And So They Started Doing Benefit Search Subscribe Must Start In All Four Directions At A Sweet Shop Download On Left Side Is Inclusive And Idli Sandwich Subscribe Convert 2015 Video Converter 2015 World will visit And converted into and share also loot download came also have planned stir well visit and I will convert dead sale in 201 120 Yadav and different so I will give in all four directions of call connected lands and with convert them into 07833 do you again came back And again will oo leg and how will come travels through the matrix and all the rooms in the corner and even tried to find out your double any one left right software pollution during owens left services k specific udairam one sleep because all governor who 120 against edifice Another is no one should withdraw zero number of enclave senior similarly if you take this another example when doing Dabuya traversing the matter of time to you will encounter one year in the first column read British boundary basically Montreal solve doing Great Friday website all four directions to Eat Ko Clear Hui Ko Share And How Can Hear You Know This Outside So We Won't Consider Were Visiting The Four Directions Who Will Check Out Disneyland Mail Narao 15000 Views All Water Says Water Sells So They Can't Continue Doing Benefits Underwater Slide Show Will Just Mode On During There Lineage Thought Honda Boundary In This Matrix Bodybuilding Will Do Again Will Regret Three Drivers Matrix President Will Travel Time Trick Scheduled Tribes Of Pandu Godare Once Left Side To During A Second Traversal Of The Matrix With Dis One Tea Spoon Yashwant 231 School Will Find If They Have Returned 3 Is The Answer Basically Position Is Number Of Enclave Site From Which We Can Not Do The Work Of The Great Writer Growth Rate And Other Water Cells In Between So Gai Is The Network Of The Great Saudi Problem Co Into Small Museum With This Should They Should Opt For The Would Explain In Detail Examples For The First Is Created Rise And Fall Of Fear And Roses Are Darling And Column Cigarette G Road After Landslide Facility The Columns And Number Of The Matrix Opposite Variable Called S Content Initial 8208 Disawar Force Traversal of Dreams Will Travels All Presence In The Greed And Wherever You Find Any Boundary Share It Is The End Having One For Example That Are This Is Boundary Salwar Reminder Set 125 Will Start Doing Difference That Sudhir Important Part Body The walk is the one that determined efforts of mountain means hijack 120 b 420 and iodine daily minus one and cheese equal to two columns miles 180 deaths will understand were this pressure research and will check the value of the boundaries of executive widening deficits conducted cell coordinate And the great clear to this is hair deficit in which you want to take good care or not valid self-pride care or not valid self-pride care or not valid self-pride 5000 or pimples or is greater than equal to roses and cigarettes daily want to columns which means that they are going outside of the boundaries for this Is not to valid side and this whole thing happened from visiting just listen DS Sundha these cases have to be town which not proceeded tribes 2009 2013 valid css for defense other wise who will visit dasharath se that and will make a disciple who ended With try going in all this for directions private students after the difficulties for directions and have mentioned this year will go in all this for directions and students after doing this you can see - and students after doing this you can see - and students after doing this you can see - gomez plus one day is job - one is jobless for this after All - one is jobless for this after All - one is jobless for this after All directions update this because they have already mentioned that for directional you can quickly see what is the difference will do is vansh don't like aa but just now a trick which color independent user can show you what ever kullu is vansh you for example start with itself that One Should Start With This Vansh Will Go On And Scheduled Tribe To Our Condition And Thoughts Connected To That One In Four Directions Right Leg This Is Gold Digger Sisters Basically Tight And Mixture Maximum Withdrawal Subsidy Scam 0 Vrat Ki Twit Convert 120 Sadhe Difficult To Invite Yaar Tu Yaar Controlling 10 Chapter Debit The Receiver Controversy Of That After Defeat Them Cool Even Go Through Of Scheduled Tribes In One Left Over The World To Man Content Will Return Contact Number Of This Is The Implementation Latest Examples For This Is The Temple Of But You should subscribe to the soldiers who can see three do yaar also getting three withdrawal getting correct answer so they can run with all the like share and also this is our second examples and have no fear suvasra number code no suit zero for the second example with You Can See You Were Getting Lions in the Second Example Listen Tight What We'll Do It's the Will You Just Convert 2008 to Convert 2021 0share 0tweet Connect with 300 Let's Convert 2021 Schedule Center on the Another Unit Taste Clear Shot Means of Curd and Ghee Paas Bani Sthal Ke Dushman Is The First Woman Rights Off Main Aa Hai Pyaaso This Point Is The First One Vihar Converting 30 1021 Body Were Converted Into One And Let's Salute This Ka Swad You Can See Know It Is Hair Oil Bigg Boss- 1 Sui Convert Dist 181 Converted Boss- 1 Sui Convert Dist 181 Converted Boss- 1 Sui Convert Dist 181 Converted Into One Election Olive Will Be Convert 220 Vikas Yaar Connected To This Boundary Date Of Birth Zero No And This Will Also Blessings All The Best You Can Avoid Sod And All The Once You Will Be Able To Work For Aadarsh ​​Reddy Always Been Converted 201 34 Aadarsh ​​Reddy Always Been Converted 201 34 Aadarsh ​​Reddy Always Been Converted 201 34 Na One Light On The Boundary Abts Connected To Dushman Hee So Lets Pray Courier Returning To Here Quadruple States Of Passing So In This Lap And Submit This Solution Is Dry And Solution Not Accepted By Liquid Fifty One Per Cent in the Performance Side and Nine Per Cent in the Memory Side Show This is the Way You Can Use Difficult Approach to Convert Like to and Account Number Friend Clips in the Given Matrix 34 Per Straightforward Explain You Work in Details with This Example Setting Show If You Have Already Sent Mother Playlist On My Channel Boat Lift Code And Do n't Sonu Subscribe Now To Front Side Examples With Java Code And Details And Subscribe Interview Questions By Amazon App Facebook Google Microsoft Company Important Questions Were Preparing For The Interview Or Interview Schedule Difficult To Others Job Interview Date of Birth Daily Point Question Solve Cheater Playlist As Well As You Like This Video And If You Find This Video Helpful Please subscribe The Channel and Like This Video Your Subscription to the Channel Is Really Important Has Been Authored Yadav Video Can Reach To More People Can Also Watch This Problem Solve Problems And You Know It Can Help Them In Their Job Interview Preparation Sutli subscribe The Channel and Share The Video With Your Friends Thank You
Number of Enclaves
longest-turbulent-subarray
You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell. A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`. Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_. **Example 1:** **Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\] **Output:** 3 **Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary. **Example 2:** **Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\] **Output:** 0 **Explanation:** All 1s are either on the boundary or can reach the boundary. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 500` * `grid[i][j]` is either `0` or `1`. For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd.
null
Array,Dynamic Programming,Sliding Window
Medium
53
88
what's up everybody i hope all of you are doing extremely well my name is akshat gupta and i'm a senior software engineer at rccm welcome to boss twitter academy's youtube channel so today we will be solving the lead code problem number 88 merge sorted array let's try to see how it looks like so the problem says that you are given with two integer arrays nums one and nums two sorted in non-decreasing order or we call that as non-decreasing order or we call that as non-decreasing order or we call that as ascending order two integers m comma n representing the number of elements in the array numbers one and num2 respectively the job is to merge nums one and nums two into a single sorted array okay so it says the final sorted array should not be returned by the function but instead it can be stored in the same array inside which is the nums one to accommodate this numbers one has extra length of m plus n where the first m elements should be uh denoted by the first elements which are present in the array number one and the remaining uh n elements are the extra space which are present in nums two so after merging them naturally we'll know that all the total number of elements will be m plus n so we have exactly n number of extra spaces in numbers two so if you look at the example given below it says that input number one equal to one two three zero and the size of this array is three which means the non-zero array is three which means the non-zero array is three which means the non-zero entities in the first number one array are three elements similarly nums two is equal to 256 and the size of that is equal to 3 so if we merge them together the final output is supposed to be a non-decreasing array in supposed to be a non-decreasing array in supposed to be a non-decreasing array in a sorted fashion so we all know that one two three two five six and club together will look something like one two three five and six so if you notice the exact number of elements are occupying the number of zeros which are in the first array hence the discussion which we have just seen in the question let's look at another example so your nums one equal to one m equal to one and nums two is an empty array since it is an empty array we do not have any preceding zeros in nums one so that means the final output is just going to be the entire the exact content which is in knoxville already if we look at example number three we have numbers one equal to zero that's just one zero and therefore m is equal to zero because we do not have any non-zero entity we do not have any non-zero entity we do not have any non-zero entity inside number one if only zeros we have only zeros inside it right coming to numbs 2 we have nums to equal to 1 for which n equal to 1 so naturally if you're clubbing them together the final answer will be what it is supposed to be just one element inside it right so let's try to understand how can we approach this particular problem so from the given input example let us take an example of 1 2 3 0 which is your nums 1 and 2 5 and 6 which is the nums 2 so here the value of m is equal to 3 and the value of n is equal to 3 and we know for the fact that we have exactly three number of extra zeros in nums one which are occupied or which will be occupied by the number of elements inside terms two how should we approach this right the basic thought process which comes into the mind is why don't we simply copy all these numbers into one array so one two three two five six we simply copied all the numbers from nums two into numbers one now we can simply call the sorting function on this input array sequence right naturally if we call the sorting function we know for the fact that the final answer will be getting is going to be one two 2 3 5 and 6 which is the exact output we are looking for absolutely right this approach will work just fine so if we try to analyze the time complexity of this particular approach right since we have m plus n elements at the end of merging state and we are calling the log sorry we are calling the sorting function on the m plus n elements so time complexity for that will be m plus n log m plus n right and the space complexity will be order of m plus n right so clearly this approach seems to be like a viable idea but we know for the fact that the constraints said that uh you know the number of elements could be uh lying between the range of 10 raised to 9 or 10 raised to 9 and the size of m into n can lie anywhere between 0 to 200. so naturally we can say the solution will pass right the solution will pass but is this the most optimized solution or not is the question can we come up with an algorithm then run that runs in linear time let's try to analyze that the example which was given to us said that the numbers were 1 2 3 0 and 2 5 and 6 the job was to merge them together how should we approach this let's try to pick the element from the back side of both the arrays right from back side of both the arrays and let's keep a pointer p at the last index of the nums one so now if i compare p1 with p2 i can clearly see that p2 is bigger than p1 so naturally i can copy number six on the last location which is p and decrement the value of p2 and decrement the value of p1 intermediate array will look something like this 1 2 3 0 at 6 and 2 5 and 6 with the pointers p2 p1 and p as shown in the diagram now again compare p2 with p1 clearly we can see that p2 is bigger so let us put p2 into the location of t to make the intermediate array as one two three zero five and six and the pointers p2 p and p1 are shown respectively again compare p2 with p1 so we clearly see this time p1 is bigger than p2 right so that means take the number on p1 and put that number into its right location so now the number that we get will be 1 2 3 5 6 with the indexes as p 1 p and p2 as shown in the diagram right so decrement the value of p1 obviously because we have put 3 into its correct location now again compare p2 with p1 on the comparison we can see that number two and number two are just the same right they're exactly the same numbers so that means we can put either of them into its correct location so let's say we'll put p2 onto the place of p the intermediate array will look like 1 2 3 5 and 6 and now p2 will become -1 p2 has gone out of the array which -1 p2 has gone out of the array which -1 p2 has gone out of the array which means we have exhausted all the possible numbers from nums 2 and we have put them into the correct location which is out there so do we need to sort the remaining array absolutely not right because we already know that the input sequence was in a sorted order already and since we have put all the numbers since we have exhausted all the numbers from nums two into nums one that means i do not want to sort the array once again so i can simply say by the end of this if p2 becomes negative then that means we have got the final input array as the answer so we can simply return the answer based on this index so let us try to understand the coding aspect of it now so as per the logic let's declare the variables as shown so i equal to m minus 1 j equal to n minus 1 and let's say we have a pointer k which is m plus n minus 1. so this is this kth index is actually pointing onto the nums 1 but on the last location if pointer is present with the first non-zero entity from the behind on nums non-zero entity from the behind on nums non-zero entity from the behind on nums one and j is pointing to the last entity of num2 so what do we need to start iterating on the values of i and j and check which one is actually bigger and based on that will be placing that entity into its correct location so we can say that while i is greater than equal to zero and j is greater than equal to zero so perform some operation inside it if nums 1 of i is lesser than num 2 of j that means the number in nums 2 is bigger so what do we are supposed to do we are simply supposed to take the number from nums 2 and put it into its correct location which is on the index k that means nums one of k minus should be equal to nums 2 of j minus correct else if the number is bigger in numbers one then that means take the number from nums one so nums one of k minus should be equal to nums one on i minus this time right naturally if we have exhausted all the possible elements from nums too then we are done we are not supposed to perform anything but if we exhaust all the possible numbers from nums one that means we have some numbers remaining in nums too so what are we supposed to do we're simply supposed to copy all those elements from nums2 and put them into the correct location based on the index k so let's do that we can say that while j is greater than equal to 0 simply put all the elements from nums 2 into its correct location so nums 2 of j minus that's it so let's run this code it works just fine let's go ahead and submit this code aha it gets submitted right so this is how we can sort two different arrays into one we can club two different sorted arrays into one in linear time complexity right i hope you enjoyed this video so stay connected like the video share it with your friends if you found it useful subscribe to the channel hit the bell icon and i'll see you in the next one until then take care bye you
Merge Sorted Array
merge-sorted-array
You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively. **Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**. The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`. **Example 1:** **Input:** nums1 = \[1,2,3,0,0,0\], m = 3, nums2 = \[2,5,6\], n = 3 **Output:** \[1,2,2,3,5,6\] **Explanation:** The arrays we are merging are \[1,2,3\] and \[2,5,6\]. The result of the merge is \[1,2,2,3,5,6\] with the underlined elements coming from nums1. **Example 2:** **Input:** nums1 = \[1\], m = 1, nums2 = \[\], n = 0 **Output:** \[1\] **Explanation:** The arrays we are merging are \[1\] and \[\]. The result of the merge is \[1\]. **Example 3:** **Input:** nums1 = \[0\], m = 0, nums2 = \[1\], n = 1 **Output:** \[1\] **Explanation:** The arrays we are merging are \[\] and \[1\]. The result of the merge is \[1\]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. **Constraints:** * `nums1.length == m + n` * `nums2.length == n` * `0 <= m, n <= 200` * `1 <= m + n <= 200` * `-109 <= nums1[i], nums2[j] <= 109` **Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time?
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
Array,Two Pointers,Sorting
Easy
21,1019,1028
380
um hello so today we are going to do this problem which is part of lead code um November daily challenge insert the insert delete um get random in all of one so what the problem says is we have this classroom domains it set um and we initialize it and we want to insert a value um into the set if the value doesn't already is not already in it and we want to return true if it was not present and we were able to insert it otherwise we want to return false the signal operation is remove a value where we want to remove a value of if it's present um so when I return true if the item was present and false otherwise so you can think of it as basically returning true if the operation was successful yeah and we have get random where we want to return a random element from the current list of elements um and um basically it's guaranteed that at least there is one element in the list when get random is called so we don't need to check for empty uh and we need to have the same probability of each element to be returned right um and then here they say that we have to have all these functions be on average of one time right um yeah I don't think we need to go into the examples it's pretty straightforward um the calls are 2 to the power of five so yeah of one would be useful um so I first let's just solve it in a simple way that is not o of one maybe over and for at least maybe it'll move and then from there we can solve it you know one time okay so the first thing we need to do is pretty simple or you can just add them to the list insert them at the end of the list and then remove just remove the value in Python from a list that would be an oven operation right um so we would have a list of values um and then here we will want to insert it at the end okay and then here we want to remove some of that sorry there is only um so here we want to remove the value we will later do the returning true or false right and then here we want to get the random how do we do that well we can just use Python has random package that has a random integer right between two values so what do we want to get a random index from the list so from 0 to the length of um self-doubt values but we want only um self-doubt values but we want only um self-doubt values but we want only valid indices so minus one this one is inclusive because around the end the values the ratio takes is inclusive so we get the index and then we just return that value okay now let's do what the problem asks us to do in terms of returning true so we want to return true if the item was not present and we were able to assert it so we want to check if the item is not present so not then we want to insert it and then we want to return true okay um but otherwise if it wasn't present which is certain false and here we want to remove it only if it's present and we want to return true if it's present so if Val is in solve that values if you want to return true um and we're going to return false uh by the way this is also like this check here contains is of n so we'll need to optimize that here okay so all of these the two operations here over and this is over one so we want to move this to be of one instead of open so let's um let's first run it make sure it passes and then we can optimize here um yes oh okay so yeah sorry it's values that remove and submit okay so that passes now let's optimize um so what we can do is actually just have a dictionary for positions this is basically so we can both find if it exists even the values in the array it would have a position in the positions map um then the other thing is also um for the to optimize this remove here how will we optimize this remove so what we can do actually is pretty simple so we have a list of elements let's say we already added maybe five seven 2 doesn't have to be ordered right and then we have the positions for each so we have our positions array that has like one at zero um five at one seven at two and then two at three okay so what we'll do let's say we get removed for maybe remove four five okay so how do we how can we do this in an optimal way so in the what operations do we have that are of one so for a list in Python popping the last element is of one right so what we can do is pop this two put it in five place and that would be it and we will need to change this to be um to be 2.21 and we will remove this right to be 2.21 and we will remove this right to be 2.21 and we will remove this right so that would be over an operations except the delete for dictionary will need to find a clever way to not make it opened okay so how would we do that um so what first the part that we know is that we will just take we'll get the index um for we'll get the index for the last position right so first we will just get the index for solved out positions for the uh the value that we are going to remove so we get the index for five okay so that would be in this case for five it's one and we'll put the two we'll save it in that position right because we'll remove two so this would be equal to self that values at position either the last position right in Python we can do -1 like this um and once we do this our list will be like this it would have two here and then we can just pop this two because we put it here so solved our values and this is over an operation okay um but now we need to update the positions right so what we can do is just Mark that now the we just need to change because now when we do this here now we have like this we just need to change this Index this map to be here 2 pointing to one and delete this or mark it as deleted or something so for the first portion which is setting for to the index to be one we will just say um for solve that values at position I which is what the 2 is at now and we want to mark it as this position and that position is basically I right um okay so once we do that um we can just delete solved up positions for this fire this two here the last one right um or we can do it differently right so we just say two to one actually so we set two to one here and then delete this one that would be easier and so we'll delete for Val which is the five right so it deletes five pointing to one okay um except this deletion here um maybe or when um and I would like to avoid it um even if it's not open it's just not great so we just want to avoid it here so how can we avoid it well it should be pretty simple the indexes of the arrays are positive right so we can just put minus five here 0.5 to -1 here 0.5 to -1 here 0.5 to -1 right and also like in other languages it doesn't even exist so instead of doing this we want to just fill it with minus one so what we want to do is do here minus one okay um and in this case we can just check if Val is far removed we can just check if Val isn't removed is it um is it is not in the positions or its value is equal to one in both cases that means it's removed right um so that's exactly what we'll do here so value not in here we now check positions so that it's of one operations because checking an element is in the map is an of one operation and we want to check that the positions for Val is different than -1 right um okay equal to -1 okay equal to -1 okay equal to -1 so this is r okay so Val not insult that position or um so the value not in positions or it was removed before so it's equal to minus one so that's where we want to remove it and here the value is in this and it needs to not be removed so we need it to be different than -1 be different than -1 be different than -1 okay um and now here we just need to update it to make sure we add the position for Val because we added it to the end of the list it's just the length of solve that values minus 1. okay and here we want to remove this we want to get rid of this because it's oven and we'll do exactly what we said here just clean it up a little bit so it would be like this um so we get the index first of the value we replace it by the last one and we pop the last one because pop is of one and then we insert in position the new index for the last value okay and then here we just set to -1 to okay and then here we just set to -1 to okay and then here we just set to -1 to mark it as removed and that should be it there is only one little um thing that we need to do here I'll just first mark this like this but here we just need to make sure that I for this to work I need to be smaller than solve for that then the length of the list after we remove the last element just in case there was one element so the length this is just for index do not get index out of bounds okay and we can now remove this and now it's over one operations because this is of one this pop is from the end is of one this assignment is of one and here also everything is over one and here it was already off one right so all of the operations are of one now and we can submit in this passes um now one simple modification we can make that it works only in Python actually because python allows us to have a default value for um for absent values from a map with the chess Lambda so we can default to -1 that way the only check we'll need to -1 that way the only check we'll need to -1 that way the only check we'll need to do is that the value is equal to -1 to do is that the value is equal to -1 to do is that the value is equal to -1 this means that it's not present um and same thing here we don't need to do two checks and we can submit okay so that works now um yeah so pretty much that of one for every operation and for the entire thing we are using two extra lists here so it would be of N and being the number of inserts um yeah so yeah that's pretty much it for this problem please like And subscribe and see you on the next one bye
Insert Delete GetRandom O(1)
insert-delete-getrandom-o1
Implement the `RandomizedSet` class: * `RandomizedSet()` Initializes the `RandomizedSet` object. * `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise. * `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise. * `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned. You must implement the functions of the class such that each function works in **average** `O(1)` time complexity. **Example 1:** **Input** \[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\] \[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\] **Output** \[null, true, false, true, 2, true, false, 2\] **Explanation** RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. **Constraints:** * `-231 <= val <= 231 - 1` * At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`. * There will be **at least one** element in the data structure when `getRandom` is called.
null
Array,Hash Table,Math,Design,Randomized
Medium
381
139
welcome to this video now we're going to solve a coding interview question called Break you're given a non-emptive string s and you're given a non-emptive string s and you're given a non-emptive string s and a dictionary word date containing a list of non-empty words of non-empty words of non-empty words determine if s can be segmented into a space separated sequence of one or more dictionary words this is the problem statement for example if you are given s equals to lay code and or predict equals to this list of words we have lead and code word in this word dictionary now we can generate this string from this word dictionary we have here the word lit and we have the word code so in this case we have to return true if we are given this string Apple pen apple and word dict equals to Apple and pin from this old dictionary we can generate this string Apple then pin then Apple we can have repetition of word we see apple repeated twice in this string so in the sketch we have to return true now how we can solve this problem for second understanding let's assume s equals to lay code and word dict equals to lit and could first we're going to construct a hash set and this is our hash set this hash set contains two word lit and code then we're going to construct a dynamic programming table and this is our dynamic programming table and the length of this table is the length of the string plus one the length of the string liquid is eight so eight plus one is nine the length of this dynamic programming table is 9. for the first index we inserted true initially why we have inserted true to the first index we'll talk about that in this video we have this string liquid and we have this set now first we're gonna check this first letter and this is L okay does ILL exist to our set no l is not exist L does not exist in our set so we'll not change the value at index 1. then for index 2 we're going to get this word AOE does early exist in our set no le doesn't exist then we're going to get the letter e does e exist in our hash set no e does not exist in our hash set so will not change the value at index 2 then we have index 3. for index 3 we have this word l e okay l e doesn't exist then e doesn't exist in our headset then e also does not exist so will not change the value for index 3 then for index 4 we will have this word lit does lit exist in our set yes it is then we're gonna check whatever word we have on the left of the word lit we have nothing right and we have here true for nothing because lit is the word and on the left we have nothing so this true end it exists in our set it's also written true so true and true evaluate it's true then we're gonna change the value here to true okay then we're gonna check EET we see EET does not exist in our hash set then et does not exist then t also not exists in our hash set then we have index 5 for index 5 we have this word ill WTC we see this is not existing or hashtable then e Etc also eetc is not exist in our hash table then Etc is not exist then tctc also not exist then just see we see does all word does not exist in the hash set so it will not change the value at index 5 then for index 6 we have this word lwtco does not exist EET Co does not exist etco does not exist in our hash set TCO and O all the word does not exist in our hash set so will not change the value for index 6. okay then for 7 we have this word LWT co-d and this word does not exist this co-d and this word does not exist this co-d and this word does not exist this word also not exist this or not exist this word then this word OD and then the letter single letter D all of them does not exist in our hash set okay so we'll not change the value at index 7. then for index 8 we have this complete word okay we see lit code doesn't exist in the hash set e t c o d e does not exist e t c o d does not exist t c o d e does not exist c o d e does exist right c o d we have in the hash set this exists so it will return true then whatever word we have left on the code we have lit so let's get the value for T at index 4 right at index 4 we have 2 so true and true is true so it will be replaced with true so we will stop here because we don't need to check for the rest when we have found a word that match our condition and this is how we can solve this problem I know this solution will exaggerated don't worry let me show you how you can solve this problem using the health of sudar code first we're going to declare a function word break that takes a string enter dictionary list let's suppose that s equals to let code and word dict equals to lead and code here old dict and decrease are the same okay then we're going to construct a dynamic programming table the length of the string plus one this is your dynamic programming table of length 9 then we're going to construct a set from the dictionary list this is our hash set okay then we're going to insert at First Position true okay why is that where you have found a complete word suppose that we found this word lit when we found a complete word in the set then what we will do we will find the left portion of it word in the sketch in the left portion of this order is nothing right for that we're inserting here true when we go through the is iterations of our Loof then you will see how it's work okay don't worry for now we're gonna run a lift for iframe want to length of the string minus 1. we're starting from one because we already inserted two at the first position then we're going to run another loop this is nested Loop for J from 0 to I minus 1 and this will generate word of length from 0 to I minus 1. then we're gonna check if diffi is a and this division means if we found the left word then return to if we do not found the left word in our set then return false or if we found empty word on the left then return true and if the current word is exist in our set then set true to the current index and then break at the end we'll have our answer right here and we'll return that okay DP length s minus 1. sorry it should be just DP length of the given string not minus one all right now let's see how it actually works for first iteration of this for loop I equals to 1 then we'll have Z equals to only zero so we generated the word of length one okay and this is l does not exist in our hash set so we'll insert here faults then for next iteration of this love I equals to 2 and J equals to 0 for J equals to 0 we're going to generate a string of length I minus Z and that is 2 and that is here AOE l e does not exist in our hash set also e does not exist in our hash set so let's insert here false we don't have to insert your faults because by default we have the value for all the field faults and that's why we're not inserting false here we can do it by using else statement we don't need the right then for next iteration I equals to 3 we have the word l e doesn't exist in our hash set e doesn't exist e also doesn't exist so here we will have the value faults then for next iteration I equals to 4 then we found a word lit we see that Lit exists in our hash set then let's check whatever value we have for the left word we see the left word is nothing in this cage for that we're going to return whatever value we have at the index 0. okay then we have inserted here true and we don't need to check for is equals to 1 2 and 3 because we already found a word that exists in our hash set and the left word is empty or we have found in our headset already then for next iteration of this Loop we have I equals to 5 we have generated all possible words we see no of them exist in our hash set then we have I equals to 6 here also we see no of them exists in our hash set then for next iteration of this Loop we have generated all possible words here also we see no word exists in our Hatchet then for the last iteration I we see when we have is equals to 4 we found a word code in our headset now let's check the left word if that exists in our hash set the left word we have for code is lit and we see that Lit exists in our hash set so it will return true and we have in our headset so this 2 will return true at the end we will insert here True by default we have all the value faults this is how we can solve this problem if you aren't understanding this problem take a look at for the is iteration we have break it down the is iteration for the two Loops so you can understood easily you will have a you will have easy time understanding this problem if you take a look at for the all iterations what's going on in the code we have right here everything we break it down to make you understand this problem clearly at the end this function will return this value true and this is how we can solve this problem this solution will text bigger of N squared time complexity where n is the length of the given string and it will text bigger of in space complexity to construct our dynamic programming table hope you have understood this problem if you have any question if you have any suggestions let us know thanks for watching this video I will see you in the next video
Word Break
word-break
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\] **Output:** true **Explanation:** Return true because "leetcode " can be segmented as "leet code ". **Example 2:** **Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\] **Output:** true **Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ". Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** false **Constraints:** * `1 <= s.length <= 300` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 20` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**.
null
Hash Table,String,Dynamic Programming,Trie,Memoization
Medium
140
748
hey guys this is how's everything going this video I'm going to take a look at 7:48 Julius completing world word is 7:48 Julius completing world word is 7:48 Julius completing world word is easy one why don't why there are C 600 dislikes by the minimun and the word from a dictionary where has all the letters from the string license plate such a wordy set to complete the given string license plate here for letter e we ignore case for example P and the license place two matches PE on the word this guarantee that a sir exists there multiple one return the route return the one that occurs first license plate might have the same letters or curry multiple times sample given license plate a PP the word pair does not complete ah I see Owen detector could be useful for one of us for the word super supper thus yeah because have PP right isolate like this one is 3 PS T words step steps stripe estoppel the smallest length word that contains the word as P and an s and t SP s D is SPE s T steps yeah license place 1 is 3 4 6 Tony s alright so all the words has s and these are this shortest so the first one is return well I suspect what a bit string within range 1 to 7 mm hmm contain digits space letters huh words have a length of huh every words contained or cases well so I think the naive solution will be just compare this 4 to each word and to see if that it has enough were tacked captors enough letters right so we do through the word a12 the linear time and we will look through each letters of the word in a time and to compare against the license plate of course we need to pre-process plate of course we need to pre-process plate of course we need to pre-process this license plate to get the count of each to the count of each letters right yeah so that's okay that's how idea free council license plate for each letter and then loop through the words and check if sad is fight and yeah so we look through all the words and update the word okay keep track the shortest yeah so this is the result cost no war and then my history count i since count if a-to-z just let this ladder license meet you get to the okay yeah and yeah I will create a function call okay I'll just lead through word of words if word satisfied word and the word men is motor and if result is more only we only update personal in this case turn result so let's create the satisfy forward and I think we will just yeah do the same I'll copy this should be not just use on the night myself against the accounts of the word let's check against for let letter this is a word let later count of license plate scam if word and yeah letter it doesn't have it we get it z0 it is less than we need stay with folks turn trip i think yeah that's it hope it works yeah it's working the time so the word we have the dependent let's say there are n words okay up milk a so we will include license plate suppose it's average the K this will cost us K and this satisfy will cost us yeah okay and for each word it whoa a ten right and okay yeah so time complexity would be in case today's map okay this is okay but it will be recycled so it's okay cool that's it hope it helps see you next time bye
Shortest Completing Word
largest-number-at-least-twice-of-others
Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`. A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more. For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`. Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`. **Example 1:** **Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\] **Output:** "steps " **Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'. "step " contains 't' and 'p', but only contains 1 's'. "steps " contains 't', 'p', and both 's' characters. "stripe " is missing an 's'. "stepple " is missing an 's'. Since "steps " is the only word containing all the letters, that is the answer. **Example 2:** **Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\] **Output:** "pest " **Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3. **Constraints:** * `1 <= licensePlate.length <= 7` * `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`. * `1 <= words.length <= 1000` * `1 <= words[i].length <= 15` * `words[i]` consists of lower case English letters.
Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`. Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`. Otherwise, we should return `maxIndex`.
Array,Sorting
Easy
2274,2327
20
let's solve the code 20 where we essentially want to make sure that any parentheses or brackets we open are correctly closed in order although there could be some nesting or multiple openings before a close so to solve this we'll use a stack to keep track of the openings we've seen so far we'll also have a dictionary of the closings to their corresponding openings from there let's iterate through this string just once if we see an opening then we'll append it to our stack now otherwise if we see a closing what if I see a closing and my stack is empty well then there wasn't a correct opening so I can go ahead and return false also what if what I was expecting to see for a uh opening is not what I've most recently put into my stack then I can also return false because I've got a mismatch otherwise I do have a correct match and so I can go ahead and pop the last opening I saw cuz it was closed off at that point my stack will either be empty or it won't and there's my answer
Valid Parentheses
valid-parentheses
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. 3. Every close bracket has a corresponding open bracket of the same type. **Example 1:** **Input:** s = "() " **Output:** true **Example 2:** **Input:** s = "()\[\]{} " **Output:** true **Example 3:** **Input:** s = "(\] " **Output:** false **Constraints:** * `1 <= s.length <= 104` * `s` consists of parentheses only `'()[]{}'`.
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
String,Stack
Easy
22,32,301,1045,2221
79
today we're going to be going over the Java solution for lead code 79 word search given an M by n grid of characters bored and a string word return true if word exists into grid the word can be constructed from letters of sequentially adjacent cells where adjacent cells are horizontally or vertically neighboring the same letter May cell may not be used more than once so here this is like our classic example of word search where we can basically have to find the word in a grid of characters but this time it's a bit different where normally in Word Search you can only make horizontal vertical or diagonal lines this one as long as the cells are connected you can basically consider them valid so by connected I mean by up down left right instead of diagonals so here we're going to be given a board of characters so that's by this input right here and that's what it looks like and then a word a Target word we have to find so a b bcced so we can see that we have a b c e d we found it and we can return true for this one right here we're asked to find the word c and so we see that okay s-e-e we found c and so we see that okay s-e-e we found c and so we see that okay s-e-e we found it and for here we're asked to find a b c b and this one returns false since it doesn't appear in this grid so we can see that if we have a right here we have a b c and no B's other than this one and remember we can't use the same cell again so we can't use the same b or else this would have been valid so that's why a b c and if we look at these two none of these are B's so we couldn't find it there and then another a right here there's no B's connecting it and so this one is also not valid so to code this up you could imagine we're going to use some sort of search algorithm you can use depth first search or breadth first search for this one I'm going to use depth first search so before we begin um the actual logic of this we're gonna have to go through all the characters in The Grid to make sure that we have looked through all the valid cells so we can make a double for Loop so four and I and less than zero eyes less than four dotted line so these are all the rows and now we're gonna go through each of the columns there we go so now what is it that we're actually looking for well if we think about this logically if we were to ask to find this ourselves so we would probably look for the first letter of the word and then try to see if any of the other words connecting it are also part of that word so for example we would scan through this whole thing trying to look for any A's once we found them let's say we were looking from the bottom to the top once we found an a we would look to all its directions and see if we could find the next letter which would be B in this case we can't then we look through again and we found this a then we look to the side of it we see that there is a b and we also find there's a third letter C and the fourth letter C and the fifth e and then the sixth D and now that we've completed the word we can say that it does exist in this grid so what we're looking for is if Board of i j is equal to word dot chart at zero so the first word or the first letter of the word then we can um execute our search algorithm so for example so our depth for search method um and what we're going to do is that if and this is actually going to be a Boolean so if this returns true then we know that we found it so the method is going to return true or false depending on did we find the whole word or did we not and if it does return true then we know that we found it and if we can go through this whole grid without ever returning true or ever finding it that means no we haven't found it so we could return false so what will this method actually take in well we're going to need to coordinate so into I and J um we're also going to need the board which uh board and we're also gonna need the word action the actual word itself now also we're gonna need to know which letter we are looking for in whenever we execute this message and this is going to recursive call on itself we're gonna need to know which letter we're looking for so we already found the first letter and so if we were to call this again we would presumably look for the next letter and so letter would be one this time and then we would look for B which is the second letter of the word so how would we actually know that this should return true well if letter is equal to word dot length so we've basically went through the entirety of the word and um we've found all of the letters that are associated with it and we were able to finish the whole word itself so we know we found it and we can return true so let's just put those stuff in here so I J board word letter and then we can do our boundary checks so if I is less than zero or J is less than zero or I squared I'm equal to work on length or J is greater than or equal to board of I dot length or a board of I and J is not equal 2 = 2 = 2 = so this is the case where it's not equal to the letter we are looking for then we can return false now once we've done that all we need to do is that if it doesn't trigger this if same and then we know we're in a valid cell so we can recursively call on the other four directions with the next letter so if we call on that we don't need an if statement for it since it's going to return true or false so DFS of i j board word and letter plus one so this is the next letter let's copy this and then do it for the four directions so I plus one I minus one J plus one J minus one so all we need is for any of these to return true since if any of them do then that means this was triggered and we know that the word was found so if that's the case we can return true for this method as well um else we know we're going to return false so we'll just say return false now if we run this we'll see that there was an error um oh all right word Dodge where was that word and letter I didn't make it oh sorry I meant to put in zero since we are looking for the first letter of the word so we can see here that we passed case one and two but case three we don't and the reason for that is like I said as we were going through the example we can't use the same cell again so what this method basically did was that it saw the A and then it saw the B then it saw the C and then the C called the method and all um the directions which are up which are I mean down right and left and I saw that wait a minute there's a b right here so then I went here and it realized we finished the word and it returned true but we can't use the same letter again or same cell again and so we have to basically restrict it from using this so we can do that by making um a separate uh grid that we can call visited and basically this is going to tell us if we have visited that cell if we have then we don't consider it's an invalid cell if we haven't then we know that we can consider it assuming all the other parameters in our boundary checks are valid so visited is going to equal new Boolean board length board God likes so now since this is global this method can access it as well and we got to add another boundary check that being that visited of I and J so if visited is true then that means we know that we can't consider it a valid cell since we've already visited it so we can also return false and then after that um if this if statement isn't triggered then we know it's a bad cell we haven't visited it but that means we have to make it so that we have visited it so we have to turn that into true then this if statement is going to run it's going to look for all the four directions and if we find the word then great it's going to return true but if we don't then we gotta make sure to turn all of these visited back to false so whenever we go through the next iteration when we find the first letter of the word again in a separate cell that we don't confuse it with the previous iteration where we said that no we have already visited it when we in fact just had started it and we actually haven't visited it so we can say else visited like I and J is equal to false so let's run it this should work hopefully no compiling errors and great now let's submit it all right great so that was leak got79 word search
Word Search
word-search
Given an `m x n` grid of characters `board` and a string `word`, return `true` _if_ `word` _exists in the grid_. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. **Example 1:** **Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCCED " **Output:** true **Example 2:** **Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "SEE " **Output:** true **Example 3:** **Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCB " **Output:** false **Constraints:** * `m == board.length` * `n = board[i].length` * `1 <= m, n <= 6` * `1 <= word.length <= 15` * `board` and `word` consists of only lowercase and uppercase English letters. **Follow up:** Could you use search pruning to make your solution faster with a larger `board`?
null
Array,Backtracking,Matrix
Medium
212
1,169
all right let's talk about invalid transception so intersection is possible in value if the marxist one thousands or is occurred within 16 minutes of another transaction with the same name in different cities so we're given a restrained transaction which transaction i consist of comma separated value represent the name time amount in cities transaction so written the list of transactions they are possibly invalid you may return the answer in any order so this is the transaction one this is transaction two so i just have to parse the transaction into transaction class this is more readable and this is a name this is the time this is a month this is a city so i will have to convert all this to transaction class and i will add into the hashmap the key is the name and the value is the transaction the whole things and later on i would just have to try verse um the transaction uh the hashmap with the send name transaction right uh with the transaction conflict if they are the same name in different city within the system mini right for another transaction so uh let's just start holding the list string i'm going to say i'm sorry go to new release i'm going to return answer patch map this is a string this is a trans list of transactions so i need to traverse the shin array and then i'll just pass the every string to the translation class so string c transaction so sensation translation trend would become new transaction t and i would just add uh i would just add put transfer name and then the list of transactions right but in the beginning we don't have any stuff right so this is better said put if absent and you put a trans name and newer religion right then there are later i need to put this current transaction into the map so map get fans and then this is add but this is becoming a list so i add a transaction to the current key right so i put the trans name the name for the key and if i if this doesn't in the map i'll just create it and then and if there's if there is a key uh in a map already then i don't need to worry about it right so put it after if there are two same name right analysis and later on after the traversal i would just have to do it again so what do i have to do it again this is because i need to check is if not in value or not so string t equal to transaction and now we're going to say transaction key transaction trend become new transaction fee so i'm going to say if invalid right is it invalid and then plan with the send and then right try and come in if this is invalid i will just answer that uh and then what do i need to add i need to edit here right this is list of string so i knew i need to know how do i actually uh rather especially function right so it's valuable to return a boolean the popular boolean and then i need a transaction p and also the list of transaction i'm gonna call this so if the amount if the cheetah amount is greater than thousands becomes both right if the amount thousand dollars return first right here mine is written force so i pass in the trans transaction you can say trends over here but i don't want to type trends i want type p so this is good and also i need to traverse the this with within the same name and in different city and the transaction is within the 16 minutes so for transactions hell in list so how do we actually do this so if different city right if these are city equal to elder city but they should be not equal right they are in different cities and the c and you cannot have 16 minute transaction which is time right so math absolute net the absolute p prime minus delta time is uh within which is less than equal right let's equal this pixel 60 and if this is happening written folks and obviously returned to and this is a little bit uh hard to understand but you can get it for sure so let me check do i have any problem so there's a reason why i use meth the absolute this is because um how do you actually know the time is actually smaller than the second transaction maybe you could i mean maybe they miss up already so absolutely it's much better so just making sure that time is within the 16 minutes so they just run it and hopefully i don't have any typo and i do have title this will become split three this start oh sorry this last 3d and let's just run it in and it's valid map and hopefully this will be the last one and yes so let's talk about timing space complexity for the time this is all the fan for loop put is out of one get is all of one and this one is all fun for the for loop and i need to pass it i need to come into its valley function and this is actually all of n for the worst case so the total will be all of n squared right so the time for the worst case is all of n squares and in space complexity this is the list of string and this attachment and they do i have to add every single transaction to the variable so the transaction for the space is actually all open and if you feel any questions just uh leave a comment below and then i'll just like subscribe like the video if you want and i will see you next time bye
Invalid Transactions
largest-values-from-labels
A transaction is possibly invalid if: * the amount exceeds `$1000`, or; * if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**. You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction. Return a list of `transactions` that are possibly invalid. You may return the answer in **any order**. **Example 1:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Output:** \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Explanation:** The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too. **Example 2:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,1200,mtv "\] **Output:** \[ "alice,50,1200,mtv "\] **Example 3:** **Input:** transactions = \[ "alice,20,800,mtv ", "bob,50,1200,mtv "\] **Output:** \[ "bob,50,1200,mtv "\] **Constraints:** * `transactions.length <= 1000` * Each `transactions[i]` takes the form `"{name},{time},{amount},{city} "` * Each `{name}` and `{city}` consist of lowercase English letters, and have lengths between `1` and `10`. * Each `{time}` consist of digits, and represent an integer between `0` and `1000`. * Each `{amount}` consist of digits, and represent an integer between `0` and `2000`.
Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table.
Array,Hash Table,Greedy,Sorting,Counting
Medium
null
462
hello everyone welcome to our channel code with sunny and today i will be discussing the problem called minimum moves to equal array elements and it is the second one and index number is 462 and the problem is of one of the medium type problems of the later okay so this is the second problem of the series of problems called minimum moves to equal array elements so i will recommend to do the very first problem and then come back to this problem so that you can have a better idea about the series of these type of problems okay so given an integer array nums of size n and we have to return the minimum number of moves required to make all array elements equal and how we are going to do that okay so for now let's first read out the problem read out the constraints and it is going to be like very much important for everyone to understand the problem statement very clearly then proceed further to understand the approach towards the solution and then finally code it up as fast as possible and the code should be nice okay so in one move we can increment or decrement an element of the array by one okay and there here are some set of examples and the answers i'm also going to explain how the answer is coming about and what should be our approach in the best possible scenario for now let's look at the constraints and it's going to be like mum's length and can go at most 10 power 5 and every number of the ad is going to lie within this range okay so let's move further to understand this problem with the help of examples and they will together build up the best solution of this problem okay so let's move further okay so suppose let us take an example of the other like suppose we have the array like 1 10 and 2 and 9. suppose this is the elements of this array and we need to find what is the minimum cost to make all the elements of this array equal note that in one operation we can increase any of the elements of the array by one and we can also decrease any of the elements of their by one in a costing a single operation okay now to make all the elements of this array equal we can choose any random value that is let's say i am going to make the elements of the array all equal to nine let's say okay so we want to convert this one to this nine it will cost me eight operations and that is incrementing every time one by one and it goes on up to this line and we can convert this 10 to this nine by decrementing one time and it will cost me a single one operation and similarly converting 2 to this 9 will cost me 7 operations and 7 9 to 9 will always cost me 0 operation it is already equal so what is the total number of operations that we have got it is coming out to be 16 8 7 and 1 16 it means that for converting every number to this the number equal to 9 will give me the cost as 16 that is it will require cost as 16. so can this be the minimum value or we can get some more minimum values or what is the optimal value being chosen so that we can converge every element of this array to that optimal value this needs to be like choosing that value is going to be like very much important okay now let us understand how we can choose that value let's say x where x is the value where every value of the array is going to converge to this x note that i am talking about the converge convergence that is convergence means let's say x is let's say uh something random value is 99 and we have some elements of the array like 1 2 3 4 20 30 000 10 000 and so on we will try to make all the elements being equal to this x and to make it equal to x the cost required will be absolute value of the number let's say number is y minus x this will be the cost to make some element of this add equal to this x and i am trying to convert all the elements to this x now the question lies is how to choose a suitable x let us try to focus over that okay so let me first erase all these stuffs okay so almost done this is also done okay now we will try to focus on how to find this optimal x okay now one thing one doubt that arises on every like uh quoted mind that while solving this problem should be like uh mean okay i'm going to write over that clearly it's going to be like a mean of the entire array or median of this entire array that is it is optimal that our value x should be either of this mean or should be either of this median but which is going to give us a correct answer note that let's say we have this array elements and let us find out the mean of this array mean of this side is coming out to be 11 and then 11 it will 22 divided by 4 it will come out to be around 5.4 it will come out to be around 5.4 it will come out to be around 5.4 something so this is going to be like a decimal value will try to convert either to the 5 or either to the 6 like everyone try to do that and because if we have some average of this array elements and we will try to make all the elements of this array equal to that average uh my answer can give us a correct answer or that is my answer could be correct could be not correct but if we choose the median then it will give us the correct answer and how it will give us the correct answer let us try to understand that with the help of examples because i think uh having the proof of some mathematical expression to get to be understood very well it is better or it is recommended to understand that proof with the help of examples directly to have a good grip over that okay so let us take an example like i have the adder elements like let's call it as so one okay i'm writing over here one and that is three ones over here and let's call it as another one and let us i have a very large value called as thousand okay so this is the array element i have taken over here that is the four one and then thousand so if we try to converge all the elements of this array to the mean and what is the mean coming out let's call it as mean as x and the values sum of this coming out to be hundred thousand and four divided by the five it will come out to be around that is ten thousand one zero four divided by five it will come out to be around two zero two hundred i think around two hundred let us take to assume this value is two hundred okay if we try to convert every element to this value two 200 what could be the cost you can see there are four one and if you try to convert each and every one to this 100 my cost would be like uh for converting this any one to this 200 it will require 199 cost into four for all the force plus this thousand to convert this thousand to this 200 and what is that cost it will require the cost of like 800 okay so if we find out this cost is coming about 800 plus this value is around 199 into 4 is around 796 i think and total answer would be like 1596. so if we try to convert every element of this array to the mean and mean is around if you can also take 200 or 201 because the it will have the decimal value of 200.8 it will have the decimal value of 200.8 it will have the decimal value of 200.8 so you can take either 200 or 201 so my cost would be around 1596. can this be the minimum cost to make all the elements of this array equal obviously not and why note that there are four ones present over here and there is only a single thousand present over here so can't we convert this thousand to this one only that is if we convert thousand to one all the elements of the array becomes one and this is going to be like yes i have found all the elements of the area as equal that is total number of distinct elements in present in this added would become one so to convert this thousand to one my cost would be like triple nine but uh okay but you can see this triple line is going to be like very less than 1596 and the cost difference is like around 600 yeah so this triple line is going to be the minimum cost and how this is going to be proved you can easily see if we take our the median of this array median is the point where the sum set of elements to the left of it if you take a sorted array and some set of elements to the right of it have equidistance that means there are equidistance from that point that is what i am trying to focus about since we try to convert all the elements of this array to this median and median is basically the it defines the state of the area is the point let us say i have access the median and it and x is the median of this array then this x has that is all the elements which are going to be strictly less than x and all the elements which are going to be strictly right greater than x which are going to be equal distance if we find out the sum this x is going to divide this array in like an equidistant manner and uh this is going to be like giving the minimum ends if we try to partition my array on the basis of this median and median is coming out to be x and if you try to convert all the elements to this x it will give us the valid and the minimum answer so we will try to make our every element of this array being converged to this x and x is the median of this array note that we need to perform sorting operation initially okay so let's move on to the code you can see i've easily written a six lines of code first sort the array and find the n which is going to be size and take the answer as zero find the median if n is odd median is basically the numbers of n by two and if n is going to be even our median is like average of this middle two values and it is going to n by two and n by two minus one indices of this num sarin values of the elements at these indexes divided by two and what could be my answer finally this is the absolute value of the every element of this addend with respect to median and since we are trying to convert i need to take the absolute value either we can increment the elements or decrement the elements and finally data on the answer this will give us a all test cases passed i think you can easily see i have some sort of accepted code over here and i'm basically trying to improve my runtime but i can't and my maximum and good runtime is 8ms and faster than 92 percent of cpp online submissions so if you have any doubts with respect to any of the things that i have discussed over here do not forget to mention in the comments section of the video and i will ask the viewers to like this video share this video and subscribe to youtube channel for latest updates thank you for watching this video
Minimum Moves to Equal Array Elements II
minimum-moves-to-equal-array-elements-ii
Given an integer array `nums` of size `n`, return _the minimum number of moves required to make all array elements equal_. In one move, you can increment or decrement an element of the array by `1`. Test cases are designed so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** 2 **Explanation:** Only two moves are needed (remember each move increments or decrements one element): \[1,2,3\] => \[2,2,3\] => \[2,2,2\] **Example 2:** **Input:** nums = \[1,10,2,9\] **Output:** 16 **Constraints:** * `n == nums.length` * `1 <= nums.length <= 105` * `-109 <= nums[i] <= 109`
null
Array,Math,Sorting
Medium
296,453,2160,2290
93
That Egg these people are going to discuss with him restore ip address servi question is what happened to us we will have a string life a strip will be formed that now we have to divide it into some tips like 9060 we have to put it in the party If we want to invite, we have to divide it into parties in this manner. The truth is that this partition is the total number of partitions and there should be one and the second condition is that the number inside each partition should be from zero to 255. For example, if we have time then 08 something means this belt means fitting too. There should not be any delay in starting below. If it is not in numbers then there should not be zero in its starting. Something like this is ok now. Presiding zero should not be in this type. Following the conscious condition, we have to tell you that no, how many parts can we divide it into, subject, daily, IP address, contact, it is correct, meaning, it should be divided into four parts with one number, hero. There should not be any presiding zero for 255. It's something like this. Look, let's take this one example. How to do the partition about this. You have the number 235, 215, more shift, after that, here, 1965, this is in this, it's good, okay so far. How are these made? From now on the cigarette is 255 dot here that the label is in the 11th this is this question so we are going to do this Now how can we do this which one which girl is this happened Okay let's take an example like 255 dad 250 5 ki 3338 so I can make a partition, I have made a tissue here, I can make a tissue or I ca n't leave this partition to launch the phone after making a partition, why? Want 250, if I take a four digit number then it's okay, so what I do is I do the tissue here, I just do the partition later, then I do the partition after that, so which one is normal, which one have I given you i plus I will do one partition, I will do partition of I plus two, I will do partition of I plus three, something like this is my first inch plus partition on the premises, this would be Malai, so I can do all these positions special edition, now look, there is a condition in the valley, it is below, I can petition plus two take up, there is a demand, I will put my number like this, then I have given 5 to 10 grams of partition or Khara one, here you are the only one of ours, this is not velvet, Edison, this is plus two partition, this because if it is like this, then we will give it to two 05 that here. After partition, we could not do tuition here because it is starting from zero, okay something like this, now what will be the problem in this that we should start from zero, okay now the problem is going to come in i plus free, that is 2952 penetrating. The middle of the partition is still there, so here I supported it for an hour, I partitioned it, but this number will go from 90 to 255, so what is the conditioning in it should start from zero, it can start from zero and from International This should be done, seats should be in the range of two digits, there is going to be an end in the country, there will be some condition for five plus one, now after this, our base will be sold to the tow work only then see if my I reaches the end, my I absolutely. And skimming sequence dot length that and second condition how much should be my partition if both of my conditions are hit means then send the answer to ok then these three will hit the dixit call, well this points is valid if this point is this then pin to We will call in this case, we will put this condition, if the answer is given, then we will add it in our result address. Okay, so see, we have to fold it a little, Ajay has to be confused, you are confused, okay, let's read the voice mail and make a function. Point jhal click height helper ok this is the ring taker number is the partition number is the first to put so first of all we are one permission of 9th May festival is gone ok check which scenes this is playing and always lag Will go here Ka or Partition Plus, if they wanted to enrich their knowledge then let them take it here that you are okay that if I have done all the things made in I Plus, it means see that I have broken in the character then see Answer Plus add in-depth then see Answer Plus add in-depth then see Answer Plus add in-depth study also director Aa aa that whoever was after character was proved to be answer minute or plus primary slots bean okay that laddu means like it was half one that such anger if point 2 f 3 4 5 store manager 122 cut then I will put dot here So these are the don't worry ones, okay now after that two more chords should be played which help + high plus immersed in cognitive partition + high plus immersed in cognitive partition + high plus immersed in cognitive partition plus work Pawan sir plus add then skimming coin till I brought it up to the best of plus minutes then answer glad That partition picture comes back, I added to it, I want something like this in the IMI Plus mission, calls will always be made, Pearl Commission is in a different village, that I got a function written, which became a custom soldier, first thing, who will go if this thing is found, means, if our The length of this note is greater than life, which means this thing will go up to the rank and it should be like I said, mine too, I have subscribed from 1 to 100. Okay, it means job settings, which is NDA, who will apply it between zero to 250 sets. Okay, so we will create a function related to this letter dots subscribe is fine from now till China Kashmir but its essay is a specific, the same condition was there for the third call, but there will be some change in it, what is the length in the school, find the restaurant, three So sometime Shahrukh will come here and say in English, okay, now I can do this, I will base it on that if my a yes brother is completely handcuffed of STR or my partition is former if both of my things were seriously crotch length first to I n Parents Loot Means Answer If you pay then we will make a list and pass it to the next one, rub all the list of typing in it, do it like I did this 1234, it is something that my one key got hit, what is in this adv1, while returning, don't press more than 120 buttons, this last one is fine. If there is, then there is an answer among those who add in the answer, here the add in is kept in half, good result, cotton should not be seen, it came till here from few days till Andher 500 subscribe like subscribe on address, like subscribe on address, like subscribe on address, a public junior, this is Valentine's Day. So the functions are Animal So you and Inter Pisces are the person of this zodiac sign, in this festival, take out the value of return road accident from this gas bank and request 25 and also apply it personally, we will have to make it in the subscribe list and now we will also pass it here. If you have to do it, then I can just check the paint shirt, so after making a call from here, now you can make a call here, but make a call like this for Rs.100 in Rs.100 in Rs.100 in more partitions, as of now, whatever is the time, MP Singh is in coma, and Ajay runs it. To jhal do picture play list of typing answer why is this animal fair not in the list jhal to ajay this is not important to no time on simple talent TCS has done well ok ajay where has retail zero been kept don't spoil the yes absolutely fine Why is the extraction gone next yes ok a pun starts then this is subscribed to us so here tax will be charged that you at this time the person who is Sanjay Bhai Placement Officer Dr that garlic is ginger will also work that I will take this of the last character ok this SIM conditioner here come in i plus that face message requested you length is ok submit it is that let's see i plus sit electronic * electronic * electronic * ok apps hai ajay ko apne friend 2016 bus return yaar appeared if soldiers looted then this dots covering letter If you want to set a dot, if you do n't want to give a rating, then it is good, then it is okay. Plus dots, it is specific. From now on, it is fixed. If it is okay, then it is acceptable. There is a problem in taking a decision.
Restore IP Addresses
restore-ip-addresses
A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros. * For example, `"0.1.2.201 "` and `"192.168.1.1 "` are **valid** IP addresses, but `"0.011.255.245 "`, `"192.168.1.312 "` and `"[email protected] "` are **invalid** IP addresses. Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order. **Example 1:** **Input:** s = "25525511135 " **Output:** \[ "255.255.11.135 ", "255.255.111.35 "\] **Example 2:** **Input:** s = "0000 " **Output:** \[ "0.0.0.0 "\] **Example 3:** **Input:** s = "101023 " **Output:** \[ "1.0.10.23 ", "1.0.102.3 ", "10.1.0.23 ", "10.10.2.3 ", "101.0.2.3 "\] **Constraints:** * `1 <= s.length <= 20` * `s` consists of digits only.
null
String,Backtracking
Medium
752
1,313
uh today we are going to decode the decompress roundless encoders in python so we are given a list of integers representing a less compressed for surroundings encoding uh consider each adjacent pair of elements for each pair there are eight elements with value b in the decompressed list returns the decompress list so um it's a little bit confusing in the description but if you look at example here one two three four and the output should be two four because uh as mentioned for each search pair there are eight elements with value b in the decompressed list so for the first pair um there should be one element of two because there are eight elements with value b for a b right so there should only be one of element two and for the next pair there should be three elements of four so four for four so um so it's actually not that hard to understand so if your input is one two three four five the output should be two four six because there should be one element of two three element of four and five element of six so um if you understand uh what is what the question is asking then you we can just code it up so basically we're dividing it into pairs and we'll do things to the pairs and return the result so we just initialize the result as a list and we initialize i at this is zero's position so while i is less than once of um gnomes if it's not out of range we will increment i by 2 to access the next pair right and we'll do things to on the pair so for g in range um i so because we'll repeat the nums i plus 1
Decompress Run-Length Encoded List
count-ways-to-build-rooms-in-an-ant-colony
We are given a list `nums` of integers representing a list compressed with run-length encoding. Consider each adjacent pair of elements `[freq, val] = [nums[2*i], nums[2*i+1]]` (with `i >= 0`). For each such pair, there are `freq` elements with value `val` concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. Return the decompressed list. **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** \[2,4,4,4\] **Explanation:** The first pair \[1,2\] means we have freq = 1 and val = 2 so we generate the array \[2\]. The second pair \[3,4\] means we have freq = 3 and val = 4 so we generate \[4,4,4\]. At the end the concatenation \[2\] + \[4,4,4\] is \[2,4,4,4\]. **Example 2:** **Input:** nums = \[1,1,2,3\] **Output:** \[1,3,3\] **Constraints:** * `2 <= nums.length <= 100` * `nums.length % 2 == 0` * `1 <= nums[i] <= 100`
Use dynamic programming. Let dp[i] be the number of ways to solve the problem for the subtree of node i. Imagine you are trying to fill an array with the order of traversal, dp[i] equals the multiplications of the number of ways to distribute the subtrees of the children of i on the array using combinatorics, multiplied bu their dp values.
Math,Dynamic Programming,Tree,Graph,Topological Sort,Combinatorics
Hard
null
78
foreign School subsets we are given an array of nums of unique elements important in ink return all possible subset the power set the solution set must not contain uh duplicate subsets and we have to return the solution in any order now for example for the example we told me one number of two we can basically have the number zero or an empty set so we can basically choose the number zero to be present in a set or for it to not be present in the set the first example is basically the same the there's an option to choose none of the elements which is just an empty set the resolution to choose only uh one single element from the input array then we can have all pairs and the last option is to choose all of the elements inside the other area and the funny thing to notice here is that number of the number of subsets the power slot length will be eight and we can cut there's a similarity between the subsets the power set and the bundle representation the configuration of the number so for example for three digits for three numbers we can use a binary number of length 3 to determine if the any of the element is present so for example if you want to reflect that all the presents the all elements are present we will use 1 and 1. for example if we if the first element is not present we will uh set the first bit to zero and rest of it to one same goes if none of them are present we'll just have zero and if you think about it to represent these eight numbers from zero to seven uh you have eight numbers you can only have one or zero so we have two options and to get eight you basically need a length of three so 2 to the length of the string that you need so basically that's our time complexity for the subset because if you have a strength of uh or a sequence of numbers which is equal to n uh we will have two to the end computation uh to generate all of the subsets now for the constraints the length of the array is from 1 to 10 and the numbers that we have inside the area from minus 10 to 10 nothing important and all the numbers of nums are unique so we don't have to worry about having the duplicates in the final output now if you go to our example let's say we have the same example one two three uh we have two options so we know that like we have two options now the base case is that we are run over the over all the candidates so our the things that we'll be passing to our helper function which we already always have for the backtracking problems is the index it will be the set of candidates so input array and we will have the current list which is our list that we are generating and also the result that we will be adding this uh current list to once we hit the base case so when Once the index is outside the boundary of the input tree we are out on the candidate so we can add that current list to our final result list now we have two options and the options user should choose or maybe element or not but for now we can either choose it and I will just declare it like this through the direct rectangle with X that means we haven't chosen it and this will be our index zero so we'll just increase the index so we can go to the next candidate and we recursively called the helper function uh so we can go down to the recursion tree now for the next shot we can either again choose number two or don't choose it we will again move the index and as we are doing this we are putting the numbers that feed the options that we choose inside our list of digits so we will choose one we will choose two and then we will choose three or we will not choose three so there are two options and let's just go to the left sub tree first so we have chosen this one and we will call the index will increase and we will call again and the helper function but now we hit the best base case and we can add this list to our result list now when we go back to the number two and we will pop the last element from our list that we are generating so it will be three and we will go to the right sub tree and because we didn't have we don't have to add anything we will just propagate to the next level but that index will be equal it will be out of the boundary of the size of the array so this sequence of elements will be added to the final list and that's how we will go through each one we will go back we'll first choose the uh options that we will choose the element and then we will go to the right node which basically means that you are not choosing the element each time we have two options and the depth of the Trees n so it will be two to the power of n times the multiplication because we are adding the array we are creating the new array from the um from the value that we are using to generate the subset at the new subset uh we will have a multiplication of n which n is basically the number the length of the initial array and for the space because we only have this current list the space will be again the only thing that you're propagating back down to the recursion tree is the array and this or this array which can be at most n so the space complexity will be linear to the length of the initial array first we will declare our result which is list of lists which will present our power set we'll be adding the cells that we are generating inside our helper function inside this result and at the end we will return it our helper function will as always take the index so we can know where we at the set of candidates which brings us over to the next parameter which is the initial array which presents the list of candidates that we can choose from the current list is basically the set that you are currently generating inside the helper function and the result is the list of all sets the power set and it will be returning as the final output of the function next if we get to the base case and then which uh which basically means that our index is autobondary of the set of candidates we run out of the candidates where we'll be just adding the current list which is our set that we have generated uh traversing through the recursion tree we will go back in the recursion tree and in the regular scenario we will first add to the subset that we are generating the current element the current candidate at the uh the index is pointing to and we will iterate we will go a level down to in the recurring Tree by incrementing the index but on the there's this is the option of selecting the element the option of not selecting element is to remove the current element and just move the move to the basically the right node in our diagram we will move without it without adding the current candidate
Subsets
subsets
Given an integer array `nums` of **unique** elements, return _all possible_ _subsets_ _(the power set)_. The solution set **must not** contain duplicate subsets. Return the solution in **any order**. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[\[\],\[1\],\[2\],\[1,2\],\[3\],\[1,3\],\[2,3\],\[1,2,3\]\] **Example 2:** **Input:** nums = \[0\] **Output:** \[\[\],\[0\]\] **Constraints:** * `1 <= nums.length <= 10` * `-10 <= nums[i] <= 10` * All the numbers of `nums` are **unique**.
null
Array,Backtracking,Bit Manipulation
Medium
90,320,800,2109,2170
1,198
hey guys has been going this is jayster in this video let's solve another problem from lead code it's one nine eight find smallest common element in all rows given the matrix mat where every row is sorted strictly increasing order so there is no duplicating each row return the smallest common element in all rows if there's no common element return negative one so like this so five is the minimum a smallest number in each row well uh i kind of uh i have done the similar questions like the uh row matrix problem like find the top k element uh among a bunch of arrays stuff like that so here in this problem i can't let's uh think of a as a simpler case suppose the row only two rows right suppose there is only two rows how could we solve this problem elegantly okay if there is two rows you need to find the uh common smallest common element in these two rows we could just uh do with the two pointers right we just check the head and if this is not a smaller then we go next one if they are the same so this is the uh the this is the uh smallest common uh element and we're done so we could easily solve this with two but if there are more rows how should we do it well we just first we get the duplicates in these two rows right in this case we find two but actually two might not be in the second in the third row so we need to find all the duplicates so um i mean the idea is just to find and duplicates in two rows and do this all over again and again this is kind of like okay we get these two and get the duplicates and uh movie back right so that we only have one array now originally we have an array and now we get n negative one array until we have only one array that would be the only uh array of duplicates in our array and then we just return the first element and it would be done so what's the time complexity of this approach is that we need to actually obviously traverse through all the elements here right and all the elements here to tackle one round and we get the duplicates and then we need to do this again to all the uh for the next array so obviously we actually have to for each item it will be travis twice so i would say it's n suppose the n array m yeah it's generally uh linear time for all the elements count so this is it let's do it so first we create a function called find duplicate which accept every one in and r2 in this function we hold all the duplicates in the array and create a cursor uh zero let j equal zero y i smaller than a r one done and j smaller or two 2.9 if they are the same this is one of the duplicates right so we push i mean to the result and increment both the cursor if the first one is smaller than the next one if this first one is smaller than the second one then we move the first one to the next index and the other case we'll just move this j to the next and after this we return a result right and now we have this atomic function that will uh reduce one array for us we would just then reduce all the array in what we know why loop so when there is more than one array we pop we could keep a it could go from left to right and but the order doesn't matter we just use pop for better performance so top one equals matte pop because top two equals matte pop right and then we met we push uh find the duplicates top one and top two yeah and then there will be only one array left so we return the first array the first item if the reason is undefined then you return negative one submit run the code pretty cool let's submit yeah so this is our approach pretty simple i would say okay actually we could solve this or solve this problem in another uh priority queue fashion i can think of well it's just uh it will be more uh complicated than this one so i'll keep this keep in this approach so that's it hope it helps see you next time bye
Find Smallest Common Element in All Rows
unpopular-books
Given an `m x n` matrix `mat` where every row is sorted in **strictly** **increasing** order, return _the **smallest common element** in all rows_. If there is no common element, return `-1`. **Example 1:** **Input:** mat = \[\[1,2,3,4,5\],\[2,4,5,8,10\],\[3,5,7,9,11\],\[1,3,5,7,9\]\] **Output:** 5 **Example 2:** **Input:** mat = \[\[1,2,3\],\[2,3,4\],\[2,3,5\]\] **Output:** 2 **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 500` * `1 <= mat[i][j] <= 104` * `mat[i]` is sorted in strictly increasing order.
null
Database
Medium
null
4
Hello everyone welcome back to my channel Ban Sake End Show In this video I am going to talk about the list code top interview questions for the problem medium to short and marriage so before this why upload the video of the third problem in the playlist like this Continue Khatron, if you have n't seen the video of your pain problem, then your penis must be going left. You must watch it. If you are interested in And Channel, then subscribe to the channel. So the question is good. A question is basically whatever is there, the medium has to be taken out, you have dual. Dev something like this ok so it is said here that 200 tabs is one number two, the size of both can be different so both N and M are their size which is completely different and what do we have to do? Watching these two airtels together, if both of them do that, but then what will be the basis of justice, okay, both of us, the media will be different, the buttons will be made with both of them, I want the medium of black total employee judgement. If you like then there are two ways to do it. One is that she was saying that there will be time complexity, there should be plus login place and then this will be a fully optimized solution for you. So in this video we do not do it after that, first. We basically have to understand that how can we do this in basic porn basic, after that we can do it in some other video, then definitely subscribe quickly, then how do we fit its medium in that way, then like if we Unless we learn the basic skin, our solution will never be able to reach the footage. Like, the first basic dream is to optimize us. Fundamental changes. Stay dream. The solution will have to be found out. Then we will see against it. Now how can we decrease its complexity. Okay so. First we are going to talk about the basic which is okay, so the question every day, you will understand, you have both add 1312, after mashing it, now look, I am not able to get 123 in the desert, I will look at these two together. So it will be one to three, then after consulting the doctor, this thing will definitely happen, so here I will tell you what will be in the complexity and it will be the seeds of the employers and the off in plus that there can also be a complexities like Chanakya. It is clear that it is simply said in login that it is near to TAM, it is near plus lage me administration * Login, it is me administration * Login, it is me administration * Login, it is more inferior than this, we will talk a little about the complexity of this one, then after stretching it, we will take it till here and one Secondly, now we have further optimized it and if we do not add it in this video, then this video will become like a complete report series. We will not talk about it very big. Now we will talk about it simply by stretching it. We will go till here and watch this one in some other video, here I will click on it, you have the gender reference, okay, so now that the question is understood, then we move forward by completing the total solutions, okay, what is the first problem, just you. Maintenance is allowed to be done that the school Anshuman Agarwal is different, the name is Suman, it is sorted or the password is and so and this is Hello A Love Story Jewish State, okay now write to us the MAC address of these two Amar Singh. ₹ 1 Wrote Hussain Question had to be ₹ 1 Wrote Hussain Question had to be ₹ 1 Wrote Hussain Question had to be written simply, here you have this, its size is M, its size is end, the employee's judgment of temperature will be ok and finding that in is now simple, the most fundamental, which is the most basic, anyone can understand. What should I do, I attach the element behind with Namaskar, okay, after that, subscribe in a simple way for alarm 2. Okay, so I am posting here till now, so on the fitting side, it is still on our channel, but keep quiet, remove the media. Now I have kept the elements, the stripes will be soft, no, it is not necessary that this bank will be soft because I have kept the first element on regular basis, its second elements, now it can happen that 1250 starts from zero here and area two three like this. If you have time then like and comment, then like I will join it, now okay, like we have softened it, so what is the login as yours, which is yours, this is what I had said in logic and complexity, here is the maximum of these. If you are a guest then you want to write simply maximum, okay then inch plus in log in plus instead of these in log in, I have written Agyeya Complexity, you have read it till now, you have set it, now you neither know the media, nor tighten, middle. There should be an element, if there is anything else then it is inches plus 12247 then it is okay if the corresponding likes come out, we do that thing and there is no problem in it, okay, so for the complexity increase of this one, I have returned it here, but this We can optimize, we can explain from this, it is appointed, okay, now how to do it, its number is closed, it is sorted, number to hunted, okay, now I give it a Hey, let me show you how to solve the problem and this is a simple back, you will not be bored. It's yours to do, they are doing it soft, that would be a problem, here I wrote Niwas Nehra and you were everywhere OK so let's say yes friend, you can remove it a little, it was given to you a week ago, two, nothing, ok, I am 1234, this is simple. Hai is a bird, simple, will take here, dam left, were here, white, right here, six days, here, self, four, till evening, share and this is also soft like dry ginger, but the edit that will be made here has the idea of ​​these things edit that will be made here has the idea of ​​these things edit that will be made here has the idea of ​​these things that Dry ginger, keep in mind, what should we do, we will cut the first point of both, it is okay if the first element has to be awakened which is the smallest because after this element increases, it is clean, then the one which comes first, like these two, its starting and its starting sometime. Control above must be coming on one of the particular indexes. Hunting of these two which is the first point induction. If you subscribe then our first point is 10. In this we also change the color on B0. Yes, so here on zero its first point is coming right now. Only then will the minimum come to whoever is appointing among these two. Why won't the maximum come? If it was only 12512, if you come till the maximum and after that you can maintain it then it is wrong because I have to keep increasing order that you Keep it to the minimum, I will keep it curly, this is what I have to use here, I will be here then this person will be the appointing element and this point which was there is the element medium gift mill, I have seen that the union of these two has been made to get the former and is. This forest is like this, I have extracted this element from here, lined here, okay, now this was the smallest in half an hour, now the school is here, this is this and the village is this, who is the kissing among these two before this is bigger but this is smaller than this. And then this one is smaller but this one was the next coming element so this one is smaller, the head will come and the smaller one is intact, it will increase by one and go away, look at this here, let me look at these two elements, again now fasting and C is now there is point one MP3 and small method in water here I added the value and this small one this illegal one this one Remedy 4.45 four is 4.45 four is 4.45 four is fine it is done oh it is sorted that is why what we are able to do is after four again small was So forces came in 2008 and who is younger 525 has been added here and its value is that this point 786 accused is completely finished, you will get this because young people subscribe complexity of ok soon near If complexity has come then somewhere we have come to a lot of these love games, these have come upon us, okay so this is what happened to my mother, let me tell you, to a great extent, okay, so I think that this part is a little bit of a trick pack. Keeping aside, how are we doing this? Okay, so now you go back from the point below, as far as these two points are concerned, when we will come together that we have got this house and all this, then what should we do for the ATM? But for the simple Android Information Rights Award and Jobs in California, he will take it out and by simply adding that index, the value will be there, he will fit it. Okay, so let me screen you its code. This is your lips, I will show you that I have done it in the entire match. What have you done? Hello friends, if you have any problem then do tell in the comment box below. Okay, till the time the code opens, okay, now for more humor, if I increase the time a little point so that you can understand, look like this. A double for inside. Why is it media? Because in China's position, you are the main one of the two. Okay, so let's talk less about it here. First of all, the total person is going to be our new name, woman or real, whatever we are becoming. If you come in its size then M and elements are going to come according to these two then there will be employee judgment. Temple has been sent by the person who came in the name of slice that I will joint this position by dropping the subscribe position and it is ok for that. For your pimples, just keep an eye on some index, I am talking about that, if you want, then either do nothing, look at this side, do it in the 10th over and keep doing something in the ghee, then it will work there too, okay, so here it is. Subscribe to the channel till the time you subscribe and want more, it is ok so I am looking at the simple one, if the number one off event will be held in Namaskar, it will be smaller than the stop, will say, the number one has become smaller, the DJ one will be plumbing ad, neither the first one will be smaller. To do that part, we made it small and made it obscene, if not then it would be really big, then we added the second rally and will increase its index. Now both of us have increased our extra inches. Yes, this is the panchayat. Wherever it is, make it out and these pink two will have to be fitted in it, otherwise I have increased both of them after this, so instead of writing once inside these two, I have pressed and written that its size has increased here. Now it may happen that neither of them are in the same size range or there is one person who is a bit like them. If both of these meetings are over, then if both of them are over then this Lucent will come out. So if someone 1 liter is finished like where after we have set that it is finished, this time will not go, so we have one person should go to these two, then whatever will happen, the first one is subscribed, so let's go here. And subscribe and this can be done okay now you want this whole plus crackers and that and simple here last suicide okay so all the elements as we did on that at that time I have done all the elements on that Add the name in it, I did it in the printer and checked it for the giver here. If you want it, then add all the prostate on top of it, now what should I do after that, take out the media, what will be in the media, do the middle element, do the hot pose, end one by one and check. That if I have my daily point, then simply invite, otherwise invite two and number two minus one is fine from the side and why is this Android two minus one happening, you understand, Android plus one is now - we are closing because West is now - we are closing because West is now - we are closing because West Indies and this is the simple thing instead of plus two, so I have definitely subscribed to this thing, so in that case, if you have this addiction, Android two and send the number to me two minus one by one two three four, you will store this internship, Pluto. Do it, I am not like you, we have taken double of it so that we can make it floating point web 2.0, make it floating point web 2.0, make it floating point web 2.0, I will take it here, MP will be returned, I only asked you to switch off the media, then its full detail explanation is active life love. To my solution which log in plus with this complexity I will lock the app in the same video quickly ok so in this video I have matched till then the video should not be too big, should not be too long ok will do 100 fit stunts Food Coloring and Telegram Channel Add the link in the description box and watch the cycle. That's all there was in this video to tell something. Subscribe to my Tashan channel. If you don't subscribe, you can also share it with your friends. Okay, see you in the next video.
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays. The overall run time complexity should be `O(log (m+n))`. **Example 1:** **Input:** nums1 = \[1,3\], nums2 = \[2\] **Output:** 2.00000 **Explanation:** merged array = \[1,2,3\] and median is 2. **Example 2:** **Input:** nums1 = \[1,2\], nums2 = \[3,4\] **Output:** 2.50000 **Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5. **Constraints:** * `nums1.length == m` * `nums2.length == n` * `0 <= m <= 1000` * `0 <= n <= 1000` * `1 <= m + n <= 2000` * `-106 <= nums1[i], nums2[i] <= 106`
null
Array,Binary Search,Divide and Conquer
Hard
null
518
in this video we're gonna take a look at a legal problem called coin change number two so basically we're given a coins array as well as the integer amount um and then we're asked to find total unique ways to make up this amount by using these coins right so you can see that uh in this example we can have five right we can take the coin five which make up mix up this now we can also take two twos and one right we can also have two plus one but we can have just uh five one coins right to make up this amount uh and you can see that there are total four unique ways and you can see that we cannot have like one plus two plus one in this case we need to have unique combination right so in this case we're just returning four and previously i did a video called quantum change number one basically uh in that video uh there's only like we can only take uh one coin right so they're very limited if we use uh coin one we cannot be able to use coin one again right but in this video we have to assume that we have infinite number of each kind of coins so in this case what we have to do is that we have to basically return the number of ways the number of unique ways that we can be able to generate using these coins right to generate this amount and you can see we also have another example like this where if we cannot be able to make up this amount using the coins that we have then we're just going to return zero right and you can see that we can also have another example like this but basically another example that was ignored uh in this question is that if we have the amount is actually zero like you can see that the constraints that the amount is can be actually zero so if it's actually zero and we only have one coin there's actually just one way to make up that amount right i know it's kind of a little confusing but basically if i have zero amount and i have one coin and there is actually one way to make up this amount by just not giving any out again not by not giving any coins at all right so how can we solve this problem so i'm just going to take you through step by step how i come up the solution how i come up with the dp table but basically what i did first is i look at this array i try to think okay how can i break the problem down to a smaller cell problems and basically i know that okay these are the amounts right this is the table and these are represents the amount so we know that um like if in this case zero if the amount is zero then we have one unique way right and then if we have amount one right so this is the these are the coins and then if we if the amount is only one um so in this case then there's only one way to make up this amount right because in this case it's just one right um so just one right so in this case and then in this case if i have amount two then i have two ways so i have one plus one or i have two right so in this case i have two ways but for three you can see that we can have one plus two right or just one plus one right so in this case the same thing we have two ways uh for four we have three ways because we have two plus two right or we can have one plus two right or we can have uh one plus one right so in this case we have three ways but for five we all know that we have four ways just like i mentioned before like this right we have these combinations these unique combinations which give us basically four combinations right so how do we figure this out like how do we go from step by step to break this problem to a smaller sub problem so we know that um in this case we have all the possibility right so for each and every single amount we have all three possible uh we have all three coins to take so at first what i did was i try to think okay so if the amount is one right so i can iterate the array so in this case one minus one which is zero so one so in this case one minus one right so in this case the amount minus the current coin which is one so minus one is basically zero so in this case zero has one possibility so in this case it's just one right and then two right in this case two uh one minus two is a negative value so therefore we cannot be able to take that as a count as well as one minus five is also a negative value so we cannot be able to take that as account so in this case the total um in this case yeah the total uh unique weight to generate this amount by using these coins is just one right and then i thought okay well what if i have two so the amount is two so i can do the same thing right so in this case um so two minus one right in this case is just one right but we already so in this case we left with amount one right because in this case amount is two the amount two minus the first coin one which left us amount one and then we already computed that um the amount one has one unique way right but that you one unique way is only for all three coins right so for all the all of those three coins the uni uh there's only one unique way to get here but in this case we want to know the total unique way for just one right so in this case we don't have that for just like one directional array so let's just continue basically like you can see if the amount is two minus one which is basically one amount one so amount one has one uh unique way so in this case we have one right and then two minus two which is in this case zero so zero in this case have one unique way so one plus one which is two so far okay and then in this case two minus five is negative value so in this case it's not going to work so we pass right so now we just have two for two unique ways right in this case one plus one we're one plus two so once we get to three uh things start to change because you can see that uh in this case three minus one which is two so we already compute that so two has a uh has two unique ways right so you so we already compute that before but you can see that this value right here right this value right here this is the total unique ways for the entire array but what we're trying to do here is we want to know the total unique ways for the amount three minus one which is amount two right so we wanna know the total unique ways for uh coin one but we didn't vote but in this case we're actually getting the total unique ways for including the coin two as well right so in this case what we had to do is we actually have to create a 2d array right a 2d table that we can be able to keep track of the um total unique or yeah in this case the total unique ways for each and every single amount so the idea is the same right um if i want to know the total unique ways um for the current amount right like let's say the current amount is x right if i want to know the total uh if i want to know the total unique ways to make up the current amount using the uh using the current number of coins what we have to do is we have to know the total unique um combinations if we take just coin one right plus the total unique ways if we just take two coin two plus the total unique ways if we take coin three and so on and so forth and then once we get the sum of all of those coins we can be able to know how many um total unique um ways to make up the current amount right so let me show you an example here so you can see this is our um like sorry just this is our table so far so basically this these are the uh mounts right sorry these are the mounts and then these are the coins so in this case you can see uh we have coin one right um and then we wanna know so here if the amount is zero and the coin's one then there's only one way right if the amount is one the coin is one and there's only one way to make up here right we only need one coin if the amount is two and the coin is one we can have two way or we can only have one way is basically one plus one right and so on for the remaining elements as well and now if we only have two coins right so we want to figure out how many uh unique ways to make up this amount right so basically what's trying what we're trying to do is that we're trying to know we already know that uh total unique way to make up this amount if we only have this coin right if we only have this coin we already know that and now we have to do is we have to compute okay the total unique ways to uh total unique ways to make up this amount if we only have coin two right but for this cell what we're going to do is that we already know the total unique ways to make up this amount with coin one plus the total unique ways to make up this amount with coin two together will give us the total unique ways to make up this amount with two coins right so does it make sense so basically what we're going to do is that um we're going to say 1 which is total unique ways to make up this amount with coin 1 plus the total unique ways to make up this amount with coin two right so coin two in this case one minus two which is a negative value so in this case that for the cell is just going to be one right okay so now it's more straightforward i'm just going to go a bit faster so basically two right two minus two zero is already computed before right so in this case it has one combination so one right four so one combination for two and one combination for coin one so one plus one is basically two um and then we have three so three minus two right so in this case we're only doing for two right we're only trying to figure out the total unique ways um for uh for coin two right to make up this amount because we already know the total unique ways to make up this amount with coin one which is already pre-computed so one plus in this case pre-computed so one plus in this case pre-computed so one plus in this case three minus two which is one which is right here right three minus two is one right so right here so one plus one is just two okay so here uh in this case we have four so in this case four uh minus two is two right so it's right here we already compute pre-computed that before so plus pre-computed that before so plus pre-computed that before so plus right plus the uh the pre-computed value right plus the uh the pre-computed value right plus the uh the pre-computed value for one right so in this case if we take the coin one um we know that for coin one it takes just only one combination to get to this amount right so one plus uh in this case two which is three right so which is going to be three um and then five in this case for amount five right so in this case we have one okay so in this case for one uh for one it takes one combination to get here right so one plus one right to get the 5. and then for 2 in this case we have 5 minus 2 right then the amount is 3 we already compute that before is 2. so in this case 2 plus 1 will give us 3 right okay now in this case here you can see the last row we basically have um uh in this case we're just going for the amount one right because five uh one minus five is negative value so in this case we cannot take we cannot calculate um how many combinations that we can make 4.5 but we already know so 4.5 but we already know so 4.5 but we already know so basically we're just going to skip right but we know that uh if we only have two points right the maximum amount of unique ways to make up this amount is just one so in this case we're just going to say one right put it right here and then for the next cell in this case it's just basically going to be the same thing two three right because we're inherited from the uh the previous result because in this case we're skipping the coin five right in this case if we skip the coin five we basically inherit from the previous rows result right basically it's how many um uh combinations that we can make if we only have two points right or how many yeah how many combinations uh we can make for this amount if we only have two coins right so for this cell right here basically what it means is that uh for this amount which is amount five right if um so basically how many combinations that we can make uh for coin five for this amount plus how many combinations can we make for coin two for this amount plus how many combinations uh can we make for coin one for this amount right all together will give us the value of this but you can see that for coin 1.2 for coin 1.2 for coin 1.2 we already know the total combinations right we already know the total combinations that they can make for this amount which is three plus the how many combinations we can make for coin five for this amount which is gonna be five minus five which is zero has one combination so in this case it's just gonna be one plus three right so which is just four and then yeah we basically come a long way then basically you can see that's the answer for this question right so this is basically how we break the problem down um and then trying to solve this problem right so you can see that we're basically trying to solve the smaller problems and then we try to use the solution for the smaller problems right to solve or get the answer for the final uh final problem right or the big problem so let's take a look at how i did this in code um so basically what i did here is i um i basically create a table right cache to the array and it's basically how many coins we have and then a plus one is basically the amount uh we use a plus one because in this case we're actually trying to calculate the total uh unique weights for this amount right for the amount that was passed in right um so we first build a first row right so in this case the first cell is always going to be one right in this case the first column actually is pretty much going to be one because in this case like i said earlier if the amount zero we have one combination um so we iterate the entire row sorry yeah the entire row um we're basically just say like for remaining amounts is basically equal to column minus so basically column is the amount minus the coin's at zero so basically it's the first rows coin right so like i said earlier if we only have one coin and then this is the current amount we want to see if it's actually a negative value so if it is negative value which is going to continue to the next iteration otherwise what we're going to do is we're just going to um set the current sales value right set the current sales value to be the remaining amount right in this case um we're going to set the current amount minus the current coin value which is basically how many combinations how many unique combinations that we can have uh for this current value right so in this case we're just going to build the first row once we build the first row we're going to build the remaining rows and at the end we're just going to return the last sales value right the last cells the last row less columns value so in this case for each and every single row right starting from the second row we know that the first column is always going to be one so we're starting from the second column and then for each and every single column we basically just go try to get the answer so we know that um we want to know the previous row right basically if we only have um like just like i mentioned before if we only have one coin um uh the total unique combinations if we have one coin plus the total unique combination if we have uh coin two right which give us total unique combinations for this amount right uh with two coins right so in this case this is what we're trying to do uh if we skip that's basically how many combinations that we can have for the previous row and then for take we want to make sure that it's actually within our range right it's not a negative value if it is not a vector if it's not a negative value we're just going to save it right we're just going to compute it right basically it's just going to be the current amount minus the current coin value which is the pre-computed um how many which is the pre-computed um how many which is the pre-computed um how many combinations that we can have right which is to take and then at the end for the total unique ways for the current amount with all the coins that we have which is basically skip plus take and then basically for this current position is basically the total unique waste right and at the end we're just going to return cash at n minus 1 a right which is basically the final row and final column and the time complexity for this one is basically big o of n times a is basically the amount and it's basically number of elements that we have in the coins array or a number of coins that we have in the coins array right so there you have it and thank you for watching
Coin Change II
coin-change-2
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`. You may assume that you have an infinite number of each kind of coin. The answer is **guaranteed** to fit into a signed **32-bit** integer. **Example 1:** **Input:** amount = 5, coins = \[1,2,5\] **Output:** 4 **Explanation:** there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1 **Example 2:** **Input:** amount = 3, coins = \[2\] **Output:** 0 **Explanation:** the amount of 3 cannot be made up just with coins of 2. **Example 3:** **Input:** amount = 10, coins = \[10\] **Output:** 1 **Constraints:** * `1 <= coins.length <= 300` * `1 <= coins[i] <= 5000` * All the values of `coins` are **unique**. * `0 <= amount <= 5000`
null
Array,Dynamic Programming
Medium
1393
1,371
hey what's up guys uh this is chung here so today uh let's take a look at 1371 find the longest stop stream continue involves and even counts so this one is a pretty interesting problem actually you know so given like a string adds right return the size of the longest substring containing each vowel and even number of times so you'll know that var is a iou okay and basically you need to return the longest substring that each of this a number has even appearances of course zero is also counted as an even number of times for example we have this uh string here and the answer is 13 because with this string here so e has appeared twice i is also twice zero is also twice and a and u are zero that's why you know everything it's even right and example two here right so this one uh it's this one l e t c here this one is because it's five because the e and e they're even right now the others are zero and this one obviously this one bcbc no there's none there's no like uh vowels in here that's why you know the entire string is satisfied and the constraint is like this right standard 10 to the power of 5 and as only contains lower english letters so for this one you know since we're getting the longest substring right and most likely it's going to be a sliding window problem and that's also what i tried to do at the fir at the beginning basically i was trying to use a sliding window algorithm maybe you know we try to expand the sliding window whenever we reach like a point that some condition doesn't mat then we shrink the left right that's how the sliding window works but this one you know after spending quite some time trying to figure out a sliding window algorithm i figured that you know this one cannot be solved by a sliding window because you know since we're we need to check the parity right for all the five files here for example if we have like some strings here let's see the left pointing to here okay and the right is somewhere here you know we cannot there isn't there's not like a clear condition that you know it tells you okay now it's time to shrink the left pointer because if we keep moving the right pointer we might get a bigger a longer string right because you know depending on what's after what's uh in what's after the right pointer we could have like another longer string that satisfy this kind of condition that's why you know this one cannot be solved right because you know let's say between the l and r right b it's an iron are there like uh two uh three e's right this one is like uh it's not a valid uh it's not like a valid string right then basic if we if in the normal like sliding window algorithm it's time for us to shrink the left pointer but in this case you know we could there could be like another e later on right that's why you know we shouldn't shrink l instead we should keep moving r right that's why you know we cannot solve it with sliding window and then i look at this constraints right obviously we cannot use a brutal force given like us a place which we simply just cannot check all the substrings uh for this one that will be a n squared solution right and they will tle so if we want to make some improvements and pass this constraints right we either have to find like either use like a priority queue or a hashmap to find out to help us to quickly find the answers at each of the index okay and then that's when i remembered there is like a very classic problem that i have solved so many times which is called um the longest subarray whose sum equals to k oh and one more thing so like i said you know we can either you should can either use like priority q or a hashmap to help us decrease the uh the complexity to look for uh the best answers right for this index but in this problem you know the product queue will not help us because the product queue always usually give us like either the smallest or the biggest right but for this problem you know all we care is a parity right it doesn't really matter like what's the account for each of the number here you know we don't know the uh we don't know the answer for like a certain count numbers all we care is the parity if it's even or odd that's why we cannot use the priority queue here and then the last option for us is the hashmap okay and then go back to my previous topic that's when i remembered i there's a problem uh i solved many times right basically given like a sub array right and this and the target k you need to find the longest sub array whose sum is k okay so if you guys remember that right we have some numbers here right and given like an sum equals like say for example 10 so how did we solve that problem we first we maintain like a running sum okay and at each of the location right let's say for example we're at right here we calculate the running sum and the second time we have target equals the running sum minus k because if we that's our target running sum because you know if we have two running sum right and then the difference will be the sub array that we're looking for and the third time we're having a hash map so we have a hash map the hashmap where we stored the earliest the smallest index for each of the running sum and at each of the index here we use the target try to find if the target exists in the in this uh hash map if it exists right and then we know we find a matching we find a sub array let's say for example this is a sub array because here it will also have a running the it here it will have the target here because you know if with the running sum subtract the target we know what that what the sub in between we'll have the target k we have the sorry we have the sum equals to k and the first one is that you know we only update right only add right to the hash map will not exist so this one is important because that's the way we can guarantee that for the same writing sum we only maintain the smallest one because you know let's say if the target is equal to three right and you know the numbers could be like uh either net positive or an active right let's say we have a three here and then let's say somewhere in here we also have like a running sum equals to three but he but in this case we don't update the index here right we only update index no we only insert into the hashmap when it's not there that's the way we can guarantee that for given like a running sum we it the hashmap stores the smallest index for a given running sum that's how we get the uh the longest sub array okay so that's a brief explanation for that problem and then for this and then we can just if we can use the similar logic for the current one that will be perfect right so now come back to our problem right so we have what we have a e i o and u so first let's take them look at them one by one so first we need a running sum which is the current state so for this problem it's like it's a running sum but for our problem it's the what is the it's a parity of this aeiou you know like i said you know the column doesn't really matter all we carry is the parity is either even or odd because you know let's say we have 2 0 6 3 and five okay so let's say this is the current state and now the second step is that we want to find the target so that we can use the hashmap to find the first target right so that we can get the longest substring in this case then what but for our case for our problem then what's the target okay if we maintain the count you know the target could be what you know so here you need to have like a good insight to be able to define this running sum and the target here because like i said we're looking for a substring or sub rate right who's who has like even count for all five balls so what could be the possible ones you know we have it could be two right it could be the 2 0 2 1 right so if the previous state is this one if the running sum is this one and then if the target is this one then you know four subtract two we have two it's going to be two zero four two four so this is a good one right but here we could have a different one you know t could also be 0 and 1 right so this one could also be a valid target because this one if you subtract this the running sum to this target you know we also get the like uh an even count for all of them so that's why i said actually you know the count doesn't really matter so all we care is the parity for each of the vowels here so either this one is like either it's even odd or even so this one is odd or even this is odd or even and if we can find a previous state right who has the same parity for all the five vowels and then that's gonna be the same one because you know as you guys can see so here you know these two are all a valid uh target right why they're valid because their parity is the same as the current state you know if this current one if the current one is like it's even let's say for example if the current one is four all we want to find is that if the previous one is also even because even subtract even is equal to even same thing odd subtract out also equals to even so now you know the problem comes down to if we can find the same parity right for all five numbers for five for all five pairs uh vols and since we only have five letters here you know we can use a beat mask to store the parity for all fives at the same time so which means that you know we will have like five bit mask here right so zero means even and odd and one means odd at the beginning everything is zero which means it's zero and every time when we have like when we see a different uh like a vowel let's say for example if the current one is it's like a it's like it's a e right so this one is e then okay we know this one will become one because we know now we have one e and the second one second time we see another like maybe a o here right and then we know okay so this one becomes to one and then the next one if we see another e here then we know okay so we have two years here which means we all we need to do is just flip this speed value right as you guys can see so the way we're maintaining this kind of bit mask is that every time when we have like a new vowel here we can simply just flip the value either from zero to one or one to zero because every time we add one count the parity will be changed right so now everything's pretty much clear right so now the we have a running sum which is the current parity and the target is the same priority because like i said with the same parity if we do us subtract right and then what's in the middle we'll definitely have even counts for all five characters letters and that's pretty much it is i think we can just then start coding that right cool so as long as we figure that out the left everything left is just a coding so first we need the uh the length of this one and then we need a running sum in this case it's like parity right so called parity at the beginning zero because at the beginning everything is zero right so all five zero so zero means zero and then we have the answer equal to zero and we have uh we also need this five volts string here a e i o u oh and we also need like hash map right so i use dp to represent the hashmap because this one is like it has a dp concept in it right so for i dot c in the enumerate s so here you know if the c is involved right if c is not valid then we simply just can ignore it uh we need the index right because you know since we're um we use this aeiou to represent the uh the five letters the five vowels right and then we need to give each of them an index that's how we do the flip the bitwise flip so i think in my case i use uh i use this one we have five zeros i think i am ace here so e i on u so this is how i map this uh vowel into the beat mask here so we have the index and then going to be valves dot index of c right so how we how do we flip the bit uh there's a trick right so we do we simply do uh xor is this one it's the is the one left bit shift to the left by index times right because you know i think i have already talked about this before so let's say we have this one if you want to flip this zero to one right if you want flip this one zero to one how do we do it we simply do xor with this one zero all right so xor this is going to be what 0 right so 0 1 x 4 is 1 and 0. all right similarly if you want to flip this one to zero right we do the same thing we do this one uh we also do a flip of this one and all the others are zero if you want to flip this one to zero right like i said it's gonna be zero one zero right so that's just remember this is how we flip a beat value and now we have this parity right so basically you know if the parity is in if the parity is in the hashmap okay that's when we can update the answer right so the answer is going to be the max of the answer dot i minus right the dp of parity and then we also need to update the hashmap right so basically if the yeah actually you know we can merge them all together right since you know since in this case you know the running sum and the target are the same they're both parity that's why we can merge them into one e-files here one e-files here one e-files here and then we have the parity out so we do a parity dp gonna be the parity equals to i right and then we return the answer yeah so that's it if i run the code here this one accept it if i run this one zero two oh i see uh so this is a special case here for in example two here uh the answer is the string starting from the beginning in this case you know we need to uh put like zero dot minus one here so this one can help us handle th this one because you know the way it works is that you know we need uh if we have like this one so this is the current i right so if we do a find like d if everything is from the beginning to current one you know we need to do the i plus one in this case right i minus one which is which doesn't exist in the uh in the heist map that's why we start we do initialize we put the zero and the minus one into it if i submit yeah it's a night pass right and yeah so as yes you guys can see the time complexity for this one is it's off in right because we have hashmap and this one at the index is this is the o of 5 which is a constant yeah cool i think that's it right as you guys can see the uh the code is pretty short but the thinking process is pretty lengthy right basically you know we uh just to recap right so first we try to solve this one uh using sliding window but it turns out that's not it's not possible and then we're trying to see given these constraints we'll see how if we can efficient efficiently calculate the find the uh the other side because given like the right pointers if we can even efficiently find the left pointer that'll be good right and then we have two options we either use prodigy or the hashmap right but the product queue since we're doing this parity thing here and we it's not useful that's why we go to the hashmap and then for the hashmap we remembered right we have a similar problem uh that we have solved before and we simply just need to convert this problem into that problem one way or the other okay and then so the way we're converting is that you know we're maintaining like a running parity state okay and in terms of the target right it's the it turns out to be the same as the current parity because in the same parity if we do a subtract was we'll be sure to get like even number of counts for all the vowels and there you go and that's how we solve this problem um yep it's a i think it's pretty cool problem and i hope you guys like the video and how to stop here thank you for watching this video guys and stay tuned see you guys soon bye
Find the Longest Substring Containing Vowels in Even Counts
minimum-remove-to-make-valid-parentheses
Given the string `s`, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times. **Example 1:** **Input:** s = "eleetminicoworoep " **Output:** 13 **Explanation:** The longest substring is "leetminicowor " which contains two each of the vowels: **e**, **i** and **o** and zero of the vowels: **a** and **u**. **Example 2:** **Input:** s = "leetcodeisgreat " **Output:** 5 **Explanation:** The longest substring is "leetc " which contains two e's. **Example 3:** **Input:** s = "bcbcbc " **Output:** 6 **Explanation:** In this case, the given string "bcbcbc " is the longest because all vowels: **a**, **e**, **i**, **o** and **u** appear zero times. **Constraints:** * `1 <= s.length <= 5 x 10^5` * `s` contains only lowercase English letters. It is the empty string, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string.
Each prefix of a balanced parentheses has a number of open parentheses greater or equal than closed parentheses, similar idea with each suffix. Check the array from left to right, remove characters that do not meet the property mentioned above, same idea in backward way.
String,Stack
Medium
2095,2221
382
foreign with the lonely Dash and today we're going over leap code question 382 linked list random node which states given a singly linked list return a random node's value from the linked list each node must have the same probability of being chosen implement the solution class so that's going to give you a class called solution and it's going to give you the head value of a list a linked list and all it does is it initializes the object with the head of the singly linked list that's pretty simple and straightforward it's giving you the linked list then they're going to give you a get random function and basically they want you to write something that chooses a node randomly from the list and return its value right that's what it has to do all the nodes of the list should be equally likely to be chosen so even though they make it look pretty complicated it's a simple concept so how are we going to solve this well we're going to use this example right here example one it's a singly linked list one points to two points to three and all we're going to do is go through one time this linked list and we're going to stick all the values in Array so this one would look like one two and three now we have a length for this array which is three and then once we have that information we're going to give a random integer generator which is that exists in pretty much every language we're going to use random interject integer generator and we're going to say hey give me anything that is between 0 and 2 right because if the length is 3 we're thinking in indexing so that would mean we'd want indexes is 0 1 or 2. right so it's a total of three but it's indexed uh zero indexed and so the random integer will give us one of these three numbers and then we're just going to return whatever value is in this array at that generated um that generated integer as an index so it's pretty simple pretty straightforward let's take a look up here at our constraints and see if there are any edge cases so for our edge cases their constraints basically just say that there's going to be a number of nodes in the linked list and it's going to be anywhere from 1 to 10 to the fourth power so we're not going to have an empty linked list so that's pretty simple all of the nodes are going to have values and they're going to be integers between negative 10 to the fourth and 10 to the fourth so we're not going to have a uh any issues there and at most 10 to the fourth calls will be made to get random so again nothing to consider there no edge cases that we're terribly worried about let's get to writing some very simple pseudo code okay getting straight to our pseudocode the first thing that we're going to have to do is create a function because it's we're actually provided the option for two functions I think when we do this uh let's just make sure I want to make sure we're doing this yes so if we're looking at it yes we're given one function and two functions with which to mess around with so uh we need to start by create a function that will add all of the values of the linked list into an array or a list right so we're just we have to iterate through a linked list because there's no way to find the length of a linked list without iterating through the whole thing so while we're doing it we might as well just create an array at the same time once we're done with that we're also going to have to create a function that produces a random number using the random Library based on the length of the created array and most languages that we're going to be studying python Java JavaScript there's going to be something that's already been created in a library that will produce a random integer so we will be using that and once that's done all we're going to be doing is returning the value at the random number that was produced index and that's it that's all of the pseudo code in order to write actual code for this question so let's copy and paste it and get coding so here we are in the Python 3 work area of the lead code website and we're just going to follow along with our pseudocode so the first thing is we need to create a function well the function's already up here create a function that will add all of the values of the linked list into a new array or list so let's create kind of an empty array we'll just call it nodes there it is and then we need to add everything so while head does not equal none right so while the head value does exist what are we going to do well we are going to append the value at the head to our array up here node so we're taking hey this array we're going to append or add whatever value is at the beginning of our linked list but of course that head needs to continue to move forward each time we're in our Loop so we're going to move it forward one position now at the end of this function there should be a full array called nodes that has all of the values that were provided in our linked list so that is how we create our function that will add all of the values now we need to create a function that produces a random number using whatever random Library we have and in Python that's just going to be random based on the length of the created array which we called nodes so how are we going to do that well first we need to understand how random Works in Python so if we're doing random dot random then we're calling uh random and this random is basically used to give us any number between basically 0.1 up to nearly one between basically 0.1 up to nearly one between basically 0.1 up to nearly one so 0.99 or something like that so it's so 0.99 or something like that so it's so 0.99 or something like that so it's only going to give us a value of something that is between 0 and 1. uh that's important to note so how are we going to get oh and I should put those in there how are we going to get that uh to be valuable to us because we can't just have numbers between 0 and 1. well first numbers between zero and one aren't an integer and we have to use an integer in order to use it as an index so the first thing I want to do is make sure that it's going to be an integer so I'm going to put some brackets around it because I want the uh program to give me an integer when we come out so random.random is going to come out so random.random is going to come out so random.random is going to give me a number between 0 and 1 well we need to have it give me something that is more so we're going to multiply this by the length of self dot nodes right and by multiplying it by this length whatever number between 0 1 comes out is going to change to be closer to one of the numbers within our length of our array so we're going to also have to give it a value and so that's everything so our choice is going to be an integer that is a randomly created based on the length of our array that we created up here so if our array is only 3 in length then this will give us a number between 0 and 2 because this length the way this will work is that the final number one through three is not going to be inclusive okay and then when we're done there hopefully all of that made sense we're going to return self.nodes and put Choice there so this self.nodes and put Choice there so this self.nodes and put Choice there so this is going to return whatever random integer this created and it's just going to tell us whatever the value is in nodes at that integer so hopefully that makes sense I'm going to hit run and see how we did fingers crossed okay it does work 52 milliseconds I'll hit submit and see how we did against everybody else in the world and make sure it works against all of the test cases and it does it beats a huge chunk 97 percent uh in runtime and 98 ish in memory so if you're looking for a quick way to solve question number 382 linked list random node this was my ideal choice for finding a quick and simple solution using python foreign
Linked List Random Node
linked-list-random-node
Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen. Implement the `Solution` class: * `Solution(ListNode head)` Initializes the object with the head of the singly-linked list `head`. * `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen. **Example 1:** **Input** \[ "Solution ", "getRandom ", "getRandom ", "getRandom ", "getRandom ", "getRandom "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, 1, 3, 2, 2, 3\] **Explanation** Solution solution = new Solution(\[1, 2, 3\]); solution.getRandom(); // return 1 solution.getRandom(); // return 3 solution.getRandom(); // return 2 solution.getRandom(); // return 2 solution.getRandom(); // return 3 // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. **Constraints:** * The number of nodes in the linked list will be in the range `[1, 104]`. * `-104 <= Node.val <= 104` * At most `104` calls will be made to `getRandom`. **Follow up:** * What if the linked list is extremely large and its length is unknown to you? * Could you solve this efficiently without using extra space?
null
Linked List,Math,Reservoir Sampling,Randomized
Medium
398
116
hey everyone welcome back and let's write some more neat code today so today let's solve the problem populating next right pointers in each node so we're given a perfect binary tree and what that basically means is that it's perfectly balanced so every single node that does have children will have exactly two children but the leaf nodes of course don't have children and that's where the tree is gonna stop and if you follow that rule you'll see that the tree is gonna be pretty much perfectly symmetrical right there's not any holes in the tree there's no missing leaf nodes nothing like that the node definition though is a little bit interesting of course we have the value for each node has a left and right pointer but it also has a next pointer that's the difference our goal is to populate each next pointer so that it's pointing at the node that's to the right of it so for example this 2 does have a node to the right of it and we need to populate that pointer but of course 3 does not have a node to the right of it so it's going to continue to point at null the default value the initial value of the next pointer i guess we can assume is going to be null also the root node does not have any right node so it's also going to point at null so this problem is a bit tricky because most of the time you might assume dfs is how you're going to solve all tree problems but don't forget that bfs is another way to traverse trees and in this case bfs will lead us to the easiest solution for this problem we're going to traverse each level so first we're going to be at this node and that's the only node on this level then we're going to start traversing the next level the way we're gonna do that is with a q data structure we're gonna add the children of this node to the queue and then when we're done traversing this node then we're gonna go start at the beginning of the queue we're gonna look at two we're gonna say okay it needs to be pointing at the next node in the queue so this is gonna be pointing at three then we're gonna be done traversing this and then we're gonna get to three it's gonna be pointing at the next node we know there is no next node in the queue and then as we were doing that though we would also have been populating the next queue we would have taken two's children added them to the queue take threes children also add them to the queue and so that algorithm is the easiest way to solve this problem if you've done a bfs solution before it should be pretty straightforward now the time complexity is going to be big o of n because we're traversing every node in the tree the memory complexity is also going to be big o of n because we do need a q and we know that the last level in the tree is going to have about n divided by two nodes in it so therefore the memory complexity is going to be this which we know the memory complexity of that can be reduced to big o of n so the question is there a better solution now they mention in this problem that technically we can do dfs and the extra memory uh from the recursive dfs does not count as extra memory so if we can do that then we can basically say that we've done it in big o of one memory and the way we could do that actually is more simple than you might think because suppose we're doing this recursively we get to the node one we know that the root node is never going to have a next node anyway but we know that its children should be connected right two to get two to point at three we can't do that from two but if we're already at the parent it should be easy for us because we have access to the left child and the right child so what we can say is the left node dot next should equal the right node so that's pretty simple and we can do that once we do dfs we can get to two we can do the same for its children four should be pointing at five but the hard part is gonna be how do we get five to point at six because two does not have access to six and this is the part where it's easy to get stuck but the solution is more simple than you might think remember we did connect two to three so two has access to three and three has access to six so it should be possible for us to connect five to six and of course that algorithm could be done recursively and we could keep doing that on a bigger and bigger tree but this isn't a true big o of one memory solution it's still using big o of n memory because of the recursion but there is actually a true big of one memory solution which i'm going to be showing you and then coding up and it actually relies on the same technique that we just talked about we can use these pointers that we're creating with these next pointers that we're creating to our advantage and we can use the original bfs algorithm that we were talking about remember we're first going to traverse the first level and as we do that we're going to be building a cue using the children and then we're going to traverse the second level and then while doing that we're going to be building a queue of all of its children but if we were clever and we connected the next pointers before we traversed the level we wouldn't even need a queue meaning we wouldn't need extra memory we could do it in constant memory but what we would need is a pointer to the beginning of the next level that's all we need because the nodes are already connected so the algorithm is going to be pretty simple this is going to be our current node this is going to be our next node we're going to know that this is the next node because it's the left child of the current node this is the beginning of the current level so the beginning of the next level must be the left child so what we're gonna do is take the children of the current node and connect them together until we can't do that anymore now in the first case it's pretty simple we're just connecting these three can't be connected anywhere else next we're going to take our current pointer and our next pointers and shift them so current is going to be over here and then our next pointer is just going to be the left child of the current pointer so the next pointer is going to be over here now starting at our current node we're going to do the same thing we're going to connect the children 4 is going to be connected to 5. we also need to connect 5 to 6. we can do that by taking by using this next pointer getting the next button and then getting the left child and then you know using that to connect the right child of two to that so we connected these now our current pointer is over here but we're gonna shift our current pointer now to be over here at the next node because we're using the next pointer we're going to go through this entire level just like a regular bfs now let's connect the children of three together six is going to be connected to seven and seven can't be connected anywhere because 3 doesn't have a next pointer that must mean that there isn't anything over here and then we would try to shift our current pointer to be over here right at the 4 and then we our next level node would be pointing at null because 4 does not have a left child and that's how you know that we're done with the algorithm because as we go through a level all we're doing is connecting the children of that level so if this level does not have any children there's nothing for us to do we already connected the tree you can see it looks pretty much exactly like what we wanted it to be and we did it in constant memory so now let's code it up okay so now let's code it up let's initialize our current and our next pointers the current is going to be at node and the next is going to be the left child of that node but it's possible that the node that we're given could actually be null itself so i'm going to do a little ternary operator in python so if the node is non-null then python so if the node is non-null then python so if the node is non-null then we're going to take the left child else we're going to take null and remember our condition to do the bfs is going to be while current is not null and the next level is not null so now we want to connect the children first we want to take the left child of the current node and connect it to the right node so we'll take the next pointer of the left node and connect it to current dot right and we might also want to connect the right node if there is a node that we can connect it to but that will only be the case if current.next be the case if current.next be the case if current.next is not null because if current.next is not null because if current.next is not null because if current.next is not null then we can say current.right.next current.right.next current.right.next is going to be set to current dot next dot left just like we did in the drawing explanation i know this gets pretty abstract when you have so many pointers but i recommend drawing it out if you don't remember what this is referring to and those are the only two connections we're going to be making per node next we're going to shift the current node to the next node in the same level if it exists so now if current though is pointing at null maybe the next node didn't exist so if not occur then current is going to be set to the next level and the next level is going to be set to current dot left and then we're going to you know just continue the bfs as if we're at the next level of the tree we're going to keep doing that until the next pointer is at null that's how we know we've pretty much done the entire connection and for some reason in this problem they actually want us to return the root node good thing we still have a reference to the root node which was the parameter node i think it's kind of dumb that they want you to do that but whatever let's run it to make sure that it works and as you can see on the left yes it does and it's very efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
Populating Next Right Pointers in Each Node
populating-next-right-pointers-in-each-node
You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node \*left; Node \*right; Node \*next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`. Initially, all next pointers are set to `NULL`. **Example 1:** **Input:** root = \[1,2,3,4,5,6,7\] **Output:** \[1,#,2,3,#,4,5,6,7,#\] **Explanation:** Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 212 - 1]`. * `-1000 <= Node.val <= 1000` **Follow-up:** * You may only use constant extra space. * The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
null
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
117,199
1,061
hello everyone welcome back to coding Champs in today's video we are going to be solving the problem lexicographically smallest equivalence string in this problem we are given with two strings of same length as 1 and S2 and a string based string we say s 1 of I and S2 of I are equivalent characters so for example if S1 is ABC and S2 is CDE then a equal to c b equal to D and C equal to e so the first character is equivalent to the first character in the second string equal to C and then the second character in the first string is equal into second character in the second string so we say p equal to D and last character is also equivalent in both terms equal to E equivalent characters follow the usual rules of any equivalent relation reflexivity a equal to a and cement symmetry a equal to B implies b equal to a and transitivity a equal to B and B equal to C plus a equal to c o k so the equivalent characters follow these three rules for example given the equivalency information from S1 ABC and S2 CD ACD and aab are equivalent strings of basting Eed and a b is the lexicographically smallest equivalent of the base string okay smallest equivalent of the base string by using the equivalency information from S1 and S2 let's take a look at the examples so firstly we are given with S1 equal to p a r k e r and S2 equal to m o r i s right now from the equivalency information we know P equal to M and equal to O and r equal to R and K equal to r equal to i and r equal to yes so P equal to m a equal to o r equal to R is by default so let me remove this and equal to i and r equal to S we can write this up here so r equal to yes these three are equivalent these two and these two are equivalent now what is the best thing given to us base string is p a r parser p a r s here now we have p P equal to M what is the smallest M so we write M here and then we have a equal to O what is the smallest a so we write a here since we have to find the lexicographically smallest at each position we try to choose the smallest character okay here we have r k r s r equivalent what is the smallest J right so we take K and then we have s also s r k r similar and s j is the smaller so we take F and if is e equal to Y the smallest is e so we take e and we again have R uh srk are similar so smallest skills we consider K what is the lexicographically smallest equivalent string we can form for the best thing is m a k e k so we written m a k a e k let us consider the second example we have hello then we have world so we know H is equivalent to W and is equivalent to Mo and L is equivalent to R and L is equal to 1 into L and O is equivalent to d so this is by default we know for everything equal to a and next we have H equal to W equal to O L equal to R and O equal to D we can write this over here okay now what is the best thing given to us h o l d gold and now uh for H equal to W what is the smallest is H and then we have o e o d r is similar so what is the smallest e so we write what is the small smallest is d right EOD smallest is D and then we have L for L we have L equal to R what is the smallest L itself so we write L and then we have the Boe are similar so what is the smallest T so the answer is h d l d is the lexiographically smallest equivalent of the base string let us consider the next example we have lead code and we have programs so from this we know L equal to p and equal to r equal to U and t equal to G and c equal to R equal to V and D equal to m equal to yes so equal to R and equal to O So we can say equal to r equal to O and then we have t equal to g c equal to r o equal to a so here we have o here so we can write we can remove this and we can write it over here or equal to VA and then we have the equal to this equal to our D equal to M and then again equal to s e is present here as well so we remove this and we write it over here um so and we have c equal to r is here as well so we remove this from here and we write C over here and can we reduce anything else L equal to P to equal to g d equal to M they don't appear over here so we cannot reduce it so this is the final equivalent uh character so what is the basic source code is purpose so where is yes s is here uh what is the least here a so we replace S with in the position of s we write a and for o is here so the smallest is here so we again right here and then we have u o Where is u U is not present in this so we by default consider U equal to U so we write U equal to U and then we have r is here so what is the smallest in this a so we write a and then we have C here see these all characters are equivalent to say in that a is the smallest so we write a and e is over here so in this smallest is here so we again right here we have c is present here so the smallest will be a again and we have o now o is here in this smallest again a so we write a and then we have d uh the equivalent to M the smallest CSD and then we have e is present here so equal to all these characters so the smallest of them are is a so we return we write a this model the lexicographically smaller string is this string so we return this so let's see how we can solve the problem so let us consider the example the first example we are given with a string S1 as Parker and S2s Morris we know the strings S1 and S2 are equivalent so the characters and the respective positions are also equivalent so let us write them P equal to m equal to 0 are equal to R and K equal to r equal to I and are equal to yes so let us consider them as the edges another point to observe is if P equal to m equal to P if you want to form Edge between P and M it will be undirected okay so let us form the edges so we have Edge from P to M and then we have H from a to O and then we have H from R to r to R is a self Edge so we know all by default or by the principle of reflexivity we know every character is equivalent to its it its own so we don't consider self edges here and we have K2 r and we have e 2 I and again we have R2 yes so this is the graph form for from the um from a given equivalence okay now let me make this graph smaller and what is the basing given is parser barset we write it over here now what is the lexicographically smallest string equivalent to the base string we have to find that so for that we iterate over the base string so firstly we have P for p belongs to this component in this component we have to find the smallest com smallest character so the smallest is M so we write M here and then we have a for a belongs to this component and lexicographically smallest character in that component is a only so we write a and then we have r belongs to this component so lexicographically smallest in that component is K so we write K over here and then we have Yes yes again belongs to this component and let's go graphically smallest in that component is K and then we are here e at e what is the lexical graphically smallest at this component it is e only if we write e and then we are at r R belongs to this component click score graphically smallest is K so the answer will be m a k e k this is the lexicographically smallest string equivalent to the base string so how we can what data structural algorithm we can use so this is like a graph and these are all like components so in the component we have to when whenever we are these are like queries whenever we are getting a character we have to go to that component and we have to Traverse the component we have to find the lexicographically smallest character in that component so we can perform DFS whenever we get a character we perform a DFS on that respective component and we can get the lexical graphically smallest string this is one way of doing it or else we can we have another data structure known as Union find in Union find we have for uh what we do let us see for each component we assign a leader we make we Union component using the Union function we make components and using the find function we find something in the we find a parent or the leader in that component so while making the components we have a leader uh in this problem we can make the leader as the lexicographically smallest character so if we consider this component that we can make um M as the leader since it's the smallest in this component we can make a as the leader and in this component we can make K as the leader and in this component we can make e as the leader so we perform Union on the given S1 and S2 so we perform Union for M and K we form edges between them and while doing that we have we make the leader as the lexicographically smallest string and finally we apply whenever we get M we apply find we find the parent of P so the parent of p in this component the parent will be M so we return m in this way we can solve this problem so let us see how the union find Works in this example so initially we have let's take the example hello world for this we have hello and we have world so let me first write down the characters h e l o w r and d so these are the unique characters uh while we are writing what we consider all the lowercase English characters but for explanation part I am considering only the unique characters present in our strings and initially all the characters are in their own components and now we perform Union operation uh between the similar character so H and W are similar so let us perform linear operation while performing Union operation what we first do we find we first find H in w we find the parent of which initially all of them are in their own component and all of them are leaders by themselves so parent of H will be hhf and parent of w is also W itself so we form an edge between H and W and what is the smallest thing smallest between H and W is H so H becomes the leader and W goes into it H's component so let me erase the W from here next we have E and O this parent of e is a parent of O is O So form Edge between E and O the smallest is e so e will be the leader and O will be the who will be its o will be in its component okay next we have let me erase o from here and next we have L and R so L and r parent of L is L parent of R is are performed H between lender and the smallest is L so L will be the leader and R comes into its component we form an edge between them it is the r is this okay next we form an edge between R and R is the parent of itself so we do not form the self edges so we leave it and we next move to O and D between o and the d u cos parent is e and this parent is D itself we form an edge between e and D what is the smallest D is the smallest so now D becomes the leader of entire component so we have let me write D over here and here is this and e will be a normal we form an inch between E and F and what is the leader is d so we have completed forming on all this in all this we completed forming unions between all the similar components next what we have to do for base string we have to find the lexicographically smallest so the best thing is hold and we have to find lexicographically smallest equivalent screen string for the base string for H we have to find the leader of um we have to find the leader of H or the parent of H for H it is parent of itself so we write H only for o we have to find the leader or the parent so the parent the reader of this component is D so we write D and we have l the parent of or the leader of L component is L itself and we have d um and the leader of the parent of decomponent is the itself will be ready this is the lexicographically small string so we return it this is how we can solve the problem using Union file let us look at the code in Union fine we basically should have a leader array so let's have a leader array no integer of 26 and um initially each leader should point to itself so let us make a loop and each character should point to itself here I am taking integer of 26 because in the problem we are given that we are the string consists only of lowercase English characters so we map a to zero p21 Etc and initially all the characters were mapped to themselves and now let's write the let's implement the Union function private void Union is X into y here we are considering the characters as integers a to zero B to 1 Etc so on that and now for X we find the leader of x find leader of X and we also find the leader of Y fine leader of Y and if both of them are equal if leader of X is equal to leader of Y then we just do nothing and we return else this reader of X is less than leader of Y in that case we make X as the X leader as leader to Y vice leader also so leader of Y will become leader of X in this Frame we make the smallest as the leader foreign and if Y is greater then we make y as the leader to X component so leader of X will become leader of Y so this is the union operation let's implement the fine parent function when parent Returns the integer and find leader it takes a increase at X if X is equal to leader of X then X is the leader of the entire component so we will return X else we return Point e leader of leader X so we'll find the leader of x axis leader if we make if you know path compression in Union fine we make leader of x equal to find leader to compress the path and what now we have implemented Union and find operations what we have to do next we iterate over these things I equal to 0 and I let's plan S1 dot length both of them are the are of equal length I plus and now we apply Union operation on the similar character so p is similar to M so we apply Union function on P comma m so s one dot character at I and we have to pass integer so we subtract a and S2 dot character at I do same thing here as well now we perform Union operation on all the similar characters and have formed the components next thing is we have to uh find the lexicographically smallest string similar to the base string so see and let's say it has result and initial light speed empty string now with Traverse load the base string character base string let's convert it to character array and now visual plus equal to we have this find the reader for the character we have to pass the integer so we subtract it returns our integer so we again have to convert the integer to character so plus a and we have to convert this integer to character so character openings let's finally we return the result this is foreign integer array let's run it now oh this is small y it passed all the sample test cases where to submitted it got accepted um so what are we basically doing here we are having we are using Union fine to solve this problem firstly we Union all the similar characters and we then go through the base string and we find the leaders of the components are basically the smallest characters present in that component so we find the smallest component and we add it to our result string and we return the result string um I hope you understood the problem and the solution uh there goes a lot of time and effort in making these videos for you so if you did understand the solution make sure you hit that like button and for more daily videos do subscribe to codingcharms YouTube channel keep practicing see you all in my tomorrow's video till then take care bye
Lexicographically Smallest Equivalent String
number-of-valid-subarrays
You are given two strings of the same length `s1` and `s2` and a string `baseStr`. We say `s1[i]` and `s2[i]` are equivalent characters. * For example, if `s1 = "abc "` and `s2 = "cde "`, then we have `'a' == 'c'`, `'b' == 'd'`, and `'c' == 'e'`. Equivalent characters follow the usual rules of any equivalence relation: * **Reflexivity:** `'a' == 'a'`. * **Symmetry:** `'a' == 'b'` implies `'b' == 'a'`. * **Transitivity:** `'a' == 'b'` and `'b' == 'c'` implies `'a' == 'c'`. For example, given the equivalency information from `s1 = "abc "` and `s2 = "cde "`, `"acd "` and `"aab "` are equivalent strings of `baseStr = "eed "`, and `"aab "` is the lexicographically smallest equivalent string of `baseStr`. Return _the lexicographically smallest equivalent string of_ `baseStr` _by using the equivalency information from_ `s1` _and_ `s2`. **Example 1:** **Input:** s1 = "parker ", s2 = "morris ", baseStr = "parser " **Output:** "makkek " **Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as \[m,p\], \[a,o\], \[k,r,s\], \[e,i\]. The characters in each group are equivalent and sorted in lexicographical order. So the answer is "makkek ". **Example 2:** **Input:** s1 = "hello ", s2 = "world ", baseStr = "hold " **Output:** "hdld " **Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as \[h,w\], \[d,e,o\], \[l,r\]. So only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld ". **Example 3:** **Input:** s1 = "leetcode ", s2 = "programs ", baseStr = "sourcecode " **Output:** "aauaaaaada " **Explanation:** We group the equivalent characters in s1 and s2 as \[a,o,e,r,s,c\], \[l,p\], \[g,t\] and \[d,m\], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada ". **Constraints:** * `1 <= s1.length, s2.length, baseStr <= 1000` * `s1.length == s2.length` * `s1`, `s2`, and `baseStr` consist of lowercase English letters.
Given a data structure that answers queries of the type to find the minimum in a range of an array (Range minimum query (RMQ) sparse table) in O(1) time. How can you solve this problem? For each starting index do a binary search with an RMQ to find the ending possible position.
Array,Stack,Monotonic Stack
Hard
2233
39
the combination some problem on Lee code asks for finding all you need combinations of numbers that sum up to a given Target here are a few ways to solve it we could first use a recursive backtracking algorithm to generate combinations by iterating through each number and checking if it can contribute to the sum if the sum exceeds the target the backtrack and try a different combination we could also utilize dynamic programming by creating a table where each cell represents the number of combinations that sum up to a certain value build the table bottom up considering all possible combinations we could also Implement a death first search algorithm where you explore all possible combinations starting from each number considering both the current number and all larger numbers that follow and lastly we can sort the input array and use two pointers one at the beginning and one at the end adjust the pointers based on some of the elements at these positions compared to the Target moving towards the desired combinations
Combination Sum
combination-sum
Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**. The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different. The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input. **Example 1:** **Input:** candidates = \[2,3,6,7\], target = 7 **Output:** \[\[2,2,3\],\[7\]\] **Explanation:** 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. **Example 2:** **Input:** candidates = \[2,3,5\], target = 8 **Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\] **Example 3:** **Input:** candidates = \[2\], target = 1 **Output:** \[\] **Constraints:** * `1 <= candidates.length <= 30` * `2 <= candidates[i] <= 40` * All elements of `candidates` are **distinct**. * `1 <= target <= 40`
null
Array,Backtracking
Medium
17,40,77,216,254,377
127
in this video we'll take a look at a legal problem called word ladder so basically the questions that were given a begin word the n word and also the word list which is a dictionary of word list we want to return the number of words in the shortest transformation sequence from the begin word to the n word and we can only change one letter at a time where that we want to change must be inside the word list so let me give you an example so you can see here the beginning word is hit so if the game word is hit then i have a dictionary which is uh these words right here so what i can do is this is the star word so i can change this word to hot right because i can only change one letter in this case i change the i to o so then what i can do is i can change the hot to dot right so i change the h to d i can also change to lot so change the h to l so now you can see i have hot is gone uh dot is gone and we also have lot is gone so now we have those words so dot can change the dog and lot can change the log right and then at the end you can see we just have to change one letter and this will give us cog which is the n word right so you can see here we just want to know the um the number of sequence right the number of transformation it takes to get to here um using the word list so you can see here i have one two three four and five right so i change five words right so there's five transformation right so you can do it either this way or this way but we just want to return the number of sequence that we want so now you can see we have another example right we have a begin where which is hit and the n word which is cog but the thing is we can change to hot first and then we have dot right so i can also change the dot here and i can also change the lot and then here i can change the dog and then here you can see i can also change to log but there's no cog in the word list so i cannot change to the cog right so basically you can see here i basically returned zero because there's no way for us to transform to the n word so now how can we solve this problem so to solve this problem one way we can do this we can use a dfs right we can do a dfs search from the beginning word to the n word so in this case we can just uh continue to go down one path let's say we have an incorrect path right so let's say here we have a let and let also points to a let's say another word called leo and leo also points to a different word right so what's going to happen is in this dfs we're basically just going to traverse down this entire incorrect path right well the correct word is actually right here so in this case we have to go down this path and then if we cannot find it we have to backtrack um and then continue to backtrack until we back to this the correct path to go down to another path right but what we can do instead is we could just use a breakfast search to search level by level and this way we once we find the word we can just return the current um current level right in this case we have one two three four five right so four or five right so we have five level to get to cog so we can just do this breakfast search and we will not um end up in a wrong path right this will give us the shortest path we can use a breadth first search to solve this problem so to do this in using a breadth first search basically what i did here is i created a dictionary i convert the list to a dictionary to a hash set and then i also have a queue right that's a global variable and we also have a counter basically counts the current path distance right which level we're on and so at the beginning we have one because in this case we're starting at the start word or the beginning word so we add the begin word to the queue and then what we do is that we're going to do a bfs to search the path so in this case if the queue is not empty so we're just going to iterate the current queue like current levels to all the elements that we have in the first level or the current level right in this case the current level is this guy right here we only have one so we iterate the size in this case one so then for we pull each and every single element out of the queue and then we're just going to see if this current word is actually equal to n word if it is we can return the count otherwise what we're going to do is we're going to visit the nearby notes right the connected nodes in this case the connected nodes are hot right so we add hot uh back in or sorry uh add it into the queue right just like how we did in this function here so what we do here is we're trying to go for each and every single combination so we iterate each and every single letter in the current string and then what we do is that we're going from a to z right so in this case for each and every single character i can try with a i can try with b i can try with c all the way to z right and then in this case we're basically just going to see if the word that we're replacing right you can see that current strain is equal to array so and then i check to see if dictionary contains this word if it does we're going to remove it and add this word onto the queue so that we don't uh end up traversing that word again or visit that word again right so and then in this case what we're going to do is that we're going to add the current character back into the uh the array so we're just going to do the same process and try each and every single combination to add to the connected word onto the cube so once we've done that we're basically just going to uh do the process the same we process the same thing we basically um iterate each and every single uh word that we have in our queue right and pull it revisit all the connected nodes and then add the connecting nodes onto the cube and then at the end you can see we're basically have to increase the count by one because we finished the current level so then we're going to see if the queue is empty if it's actually empty that means that we did not find uh that means that there's uh no um no n word that we can be able to find so at the end we're just going to return zero because we cannot find anything right so basically this is how we solve the problem so the time complexity for this algorithm is going to be n squared times n and the reason why we have m squared times n is because um here you can see we're iterating each and every single characters that we have in the string right so m is basically how many characters that we have in the string and n is how many uh words we have for how many strings we have in the word dictionary right so we're basically iterating each and every single character that we have in the string and then for each and every single character we basically try with a combination and in this case you can see here we're basically uh converting the strain array right or i should say the character array into a string so this will also give us a linear time complexity or big o of m so in this case m times m is m squared and then you can see here we're basically iterating each and every single string right in the worst case scenario we basically iterate each and every single string that we have in the dictionary so this will give us a time complexity of m squared times it
Word Ladder
word-ladder
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that: * Every adjacent pair of words differs by a single letter. * Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`. * `sk == endWord` Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _the **number of words** in the **shortest transformation sequence** from_ `beginWord` _to_ `endWord`_, or_ `0` _if no such sequence exists._ **Example 1:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\] **Output:** 5 **Explanation:** One shortest transformation sequence is "hit " -> "hot " -> "dot " -> "dog " -> cog ", which is 5 words long. **Example 2:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\] **Output:** 0 **Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence. **Constraints:** * `1 <= beginWord.length <= 10` * `endWord.length == beginWord.length` * `1 <= wordList.length <= 5000` * `wordList[i].length == beginWord.length` * `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters. * `beginWord != endWord` * All the words in `wordList` are **unique**.
null
Hash Table,String,Breadth-First Search
Hard
126,433
1,295
hi guys today we are going to do a little problem find number of even numbers of digits given an atom's of integers return how many of them contain an even number of digits so we need to return the count of numbers in the nums arrive which have even number of digits so number like number one 212 has two digits so this is even number of digits like 1 2 3 4 5 it has how many digits it has five digits and then if we take 2 1 3 4 then it has 4 digits so how many of them open these would be counter would be would add to the result this would I have to the result in this wood out of the result because it has even number of digits okay this has also even number of digits but this has five digits so it has not has even number of digits so we do not include this number so this is what we require to know from this problem then how do we this is a quite simple technique we just have to go through D digits like we have to go through these the number is 1 2 3 so first you take the yellow monster okay so 123 n would give us 1 3 go to a string because when we divide 123 by 10 then the yellow would be 3 because 1 one two 121 12 into 10 will give us 120 so they remain that would be three likewise then we divide the number by ten so we get answer 12 then we are getting take the module of the question quotient we get so what remainder is 2 then we divide 12 by 10 we get what we get 1 then we take yellow of 1 mod n we get 1 so then IBM will divide 1 by 10 then here we get also zero so here intensity base case where we have to stop our attention stop our electrician here ok so we will see how to code this is quite simple let's just do so we take a variable count will initialize it to 0 it will tell us the number of numbers which are even count of dejection okay and let's take a temporary variable then for each element any lumps add this is for you for each and what we will do is we I credit 20 and a month while element is not equal you see you know as we've already discussed that this one with the base condition okay so first element that would come to us is 12 so element is not equal to 0 so here what coincide through nope then the remainder it will be element and we actually do not need to calculate the remainder we just increment you think in number oh they judge in English enjoy and we will just increment the count here on the number of digits because this would be less than x and the while loop would rally so we just divided the element by ten okay so basically what would happen is we would get 12 then we will divide 12 by 10 so we can't answer 1 the element is still not equal to 0 so we ugly the count layer becomes 2 now then we divided by 10 so the answer 1/10 would divided by 10 so the answer 1/10 would divided by 10 so the answer 1/10 would be zero so here the page condition is fit and we will do not increment the count alone now we check if number of digits to 0 this is the condition where we check in for the number of digits even or not so we would increment the counter which would tell us that yes this number has even tickets and then the for each loop ends here then we return the cow let's run this code we get a correct answer okay so we get a wide definition solution for this was a very simple question hope you've enjoyed and understood how we approach the question thank you so much for joining in bye-bye
Find Numbers with Even Number of Digits
minimum-garden-perimeter-to-collect-enough-apples
Given an array `nums` of integers, return how many of them contain an **even number** of digits. **Example 1:** **Input:** nums = \[12,345,2,6,7896\] **Output:** 2 **Explanation:** 12 contains 2 digits (even number of digits). 345 contains 3 digits (odd number of digits). 2 contains 1 digit (odd number of digits). 6 contains 1 digit (odd number of digits). 7896 contains 4 digits (even number of digits). Therefore only 12 and 7896 contain an even number of digits. **Example 2:** **Input:** nums = \[555,901,482,1771\] **Output:** 1 **Explanation:** Only 1771 contains an even number of digits. **Constraints:** * `1 <= nums.length <= 500` * `1 <= nums[i] <= 105`
Find a formula for the number of apples inside a square with a side length L. Iterate over the possible lengths of the square until enough apples are collected.
Math,Binary Search
Medium
null
1,663
hi everyone welcome to my first video so uh this video is created uh to practice my english and solving problem i explained the tricks in english so anyway i don't think it would be really helpful but uh it's your option to choose whether to access this uh page or not and i hope it will withstand too much time anyway so let's see the problem okay quicker reading so this problem is the basically called the daily challenge question and it asks us to gather smallish strength so in lexi uh lexo lexiographically order so if you can get a right and don't get a b x okay so it gives us two um two input values so the first one is um so n is the length of the output string so if it gives you uh any x a is equal to three then you need to uh return a string with length three so yeah one two three zero i exactly three characters in this stream and uh the second one is the sum of the critical values so in this question each character is assigned to a unique value so a would be the value okay so let's write it so a you will get with 1 and b you would give it a two so something like that and the okay we're increasing so you finally get j as 26 okay so we are going to just deal with this 26 lowercase factors so now we need to think about how we can solve this problem so uh you can intuitively think about how about the solid from the beginning to the ending right so if we try to solve it from any and we would naturally think about it would ask us to give us noise strength so of course we would uh choose a and whatever until we get something like we counter or use a because we need to satisfy the condition that the sum of k is equal to the given value and then we just put the uh rest of okay i mean we just put the character that its value is equal to the rest of k like this one you make it with a and then you'll you only have 25 left right and the character that has the sun value to be 25 is the character y so you give it the y here and you uh therefore us to the final uh answer that would be ava but uh this method actually won't work if we have like a 28 here uh so like if you have 28 k is equal to 28 right and then you give uh the data stream will be a and this data means that there is no uh there is no any possible character that would satisfy the value that is equal to 27 right okay if you just give a here and you will have oh sorry if we have k is equal to 29 okay sorry about all of that previous explanation anyway so if we have twenty here of course we need to have uh a cracker that its value would be 27 but obviously we know the largest character the largest value of the possible character would be 26 so we can't spend a reasonable character to put it in this position so of course this algorithm won't work so how about the working from the earth to the beginning well that might be a way but let's think about it so what kind of condition we need to satisfy if we want to go back uh go through this uh um go through this out to the screen in reverse order so if we have a dot as well final answer and we need to put replace every dot with a value factor so now we need to uh check this one so what about this one so in this case we have a equals 3 and 10 k equals 27 right and naturally we will think about uh if we put this one as the largest character it could be so the previous two character would naturally become the possible smallest factor it could be and that's how we can solve this problem so in this case what kind of condition to satisfy so because we have already talked about her we need to fade a character with a possible largest value right but obviously we see that this is why instead of j because they is the largest term they have the largest letter right so why would they choose y instead of z because we need to make sure that the previous two characters could be a character so same question oh really how talking about when k is equal to 29 and the approach from the beginning wouldn't work because the final character value would be out of the range from uh with from zero uh from 1 to 26 and similarly here we need to make sure that the previous two characters value won't be out of range so maybe it would be lighter than that and we can't stand uh a possible character a suitable character here right and here is why we need to uh here is what condition we need to satisfy and we can say so if we have k sub k equals to 27 and then we need to make sure the previous two values has at least two suitable characters so if we have something like uh so if we have already faced data and k will be updated to a new k rather and for these two characters it will have a summer of some value of the new uk and the new k could be at least two right because you have two characters here the smallest some value of them would be two okay so it would be something like 27 minus something it would be equal to two okay and we can clearly say that this 2 would be the current index of the character value invasive so the rdx will be equal to n minus 1. okay because we start from the third position and in an array it is zero indexed so we need to uh minus one to satisfy this condition and the 27 is just k and what we need to minus to make sure so of course we need to minus the current value of this character so after we manage this the sum of the rasta of the previous two characters the value would be k minus this value of this character so it will be uh minus the current c okay so this is the current value of the character index the after two okay let's try to make it chromatic formatted okay so here have our condition and how we need to get this character say so we need to make sure it would be at uh it will be as large as possible so we need to lose through say to a right we still need to look through in a reverse order compared to the normal alphabet product and to make sure the space that is fine a ball condition okay and we know it could be uh this is the eighth case but you could actually be lighter than it if you'll get the raster sum of value of uh you get the rest of some value that would be larger than the previous length of the crackers it will be also all right because you can make sure that it will be like so cool graphically you small is the screen yeah because you really want a right instead of abx right so as long as you have something uh some character that satisfies this condition you must have uh put it in our result and after the k value and okay after we find this day we'll find this same update and oh sorry after k and break from our looping through uh from our loop from our for loop and then uh updated earn okay so that's the whole algorithm now we just need to code it so of course we need to use the lao group or you can use the follow that's your choice uh that's a totally up to you so i'll just use the value and we need to give the current index so it will be n minus one right and then we move they lose to from day to a and then if we check that k minus the current state and they say if we are going through the uh car value so you actually get it you need to gather say like a is equal to y you need to do a actual calculation like a minus a plus one so for b you just have something like b minus a plus 1 okay equal to 2 okay so here we have say minus a plus but it is a larger than or equal to our current fbx okay then we can just put it in our result okay we need to initialize the result here okay so right the idx will be equal to this say and we need to update our k okay is equal to 3 minus a plus one because we have already put the current character into this position and the k need to update to be updated as the raster summary of this previous two characters all right and it generally breaks because we don't need to look through the rest of value and don't rule don't forget to update the um as well uh if you are using a for loop so that we find i don't need to care about that okay let's try okay again this is a very personal video i'm posting it just to practice and so if it doesn't help you i'm sorry about that and i hope it won't waste your time thank you
Smallest String With A Given Numeric Value
detect-cycles-in-2d-grid
The **numeric value** of a **lowercase character** is defined as its position `(1-indexed)` in the alphabet, so the numeric value of `a` is `1`, the numeric value of `b` is `2`, the numeric value of `c` is `3`, and so on. The **numeric value** of a **string** consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string `"abe "` is equal to `1 + 2 + 5 = 8`. You are given two integers `n` and `k`. Return _the **lexicographically smallest string** with **length** equal to `n` and **numeric value** equal to `k`._ Note that a string `x` is lexicographically smaller than string `y` if `x` comes before `y` in dictionary order, that is, either `x` is a prefix of `y`, or if `i` is the first position such that `x[i] != y[i]`, then `x[i]` comes before `y[i]` in alphabetic order. **Example 1:** **Input:** n = 3, k = 27 **Output:** "aay " **Explanation:** The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3. **Example 2:** **Input:** n = 5, k = 73 **Output:** "aaszz " **Constraints:** * `1 <= n <= 105` * `n <= k <= 26 * n`
Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
null
1,684
Hello Hi Guys Welcome to my YouTube channel, I am Tiwari and in today's video we are going to talk about the problem of account number and consistent prince's play list and for those who are new on this channel, let me tell them that you can see the I button. Now you can complete and fit a clear channel, this was subscribe to do it do it ok so my problem statement was saying given friend aloud pen card me aloud consisting of different characteristics and subscribe button middle aged whose Now this is absolutely right here, Robert, so basically what do I want to tell you, which is the stream in which whatever elements you do, they are all heard, if they do not melt, then you will not account in Om Shanti and electrification can happen. Seen here three times but still it's contributing as no answer all 100g no one is in trouble because if you subscribe here in Marathi then it is very simple what you have to do is you simply click on continue then subscribe And subscribe The city is amazing The deposit is 42% of everything, if it is in this line, deposit is 42% of everything, if it is in this line, deposit is 42% of everything, if it is in this line, you will have to reverse it, otherwise I have appointed use here, so what can we do here, we can add this because we will use it, so what can we do here, subscribe, so this is I've taken I'm so I've taken now let's set the alarm from this so I say and I is equal to zero then our is less than what value suv cars by writing loud dot loop plus okay so here But I set the alarm subscribe here I can also do the second one and I do it seems a little bit so now we will do it here now this will do this let's now your GST Hey first time it will point here second time point here Do that means indexing, friend to children, this is going to work for you to see all the elements, any way, now we call them chicken, we have to do spring tribes, so I say and I is equal to zero iced tasty equal to zero iced tasty equal to zero iced tasty DTH length plastic, so now what is here? Have to do here click on us that I say that if the problem will not solve the problem for hours then I put this note operator it means that so a little bit of not contest does not mean that STR daughter at IT came toe flag Make off, above, make bullion name available, this is how I do the whole end room, keep it from initial to two, I will not do the cutting for half an hour, okay superintendent, we call it okay, now when I was on the village team, now I am appointed in schools. If he doesn't do it, he won't do it, then if I am here, increment my answer mini counter, okay, simply, if he doesn't do it, then there is no problem, friend, we have done this in the form because these people think that you will do it, so let's share it here. If I do, then you will keep one and a half, then you should subscribe here again, here this thing is not required to be subscribed, you can watch the railway by submitting it, friend, this was in today's video, if you like the video, then definitely subscribe the channel. If you haven't seen it on this channel, you will definitely check it out. That's all. See you in the next video. Till then bye-bye.
Count the Number of Consistent Strings
find-latest-group-of-size-m
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`. Return _the number of **consistent** strings in the array_ `words`. **Example 1:** **Input:** allowed = "ab ", words = \[ "ad ", "bd ", "aaab ", "baa ", "badab "\] **Output:** 2 **Explanation:** Strings "aaab " and "baa " are consistent since they only contain characters 'a' and 'b'. **Example 2:** **Input:** allowed = "abc ", words = \[ "a ", "b ", "c ", "ab ", "ac ", "bc ", "abc "\] **Output:** 7 **Explanation:** All strings are consistent. **Example 3:** **Input:** allowed = "cad ", words = \[ "cc ", "acd ", "b ", "ba ", "bac ", "bad ", "ac ", "d "\] **Output:** 4 **Explanation:** Strings "cc ", "acd ", "ac ", and "d " are consistent. **Constraints:** * `1 <= words.length <= 104` * `1 <= allowed.length <= 26` * `1 <= words[i].length <= 10` * The characters in `allowed` are **distinct**. * `words[i]` and `allowed` contain only lowercase English letters.
Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map.
Array,Binary Search,Simulation
Medium
null
888
uh this question is feel kindly swap so you are given to a red one is Alice the other one is Bob and then I'm going to summarize this question so you need to swap one element from Alice to the bulb and also above two hours and both of the sum should be equal air right so uh this is pretty much a math question so I'm going to say sound of Alice and then you need to swap an element right so you need to subtract 5x plus the element you need to swap from Bob Y is equal to the sum of Bob exactly the same thing minus y you need to this is represent why this represent X and then this is plus X right so uh once again that you if you do the math right so uh let me just quickly go over here so it's going to be what 2y minus 2x equal to SP minus S8 and just a little bit math just a little bit right over two right and then at the end this is going to be what a X Plus HP minus sa over 2 right so y equal to X Plus SP minus sa over 2. s b represents sum of the Bob array and the answer represent the sound of s array right so uh this is a pure math for sure and then uh what is given the given is X and Y right the element you need to swap uh in the ls array element you need to swap in a bubble rate why is Bob right X is LS and then SP is some of the Bob array essay is the sound of LS3 before this one right and then you use this idea right you can do uh you can just find a lenser right and this is going to be what this is going to be um uh for SP minus X it's going to be even number for sure right uh otherwise they are now going to uh they are not going to give you all number uh because if one over two and then you give what you give zero and this is not working right when you swap this is not working so uh just not worry about the odd number when this turns to the odd number right I mean this stuff definitely don't turn even number but I mean SP minus I say so okay so let's talk about the solution right so you use this equation uh to find out which candidate you need to swap right and then uh what you need to do is you need to calculate the sum of Alice you need to calculate the sum the ball first and then storing the Delta so I'm going to turn this into Delta right and I'm going to Traverse uh the ls array again but beforehand I need to know what are the elements in above array so when I Traverse the ls array right I can actually know which candy this is Alice candy and then this is Delta which can elect and swap uh for the ball right so uh this is going to be pretty much it right so it's kind of like not easy but also a little bit like uh thinking right so basically a candy and then add us right so sum a possible can be and then I'm going to copy paste but uh make sure you change the element and also you need a set you go to a new headset Shadow ad and all right so um you also need what um you also need to use Traverse again the address can be right so is the setup contents and also I forgot the Delta right sorry so sound B minus sum a and everything divided by two and then so what do you need to contain the X plus the Delta right so if you find it which means you can definitely Swap and then the sum are going to be equal so you need to return a candidate right so it's going to be new ink and this is going to candy and it can be plus Delta all right so uh as you cannot find it's gonna be returned no all right so I'm not sure I made a table or not but it looks like it's pretty good all right so let's talk about the time in space this is space and space right so this is going to be about all of the about right the element inside the box right the unique element inside the box so all of B for the space this is going to be a time all of a this is all of B this is all of a right so it's going to be maximum between the address or bubble rate so a lot of time space are pretty straightforward so I don't need to use a debug mode to actually guide you through what happened but uh just a little bit thinking is required so if you have any question leave a comment below subscribe if you want it all right peace out
Fair Candy Swap
mirror-reflection
Alice and Bob have a different total number of candies. You are given two integer arrays `aliceSizes` and `bobSizes` where `aliceSizes[i]` is the number of candies of the `ith` box of candy that Alice has and `bobSizes[j]` is the number of candies of the `jth` box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return a_n integer array_ `answer` _where_ `answer[0]` _is the number of candies in the box that Alice must exchange, and_ `answer[1]` _is the number of candies in the box that Bob must exchange_. If there are multiple answers, you may **return any** one of them. It is guaranteed that at least one answer exists. **Example 1:** **Input:** aliceSizes = \[1,1\], bobSizes = \[2,2\] **Output:** \[1,2\] **Example 2:** **Input:** aliceSizes = \[1,2\], bobSizes = \[2,3\] **Output:** \[1,2\] **Example 3:** **Input:** aliceSizes = \[2\], bobSizes = \[1,3\] **Output:** \[2,3\] **Constraints:** * `1 <= aliceSizes.length, bobSizes.length <= 104` * `1 <= aliceSizes[i], bobSizes[j] <= 105` * Alice and Bob have a different total number of candies. * There will be at least one valid answer for the given input.
null
Math,Geometry
Medium
null
1,957
hey everybody this is larry this is me going with q1 of the buy weekday contest 58. delete characters to make fancy string hit the like button hit the subscribe and join me on discord let me know what you think about this problem uh especially if you came from the contest well come hang out uh on discord where everyone chats about the contest almost immediately afterwards so you know you can get to it um yeah uh so this one is just greedy in that you look at every three characters three consecutive characters and if they're the same then you delete it um there are a couple of ways to implement this and you can be very sloppy so i definitely urge you know you won't see top people get it wrong because it's very easy to be sloppy um and i almost did that as well but in the end that's why i took two minutes even though this is probably not a two minute question i also to be honest misread this and dodge have to return to count for some reason of the number of deleted so if you see me try to solve this live after the contest uh or after this video you'll see me live during the contest and you know uh yeah but basically i just keep the string up the first two characters and then i look at the third character if it's not the same then i append it and then indiana we create the string this is linear time and linear space because you can not do better linear space so i did some like uh things to even make it a little bit more dubious but that should be okay um yeah that's what i have at this farm let me know what you think and yeah you could watch me solve a live and contest next all right let's go um so oh i messed up about the problem whoops messy um messy hey uh yeah thanks for watching hit the like button hit the subscribe button join me on discord let me know what you think about this farm again you know if you came from the contest we like going through the contest right after contest so yeah contest so come join me on discord and hang out with me and other smart people i'll see you later stay good stay healthy to good mental health bye
Delete Characters to Make Fancy String
closest-room
A **fancy string** is a string where no **three** **consecutive** characters are equal. Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**. Return _the final string after the deletion_. It can be shown that the answer will always be **unique**. **Example 1:** **Input:** s = "leeetcode " **Output:** "leetcode " **Explanation:** Remove an 'e' from the first group of 'e's to create "leetcode ". No three consecutive characters are equal, so return "leetcode ". **Example 2:** **Input:** s = "aaabaaaa " **Output:** "aabaa " **Explanation:** Remove an 'a' from the first group of 'a's to create "aabaaaa ". Remove two 'a's from the second group of 'a's to create "aabaa ". No three consecutive characters are equal, so return "aabaa ". **Example 3:** **Input:** s = "aab " **Output:** "aab " **Explanation:** No three consecutive characters are equal, so return "aab ". **Constraints:** * `1 <= s.length <= 105` * `s` consists only of lowercase English letters.
Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time.
Array,Binary Search,Sorting
Hard
2179
733
welcome back everyone we're going to be solving Lee code 733 flood fill so we're given an image which is represented by an M by n integer grid where the image of the row column i j represents the pixel value of that image we're also given it three integers uh srsc and color and we need to perform a flood fill on the image starting from the pixel image source row Source column and they tell us to perform a flood filler we need to consider the starting pixel plus any pixels connected four directionally to the starting pixel so what we need to do is we're given this middle pixel in example one essentially what we're going to do is perform a breadth first search to find all of the pixels that are for directionally connected to this one in this case it would be this one right here and then this one and then we would continue our breath first search looking for pixels of the number one that are four directionally connected to the to this pixel and this pixel in this case it would be this one and then this one here all right so then whenever we hit a zero right and we can't go any further in our breadth first search we terminate so I know we've been doing a lot of medium problems lately but uh and this is an easy problem but it's pretty relevant to um solving you know grid style breadth first or depth first uh problems and it's really similar to the uh count number of islands so we're gonna do it uh like I said we're gonna do breath first so we are going to import our DQ from collections okay let's set that up we'll make it equal to Q is equal to DQ and on this Q we they give us a starting position already so we're going to put Sr and S C on our Q s r s c let's also grab the uh pixel color that they give us that will be equal to image of Sr SC we're also going to have a visited set okay now all we have to do is run breadth first search on this so we'll say while the length of our Q is not equal to zero what do we have to do we will grab the row and the column with Q dot pop left okay now what now we need to check and make sure that the row column pair that we just grabbed is not in our visited set so we'll say if row column not in our visited set what do we want to check and make sure that the previous row the next row the previous column and the next column are also within this grid so if we're given um this pixel right here we want to make sure that the next row and then in the same column is still a valid value within our grid so if we want two rows down we're outside of the grid we don't have a valid value and we need to check this for both the row and column so we will say if our row is greater than or equal to zero and less than the length of our image and our column is greater than or equal to zero and less than the length of our image of the first row what are we going to do we are going to first of all add that row column pair to our visited set so add a row column we are also going to add the next row previous row next column previous column to our queue so Q dot append the next row of the current column q.append the column q.append the column q.append the previous row of the current column and Q dot append the current Row in the next column and finally q.append the current column and finally q.append the current column and finally q.append the current row of the previous column now before we end this we also have to after we add this real column pair to our visited set we want to change the given starting pixel to the color that they give us so we will say image of row column is now going to be equal to the color that they give us all right now we can just return the image we should have performed a breadth first search and changed all of the connected pixels to their correct color so let's run this we get one wrong test case so what did I do this should be this is bright this is where aha we also need to check because we don't want to run breath first on every single Pixel right this is a one we don't want to run it on zero we only want to run it on the ones so we have to say and the image at our row column is equal to our starting pixel column value right now if we run this we should get the right answer yep and we passed both test cases so we'll submit perfect okay time and space complexity time complexity is going to be o of n we are going to have to Traverse an N number of pixels and our space complexity is going to be o of n where our Q can grow to the uh a length of however many pixels we have traversed all right that'll do it for Lee code 733
Flood Fill
flood-fill
An image is represented by an `m x n` integer grid `image` where `image[i][j]` represents the pixel value of the image. You are also given three integers `sr`, `sc`, and `color`. You should perform a **flood fill** on the image starting from the pixel `image[sr][sc]`. To perform a **flood fill**, consider the starting pixel, plus any pixels connected **4-directionally** to the starting pixel of the same color as the starting pixel, plus any pixels connected **4-directionally** to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with `color`. Return _the modified image after performing the flood fill_. **Example 1:** **Input:** image = \[\[1,1,1\],\[1,1,0\],\[1,0,1\]\], sr = 1, sc = 1, color = 2 **Output:** \[\[2,2,2\],\[2,2,0\],\[2,0,1\]\] **Explanation:** From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color. Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel. **Example 2:** **Input:** image = \[\[0,0,0\],\[0,0,0\]\], sr = 0, sc = 0, color = 0 **Output:** \[\[0,0,0\],\[0,0,0\]\] **Explanation:** The starting pixel is already colored 0, so no changes are made to the image. **Constraints:** * `m == image.length` * `n == image[i].length` * `1 <= m, n <= 50` * `0 <= image[i][j], color < 216` * `0 <= sr < m` * `0 <= sc < n`
Write a recursive function that paints the pixel if it's the correct color, then recurses on neighboring pixels.
Array,Depth-First Search,Breadth-First Search,Matrix
Easy
463
1,886
Everyone Month Sandeep &amp; Everyone Month Sandeep &amp; Everyone Month Sandeep &amp; David Problem 186 6 Install Amaze &amp; David Problem 186 6 Install Amaze &amp; David Problem 186 6 Install Amaze &amp; Size &amp; Craft &amp; Quote - RCM Size &amp; Craft &amp; Quote - RCM Size &amp; Craft &amp; Quote - RCM 's Birthday Sakait But That Unwanted's 's Birthday Sakait But That Unwanted's 's Birthday Sakait But That Unwanted's Post Matric 123 Number Times For Example Against Hair Only 10 Richest Gram Protein Test Match Point Delivery 800 Which is the Target 101 Time to Time To Kya Hua The President Se Zara Skit to Western Wear First Bank PNB Rotator Matrix How Many Times Rotted and So it Voted for Times Will Get Value 360 ​​Degrees Times Will Get Value 360 ​​Degrees Times Will Get Value 360 ​​Degrees Latest Afforestation Set Welcome to the Original State So Wick And Ment For Times Next How To Draw The Matrix In The Morning At That Time Tricks For Particular Classes Column Directly Handed Over To Subscribe Very Exchange Na Directly Example Of But Not With Hydrogen Is Possible But Se Subscribe Element Subscribe And Share And Subscribe To 200 Start From The Last Subscribe And Tourism When Last Column Day Immediately Phase Column Start District Start With Roasted Sesame But Feel It On Flame For A Few Seconds Time When So Let's Come Together They Can Simply Say Vighn-Vighn The 0 But Last - - - Vighn-Vighn The 0 But Last - - - Vighn-Vighn The 0 But Last - - - - Subscribe 065 Subscribe to my channel and subscribe the effigy of record 10 auspicious record a slow sex yes yaar ki pake softventures special vighna adheshan to abhi cancer lung course not know what to bihar today's topic a lot tomato asim i am late from you metrics and save target s this very hand less than 10th sample vitamin through from a girl and boy went to give some important tomato its quite a function i have o message hai itna thick very after protests in the simplest form last date previous song mithun 122 Function From Samsung Note And Every Native May Not Get First Partnership I Here 188 Test Cricket Association Ne Soch Post Matric Number Approach Net Pack No Number Of Problem A Fan Ki Noida Shaadi Number One Column Shubh Soviet Swift Hum Rose End Columns Ghat Par Ki Naukri Channel Value on do aphoto so if this is on us is well but ever find a way to rate restaurant also of J&amp;K rate restaurant also of J&amp;K rate restaurant also of J&amp;K previous stroke and minus one which Amethi ne I India before Britain and Belgium in Bihar on I am rich they sample check This To Matters Not Half Let's Celebrate Control Editing Course Financials Minute Checkpost This Number Of Roses Very The Fallen In The Matters Same Day Taste In This 123 And Today I Have Told A Number Of Columns Ko Janam Hai Or Frozen Follow 10 Days Special Introduction Hai Ya Sunao Introduction Payas Loot 101 To Balance Don't Make Them In The Form Of Matrix White Net Is Not Equal To My Target Of IT And Judge Me Sampann Return And Post 116 Samay Distic Looters Ne School The Sets Share Maa Saraswati Ki Kapil S that this photo browser is near the hospital sample page so what happened that xxx 1080
Determine Whether Matrix Can Be Obtained By Rotation
minimum-limit-of-balls-in-a-bag
Given two `n x n` binary matrices `mat` and `target`, return `true` _if it is possible to make_ `mat` _equal to_ `target` _by **rotating**_ `mat` _in **90-degree increments**, or_ `false` _otherwise._ **Example 1:** **Input:** mat = \[\[0,1\],\[1,0\]\], target = \[\[1,0\],\[0,1\]\] **Output:** true **Explanation:** We can rotate mat 90 degrees clockwise to make mat equal target. **Example 2:** **Input:** mat = \[\[0,1\],\[1,1\]\], target = \[\[1,0\],\[0,1\]\] **Output:** false **Explanation:** It is impossible to make mat equal to target by rotating mat. **Example 3:** **Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1,1\]\], target = \[\[1,1,1\],\[0,1,0\],\[0,0,0\]\] **Output:** true **Explanation:** We can rotate mat 90 degrees clockwise two times to make mat equal target. **Constraints:** * `n == mat.length == target.length` * `n == mat[i].length == target[i].length` * `1 <= n <= 10` * `mat[i][j]` and `target[i][j]` are either `0` or `1`.
Let's change the question if we know the maximum size of a bag what is the minimum number of bags you can make note that as the maximum size increases the minimum number of bags decreases so we can binary search the maximum size
Array,Binary Search
Medium
1335,2188
141
hey guys Greg here let's solve link list cycle leak code number 141 it's claimed to be an easy but there's actually some tricky components to it and we're going to learn a really useful algorithm now we're given head the head of a linked list as usual and we want to determine if that linked list has a cycle in it now we don't really need to read this it's pretty visual so if we are going through the list and then we actually never stop going through the list well then we have a cycle so there's really no completion to this because it keeps wrapping around every time we get to the -4 so in other words it basically -4 so in other words it basically -4 so in other words it basically happens because we're traversing and then we actually have a next pointer so this next pointer is actually pointing to a node that we've already seen before and that's going to give you a clue into our first solution okay so suppose we had this list here and you can see there's no Cycles in it if we were just to Traverse this we'd Point C or CER equal to the head and we would just kind of go through by setting C to be c. next we could go through while cerr is a valid node and if we got out of bounds or when it equals none well then we're out of bounds and so clearly there wasn't a cycle but say that there actually was a cycle and so we'll point for say over to two here so now we're in the circumstance where if we were to do this if we were to send CER through just setting it to c. next well this is actually going to go on infinitely okay so yes you could return false if we get to the point where Cur is none but otherwise how do we actually detect this cycle cuz this is an infinite Loop now if you ever want to detect duplicates then you could use something like a set or a hash map anything that uses hashing so we'll just use a hash set so in here we'll just store node references to the nodes we've seen and you want references not values you don't want these to be integers because if you were in the case where actually these had two different values here well this is not an issue here okay this part right here does not imply a cycle because these are two different nodes they have the same value but they are two different nodes so we don't want to put you know integers over here we actually want to put node references and it's really easy to do that in code even C here you could actually just put C into the set and that would use the memory address that would work just fine for the visualization it's a little bit harder so I'm actually going to write the number which is going to indicate which one of these it is but know that I'm actually not putting integers here I'm actually putting references to the node itself and you can do that you can hash on memory addresses because a memory address is immutable which is the definition for hashing in most cases okay so we just put this node into the set here and then we will move forward by setting C to bc. next C is just short for CER so we see two so we're going to put that into the set we haven't seen any duplicates yet here we go over to three we'll put in three and this is going to plug in four here and at this point we actually Traverse over back to here and so before we put stuff into the set we're going to ask if it's already in the set and so it is already in the set okay this node reference here that is already in the set and that is when we would return false here okay and imagine we didn't have some cycle so we'd actually get out here and so C would be none at some point and that's a case where we could actually return true okay now the only problem with this solution is that this has o of n space here okay we're using a hash set to store these n values so the time is O of n we're not going to be able to do any better than that there's an algorithm called Floyd cycle finding algorithm there's a couple names for this algorithm it could be called like slow and fast pointers could be called Uh there's this guy named Floyd that came up with it so Floyd cycle fighing algorithm tortoise and hair because you know hairs are faster than tortoises kind of like a slow pointer is you know slower than a fast pointer let's see how to do this and it's going to end up being constant space okay so for this example it's actually not quite necessary but I find it's useful to start off with a dummy node so this is just creating a new node the value of it doesn't really matter and we're going to set that dummy. next to equal the actual head okay so that way we can set up our two pointers we'll call them s for slow and F for fast so those are both going to point over to the dummy and the fast pointer is going to move two steps every time the slow pointer moves One Step so the fast pointer moves twice as fast as slow so say that we were to move slow once immediately after we'd move fast over twice and then we move over once we move fast over twice well F can't move twice here it actually can't even move once and so we can detect that right here and since fast can't move anymore well that means that we actually found an end to the list and therefore there wasn't a cycle because if there was a cycle well then you would have been trapped in that the whole time and so there must not have been a cycle we were about to escape and so since it was trying to go out of bounds this is actually a scenario where we'd return false because there wasn't a cycle okay but again say that we were in the scenario where there actually was a cycle so maybe four was pointing over to two so if we were to do this again we'll Point slow and fast over to the dummy and then we're going to move slow over once fast is going to go over twice slow goes over once fast goes over twice look at what happened here they actually started pointing at the same node so they are pointing to the same node reference here now what's super crazy and I feel very counterintuitive is that if there is a cycle in the linked list then it's actually guaranteed that if you run this algorithm where we have two pointers run at a different pace at some point they are actually going to equal the same node they might not equal necessarily this node but they're going to equal some node that is you know part of that cycle okay so I don't really want to talk about why that's true but just know that this algorithm actually does work and there's a theorem behind it okay so let's write our code we're going to set a dummy node equal to a new list node we really don't care about its value we're just going to specify that dummy. next is equal to the head so that connects them up now we're going to set both slow and fast F pointing equal to the dummy so that basically says you know fast is going to point to dummy and slow is going to point to fast but that means they're pointing to the same thing while we have fast and we have fast. next why because we're going to set fast equal to fast. next so this code here is assuming that fast. next actually exists it has to be a node because if this wasn't a node well something like null or none that's not going to have a next so each time this runs we're making sure fast isn't node and we're making sure fast. next is a node so that we can move fast over twice okay and so every time fast moves over once slow is going to move over once and if you are ever running into the case where slow is fast so if their memory addresses are the same they're pointing to the same node so that means there must have been a cycle by Floyd's awesome algorithm here we return true in that case and then otherwise if you actually escape this Loop well that means that this expired and so at some point you basically got through the list and if you got through the list there must not have been a cycle so we can just return false there now the time and space here is not super intuitive because if there is a cycle we don't really know how long it's going to take fast and slow to equal each other we know they will equal each other but it turns out that the time complexity they are going to find it in you know Big O of n time it's not going to take that long for them to find each other and the space complexity of this algorithm this actually doesn't take any space it holds just you know a dumb is a new node that's fine and two pointers that's really all it is so that's going to be constant space that's why it's better than the hashmap solution cuz the hash map solution or the sorry the hash set solution that would be Big O of n in this solution we get rid of the space I hope this was helpful guys drop a like if it was and have a great day bye-bye
Linked List Cycle
linked-list-cycle
Given `head`, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**. Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** false **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Easy
142,202
724
in this video we're going to look at a legal problem called find pivot index so given an array of integer nums write a method that returns the pivot index of the array so we define the pivot index as the index where the sum of all numbers on the left of the index is equal to the sum of all numbers to the right of the index so if there no such index exists we're going to return negative 1. if there are multiple pivot index we just return the leftmost pivot next so here you can see we have a um an array and basically what we're trying to do here is we're trying to return the pivot index in this case it's going to be index 3 because here everything on the left is actually equal to everything on the right so 1 plus 7 plus 3 is 11 and 5 plus 6 is 11 so in this case 11 is equal to 11 so we have the pivot index so yeah basically here you can see you have we have another example where there's no index that's satisfied then we're going to do is we're just going to return negative 1 if there is no index that satisfy the condition so how can we do this well what we can do with naive solution is that for each element in the array we're just going to let's say we have we want to find um index one is the actual the valid uh the valid pivot point right so we're gonna do is we're just going to iterate all the elements on the left and all the elements on the right to see if they're equal to each other right so we're going to get the sum of the right sub array and the sum of the left sub array to see if they are the same in this case they're not the same so we're just going to continue to move to the next index in this case index 2. we iterate all the elements we basically get the sum of all the elements on the left all the elements on the right to constantly um getting the sum and comparing the left sum and the right sum and then at the end we're just going to return the index that has a valid condition so in this case this will give us a n squared time complexity where n is the number of elements in the array so it's not the most optimal solution but what we can do instead is we can use a linear time complexity where we're going to basically simply first of all get the sum of the whole array right the entire array uh the sum of the entire array i believe was 28. so what we're going to do then is we're just going to see by standing at the current index let's say index zero the sum on the left is zero because there is no elements on the left the sum on the right is simply by 28 minus the current element so 28 minus one will give us the sum on the right so this is a 27. so if that's the case then we're going to do is we're just going to continue to see to compare the left sum and the right sum right by simply minus the current element um of the uh of the total sum right so minus so total minus the current element uh will give us the uh the right sum in this case now we have 27 for the sum of here right so we're gonna do is we're going to take index one right index one now we know that in the left index the sum right is one the right here is going to be 27 minus 7. this will give us 20 okay this is the sum of total on the right so 3 plus 5 is 8 a plus 12 is 20 right so in this case we have 20 on the right so by simply just minus 27 uh by simply using 27 to minus the current element will give us the sum of the right side which is 20. so this way we can be able to bring time complexity down to a big o of n where n is the number of elements in the array so now let's try to do this in code so we're going to do first is we're basically going to first get a sum so for each element in nums we're basically going to say sum plus equal to num once we get the sum of the entire array what we're going to do is we're going to start by simply have a variable called left sum right left sum zero the right sum is equal to sum gonna use a for loop to iterate so we're gonna do is we're going to get the current element by simply minus that on the right zone and then plus that on the left sum after we compare so this is how we're going to do first we're going to get the right sum minus equal to the current element so nones at i first minus the current elements so that we have the right sum and then what we're going to do is we're going to compare that so we're going to see if the left sum is equal to the right sum so if that's the case then what we can do is we can just return the current index if that's the case right then what we're going to do is we're going to move on to the next iteration uh move on to the next element to check to see if that's the current uh if that's the pivot index i simply just move on to the next iteration but what we have to do is we have to get a left sum plus the current element because we're moving on to the next element right so in this case if we were to move from index 0 to index 1 we have to get the left sum plus 1 okay because the right sum is already minus the current element already so we just have to get left sum plus equal to num zi okay so we're going to do is we're just going to continue to do that until we get to the end of the array if nothing happens we're just gonna return negative one okay let's try to see if we have a valid answer okay let's try to submit so there you have it and um this is basically how we bring the time complexity down to linear and the space complexity in this case is going to be constant okay so thank you for watching
Find Pivot Index
find-pivot-index
Given an array of integers `nums`, calculate the **pivot index** of this array. The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right. If the index is on the left edge of the array, then the left sum is `0` because there are no elements to the left. This also applies to the right edge of the array. Return _the **leftmost pivot index**_. If no such index exists, return `-1`. **Example 1:** **Input:** nums = \[1,7,3,6,5,6\] **Output:** 3 **Explanation:** The pivot index is 3. Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11 Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11 **Example 2:** **Input:** nums = \[1,2,3\] **Output:** -1 **Explanation:** There is no index that satisfies the conditions in the problem statement. **Example 3:** **Input:** nums = \[2,1,-1\] **Output:** 0 **Explanation:** The pivot index is 0. Left sum = 0 (no elements to the left of index 0) Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0 **Constraints:** * `1 <= nums.length <= 104` * `-1000 <= nums[i] <= 1000` **Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/)
We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1]. Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i].
Array,Prefix Sum
Easy
560,2102,2369
36
hello everyone let's look at valley sudoku if you have ever played stuku before this question would be an interesting one let's look at the problem statement we need to determine if a 9 multiply 9 stucco board is valid and we only validate those that has been filled there are a couple of rules we need to follow first each row must contain the digits 1 to 9 with a repetition second each column must contain the digits one to nine without reputation third each of the nine three multiply three sub boxes of grid must contain the digits one to nine with a reputation and this board is solvable or not we don't care we just check if all the field cells comply with those three rules let's look at a few examples for the first one not much to say that's a valid board for the second one because this first column we have 2 8 so it is invalid let's have a look how we can solve this problem i guess we absolutely need to have two for loops and then we can visit individual i and j so for this individual element we simply need to validate and see if this element has violated the rule for this specific column specific row and specific box and we know the row index is i column index is j what is the box index i would propose the box id like this so the top left area will be zero and bottom right will be eight zero one two three four five six seven eight and now we have the road index column index and box index we can then use a map to save them so in our case let's roll map box map column map and then we can save the value into the map when we see a value and the key will be the index and value the value will be a boolean true let me type it out you will understand really clear so we can do like this and next time when we see a value we just check if this key already exists in our map if any of these three are true then we simply return false otherwise we push the value into this corresponding map another thing we need to do before we do all this is to make sure the value is not a dot so this should be our whole solution we have this row column box we have three different maps to save all the necessary data and each time we see a value and its index we push it in and the value will be true the key will be the index and the value and then next time when we loop through into other values when we see the same value and same index then we simply return first and all the way in the end we can return true let's try to sum it yeah i'm sorry we have this uh typo here this should be j let's do it again this time it passed let's look at the complexity i guess in our case everything is constant both space and time is constant because the size of this board is constant so this input size will not change so everything is constant and if you have any other questions please leave a comment below thank you for watching
Valid Sudoku
valid-sudoku
Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**: 1. Each row must contain the digits `1-9` without repetition. 2. Each column must contain the digits `1-9` without repetition. 3. Each of the nine `3 x 3` sub-boxes of the grid must contain the digits `1-9` without repetition. **Note:** * A Sudoku board (partially filled) could be valid but is not necessarily solvable. * Only the filled cells need to be validated according to the mentioned rules. **Example 1:** **Input:** board = \[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\] ,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\] ,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\] ,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\] ,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\] ,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\] ,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\] ,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\] ,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** true **Example 2:** **Input:** board = \[\[ "8 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\] ,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\] ,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\] ,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\] ,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\] ,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\] ,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\] ,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\] ,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** false **Explanation:** Same as Example 1, except with the **5** in the top left corner being modified to **8**. Since there are two 8's in the top left 3x3 sub-box, it is invalid. **Constraints:** * `board.length == 9` * `board[i].length == 9` * `board[i][j]` is a digit `1-9` or `'.'`.
null
Array,Hash Table,Matrix
Medium
37,2254
1,991
hey everybody this is larry this is me going with q1 of the bi-weekly me going with q1 of the bi-weekly me going with q1 of the bi-weekly contest 60 find the middle index in the way so this one it's kind of brute force um let's see n is a hundred right so you could do this in a number of ways and it'll be good um but the way that i actually do it even though i normally don't do this and it maybe ate into some time because i spent two minutes on this instead is that i did a linear time algorithm um okay that's awkward right um yeah and basically the idea i have is that um you can think about it as a prefix sum um and then total is the sum of all the numbers and then this is the prefix sum where basically we look at the sum of the first indexes um including the index i wrote this in a little bit you know this is contest coded is a little bit awkward but basically this is all the numbers that are left of this index and then this is all the numbers to the right because it is um it's basically the total minus that we bring to the left right so that's basically the idea and if they match we get the first index that it happens for and then we return negative one otherwise this is linear time you know it's not necessary you could do an n square algorithm very quickly um but yeah um and maybe i should have i didn't i actually didn't look at the constraints because i knew the linear time algorithm pretty quickly but you know i had enough not off by one i just wasn't super sure but yeah um that's all i have for this one let me know what you think let me know if this formula makes sense because you just basically look at um but current basically just gets to total of the first um x numbers right so that's basically the idea we have to subtract it because we don't want to count it that oh i spent some time there because i actually didn't read the volume too carefully because i doubt that you have to include this number as well but actually you don't include this number which is why i you know i had to go back up and read it and you could see me do this live during the contest next oh i think i'm today yeah well oh press the button he ascends speed okay let's go bam yes the total of oh indexed this is very awkward though well that's not good oh wait that's not right oh not including this index okay then i'm off by one somewhere yes yeah thanks for watching hit the like button hit the button join me on discord especially if you like talking or seeing about these contest farms in a more real time i'll see you later stay good stay healthy take good mental health uh yeah have good problem solving bye
Find the Middle Index in Array
league-statistics
Given a **0-indexed** integer array `nums`, find the **leftmost** `middleIndex` (i.e., the smallest amongst all the possible ones). A `middleIndex` is an index where `nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]`. If `middleIndex == 0`, the left side sum is considered to be `0`. Similarly, if `middleIndex == nums.length - 1`, the right side sum is considered to be `0`. Return _the **leftmost**_ `middleIndex` _that satisfies the condition, or_ `-1` _if there is no such index_. **Example 1:** **Input:** nums = \[2,3,-1,8,4\] **Output:** 3 **Explanation:** The sum of the numbers before index 3 is: 2 + 3 + -1 = 4 The sum of the numbers after index 3 is: 4 = 4 **Example 2:** **Input:** nums = \[1,-1,4\] **Output:** 2 **Explanation:** The sum of the numbers before index 2 is: 1 + -1 = 0 The sum of the numbers after index 2 is: 0 **Example 3:** **Input:** nums = \[2,5\] **Output:** -1 **Explanation:** There is no valid middleIndex. **Constraints:** * `1 <= nums.length <= 100` * `-1000 <= nums[i] <= 1000` **Note:** This question is the same as 724: [https://leetcode.com/problems/find-pivot-index/](https://leetcode.com/problems/find-pivot-index/)
null
Database
Medium
null
696
hey what's up guys uh this is chung here so today uh let's take a look at today's daily challenge problem number 696 count binary substrings know even though this one is marked as a easy problem i still like to briefly talk about this problem because it's not like very traditional easy problem it's still requires you requires a little bit of observations you know so basically you basically are given like a string as right and your task is to count the number of non empty contiguous substrings that have the same number of zeros and ones right and all the zeros and ones uh in the substring are grouped consecutively and substrings that occur multiple times are counted the number of times they occurred so what does it mean for example we have this one we have zero one right so the answer is six so why do we have six we have this is one right this is a one substring because both zero and one there are one and this is the second one right zero so from this substring both the count r2 right and same thing for this for the one zero this is all also another one this is also another one right and same thing for this one this is another one that's why we have six in total so and the constraints is like uh 50 000 right i mean a brutal force way is what we simply just try to me enumerate all the substrings right and for each substrings we're gonna count there count the zero and the ones right and then we check each of the string but obviously with this kind of uh constraints here right so that the brutal force one was definitely tle so which means that we need to find the like better solution right but how can we do it how can we find that uh a pattern so that we can reduce the time complexity um so at the beginning i was thinking about uh this one seems like a stack maybe we can try to use the stack so basically every time uh we see if the current character or current number is it different as the ones on the top and then we know okay we find the pair right we find a pair and then the and then we'll just pop that one out right so when but did but then that's um then zero one works right but here we have another zero this these two zeros also need to be paired with this these two ones if we use stack you know these two ones will not be in the stack regardless right and so which means that we have to find we have to uh change that logic a little bit basically you know every time when we have like a different one right we have a different one we uh we can still use the stack basically you know if they're the same right we're just pushing push it into the stack and when they're the different you know will basically pop that thing pop that's uh the number from the stack but that will also cause another problem because you know for this one zero there they're fine they're okay but if we have this kind of three zeros at the beginning right and then we basically push three zeros in the stack and then we have two ones and then we pop two zeros out and then we still have one zeros left in the stack so basically you know what i'm trying to say is that you know stack may not be a proper uh data structure to use here instead you know what we can do is that we can see as you guys can see so every time you know as since we need to find the pairs right i mean it's not pairs the groups that have identical have the same concern once it means that you know it has to be either zero one or one zero right it cannot it we don't need to worry about this scenario you know it has to be a zero on the left or one on the right or what or the other way around we there's no point to consider this one you know because this one is separate right basically right this one is also a valid one right but you know this is because you know we have a this condition here you know all ones and zeros all zeros and ones are grouped consecutively which means that this zero one does not consider as a valid answer if we look at uh example two here you know we have one zero one you know so there are four substrings one zero and zero one right so this one zero does not count as a valid one because the ones and zeros they're not grouped consecutively they are separate they're the split uh they're split by each other right by adding a zero in between that's why you know we don't need to work consider this scenario so we can simply just use like a count right i mean in this case let's say we have three zeros in the end at the beginning so in this case all we need all we care is that like the current consecutive count right for the current numbers you know in this case you know at the beginning we have three zeros right we have three zeros and then now and then we have two ones right and then we have two ones so what does this one mean it means that you know previously we have three uh zeros either zero or one it doesn't really matter but now we have a another two different numbers so between three and two we have what we have two pairs right that's why the answers can be two at the beginning right and then we simply discard this one because we know so now the left side becomes a 2 now we simply need to count the new right side which is this two here right it's another two here so now this one minimum between two and two is also two right so that's why we have another two here and then we just got we discard this one now the left side is also two right now we simply check this side it's also two that's why that's how we get the total six so we simply just uh we keep we maintain like previously previous count right and then for the current one we count the current one until the next one is different and then we keep comparing the minimum between those the previous column and the current count that's going to be the uh that's going to be the new pairs we find cool so let's start coding then so the answer is going to be zero right that we have a pre count equals to zero right and then i'm going to have like a n actually there's an n equals the length of s so while i smaller than n right um so the current count right the current count will be starting from one because this uh one ladders uh stands for one right and then we i just move this current cursor forward until the next one is different right and s i is equal to the s i plus one right if that's the case we think we increase the current count right by one so the this current count can stand uh constant for either zero or one doesn't really matter right because we know as long as the pre because we know the previous column and the current count there are two different numbers and we increase i by one right and i simply check if the pre-count is greater simply check if the pre-count is greater simply check if the pre-count is greater than zero right because we can we need to check this because you know because at the beginning you know once we count this part you know there's no uh counterpart to be able to uh so to form like a string that's why we do a pre-con pre-con pre-con because at the beginning the pre-column because at the beginning the pre-column because at the beginning the pre-column is equal to zero so if the pre-count is greater than zero so if the pre-count is greater than zero so if the pre-count is greater than zero it means that you know we have a pair so how many pairs we have here or how many substrings it's going to be the minimum of the pre-count the minimum of the pre-count the minimum of the pre-count and the current count right and after this one we update the pre-con and after this one we update the pre-con and after this one we update the pre-con with the current count right and then don't forget to increase the cursor by one right and then we return the answer yep so if i run code i forgot to define i here okay some typo here current count yeah cut count okay all right so submit cool so pass right i mean so this one the time complexity for this one obviously is o of n right because we only traverse the string once and then we use like the uh we only use this one variables uh defined like pre-count to variables uh defined like pre-count to variables uh defined like pre-count to track the previously previous the column for the previous number so that's why you know the time complex is this one and space complexity is o of one right yeah i think that's it i mean even though it's easy problem but you know the pattern it seems a little bit seems interesting you know i hope you guys like uh enjoy watching this video and yeah that's it and yeah thank you guys and i'll see you soon bye
Count Binary Substrings
count-binary-substrings
Given a binary string `s`, return the number of non-empty substrings that have the same number of `0`'s and `1`'s, and all the `0`'s and all the `1`'s in these substrings are grouped consecutively. Substrings that occur multiple times are counted the number of times they occur. **Example 1:** **Input:** s = "00110011 " **Output:** 6 **Explanation:** There are 6 substrings that have equal number of consecutive 1's and 0's: "0011 ", "01 ", "1100 ", "10 ", "0011 ", and "01 ". Notice that some of these substrings repeat and are counted the number of times they occur. Also, "00110011 " is not a valid substring because all the 0's (and 1's) are not grouped together. **Example 2:** **Input:** s = "10101 " **Output:** 4 **Explanation:** There are 4 substrings: "10 ", "01 ", "10 ", "01 " that have equal number of consecutive 1's and 0's. **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'0'` or `'1'`.
How many valid binary substrings exist in "000111", and how many in "11100"? What about "00011100"?
Two Pointers,String
Easy
271
16
this is the 16th leeco Challenge and it is called threesome closest given an integer array Norms of length n and an integer Target find three integers in nums such that the sum is closest to Target return the sum of the three integers you may assume that each input would have exactly one solution so if you're given the numbers of negative one two one negative four and a target of one the output is two as the sum of negative one plus two plus negative one equals two okay and if you're given all zeros I guess anything can do is returned all zeros nums length is a minimum of three and a maximum of five hundred the numbers within the array are a minimum of negative one thousand to positive one thousand and the target is anywhere from what is that negative ten thousand to positive ten thousand so let's get started okay so I've now got the project set up so for this class I just copied and pasted the previous challenge which was threesome and I've modified it so it works with three some closers so we've got inputs targets and expected outputs and we just go through each list and we run it so three some closes we put an input and a Target and when it runs we should get the actual output and hopefully that matches the expected output so if I go back to the top I've still got all the code from the previous challenge threesome so I guess let's get started and trying to go through it so what we're doing we have list of numbers and we're trying to add three of them together so they are closest to the Target so I guess first thing we can do is actually I forgot to change this needs to return back to Bing which I haven't even looked here what's the end targets okay so returns an INT which is expected so I've got int and we'll set this as n32.max we'll set this as n32.max we'll set this as n32.max just so we can say it's as far as possible from the target so what I did before in the previous one was I sorted it I don't think sorting it is actually no it will keep it as sorted yeah we'll do that iterating through the list this is the first number if I is greater than one and no we don't need this check anymore okay so we're iterating through all the numbers in the first list we start off at index zero and the first number will go up to the second last number so in low that is the one above the current number looking at and the entire is the last number so while low is lower than higher we are summing the numbers together because in this case if sum equals zero which is not what we're trying to do in this one we can just add sum equals Target return Target okay I think I need to just go through and remove the stuff that's not needed so this will exist for here if yeah so none of this is needed anymore yeah we don't need the list of numbers that it is okay I remember how this works now so if it equals Target we just return as that's closest that we'll get some if type if it's less than Target we increase the low else higher well I don't need to do that so you have the output there so you have the output way right through the numbers we have a higher low while low is great and higher so they meet in the middle um we sum the numbers together if it's a Target then we know what the output is let me do that else we increase the low or we reduce the height if sum is lower but we also need to do a check what how would we do this so we want to see if the current output if the current sum is closer to the Target than the current output then we assign the new output if output is null or okay right can't do anything for that okay we will have to assign here so if Target is greater than zero order int Min value or int max value why not this colon so we have to have a value assigned and we want it to be as far away from the target as possible you hope that works so if so we need to figure out the difference I guess we'll just do an initial one where it's if output equals into max value or output equals int Min value we'll just do output equals sum else if trying to figure out the math that needs to be done so you have the target we have the current output and the current sum and the way we do this math depends on whether it's positive or negative all right we'll also do a bull Target positive equals Target greater than do great or equal to zero so Target positive so if Target positive so we'll just quickly change this put continue there and put this statement here so the target is positive and then we need to see if in current difference then int sum difference if actually we should just put this at the very top int current if it's no point of calculating this every time we do it and we'll create a quick function here so if Target is greater than zero and current is greater than zero in difference equals Target minus current if current is greater than zero outs okay I realize I'm making this much more difficult than it needs to be because there's math function which does this ever and I've done this before we'll just do return math dots ABS current like that we will change this here don't need this uh we'll keep that so int sum actually we'll remove it just so we don't have to worry about that so int current difference equals Target output int sum difference equals number difference Target sum if some difference is less than current difference then output equals sum I think that's all that needs to be done so let's run it and see if it works okay so your return expected output two actually I could put two expected up at zero actually I'll put zero so that seems hopeful let's copy this code and put it into leak code then we can see if it works as expected let's run it with the test first just to make sure that is all working I have forgot to include number difference there so we'll copy that in run that and that worked but those are the same test case I assume yep okay now let's submit and see if it works and that did work and it beat 90 of other answers in terms of performance so that was challenge 16 of link code and C sharp three sum closest if you like this video make sure to like And subscribe
3Sum Closest
3sum-closest
Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`. Return _the sum of the three integers_. You may assume that each input would have exactly one solution. **Example 1:** **Input:** nums = \[-1,2,1,-4\], target = 1 **Output:** 2 **Explanation:** The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). **Example 2:** **Input:** nums = \[0,0,0\], target = 1 **Output:** 0 **Explanation:** The sum that is closest to the target is 0. (0 + 0 + 0 = 0). **Constraints:** * `3 <= nums.length <= 500` * `-1000 <= nums[i] <= 1000` * `-104 <= target <= 104`
null
Array,Two Pointers,Sorting
Medium
15,259
8
here we have a list of strings that I want to turn into integers the way that we could do that is with list comprehension I'm going to save this into a variable called numb list and then I'm going to say with list comprehension int and that's going to be the for the string number in the string list before we run this I also want to check that we can actually convert it the way that we'll do that is with an IF function and we'll say that if the string num and we're going to call the is numeric function and set that equal to True let's run this and check out our list and we can see that we converted them to integers thanks everyone for watching and happy coding
String to Integer (atoi)
string-to-integer-atoi
Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer (similar to C/C++'s `atoi` function). The algorithm for `myAtoi(string s)` is as follows: 1. Read in and ignore any leading whitespace. 2. Check if the next character (if not already at the end of the string) is `'-'` or `'+'`. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present. 3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored. 4. Convert these digits into an integer (i.e. `"123 " -> 123`, `"0032 " -> 32`). If no digits were read, then the integer is `0`. Change the sign as necessary (from step 2). 5. If the integer is out of the 32-bit signed integer range `[-231, 231 - 1]`, then clamp the integer so that it remains in the range. Specifically, integers less than `-231` should be clamped to `-231`, and integers greater than `231 - 1` should be clamped to `231 - 1`. 6. Return the integer as the final result. **Note:** * Only the space character `' '` is considered a whitespace character. * **Do not ignore** any characters other than the leading whitespace or the rest of the string after the digits. **Example 1:** **Input:** s = "42 " **Output:** 42 **Explanation:** The underlined characters are what is read in, the caret is the current reader position. Step 1: "42 " (no characters read because there is no leading whitespace) ^ Step 2: "42 " (no characters read because there is neither a '-' nor '+') ^ Step 3: "42 " ( "42 " is read in) ^ The parsed integer is 42. Since 42 is in the range \[-231, 231 - 1\], the final result is 42. **Example 2:** **Input:** s = " -42 " **Output:** -42 **Explanation:** Step 1: " \-42 " (leading whitespace is read and ignored) ^ Step 2: " \-42 " ('-' is read, so the result should be negative) ^ Step 3: " -42 " ( "42 " is read in) ^ The parsed integer is -42. Since -42 is in the range \[-231, 231 - 1\], the final result is -42. **Example 3:** **Input:** s = "4193 with words " **Output:** 4193 **Explanation:** Step 1: "4193 with words " (no characters read because there is no leading whitespace) ^ Step 2: "4193 with words " (no characters read because there is neither a '-' nor '+') ^ Step 3: "4193 with words " ( "4193 " is read in; reading stops because the next character is a non-digit) ^ The parsed integer is 4193. Since 4193 is in the range \[-231, 231 - 1\], the final result is 4193. **Constraints:** * `0 <= s.length <= 200` * `s` consists of English letters (lower-case and upper-case), digits (`0-9`), `' '`, `'+'`, `'-'`, and `'.'`.
null
String
Medium
7,65,2168
1,095
Hi Everyone, today's our lead code daily challenge is Find in Mountain Array, this is a hard level question and it is an interact problem, so what does interact problem mean, whatever our test cases will be in it is already there. It will not be determined. When we run the program, different test cases will be checked. Okay, and now what happens is that we first need to know what a mountain array is. Okay, so what is the definition of a mountain array? It is given that the length of that array should be at least greater than and equal to two. It means that the length of our array should be three or more than that. After that it has been said that the array in it is true. That there assist I with zero of I less than the array of length minus I true that the array is either in our ascending order or if one we come to such a point okay that means we will call it we will assume peak index okay So after that peak index, what will all the numbers become in decreasing order? This means that if there is two, then we assume that if there is two, then it will increase till one instant and After that, when it will reach the maximum index i.e. peak index, it will reach the maximum index i.e. peak index, it will reach the maximum index i.e. peak index, after that it will start decreasing, okay, then such an array will be called our mountain array, now what is given to us in the mountain array, not that we have to search the value, we will be given a target value, okay If the target value is given then we have to return its minimum index. Suppose if we have target here then we have to return the first value of two and if we are not getting the target then we return -1. We will do it, getting the target then we return -1. We will do it, getting the target then we return -1. We will do it, okay, and in this we have been given a condition that whatever we access, what we use, normally, if we have to access any value, then we can directly access it is given by us. Mountain is the mountain of I use, here we cannot access the element of array directly, we have to use dot get function and for length we have to use dot length function, both of these are pre-defined and if we both of these are pre-defined and if we both of these are pre-defined and if we use If we don't do that, then the answer given by us will be considered as a color answer. Okay, so we have a mountain array interface defined in which there is a dot get function and a dot length function. We have to access any element using this and get the length. Okay, now let's take an example like here 1 2 3 4 5 3 1 Now if we see here then this value has increased till F. What happened after that, the decree was done, now what we have given is that the target is three and we have to return its least index, so it is 0 1 2 3 4 5 6. So let's see that we are at the second position. If three acres are happening, then what will we do? We will return two. Now what is to be done in this question, so what we have to do first is that the array is ok, we have to find the peak index of the array. Now if we people Let us see that if we have the peak index, after that if we have zero to peak index, okay zero to peak index, what will happen at this distance, our array will be in ascending order right and the length from peak index to What is our length minus till what will happen to us? The array will be in descending order. This means that here we can see that this far here is also sorted and this far away is also sorted, so we What can we do easily? If we have a sorted array then what do we do? We use binary search. Now we know that we have to use binary search here. Now we What will be the first task of the people? We will take out the Buck Index here and after that we will do a binary search and in this, our work will become easier as if we had given an example here. Okay, and what was our target? The target here is our three. Now if we see that between here and here, okay, this is our peak index. If we see our target in this distance. If we are getting the value, then we will not have to search in the decreasing order part, meaning if we have found the value in increasing order, then we will not have to check the other half of the array. So what has happened to us? The work of means whatever array item is there will be reduced further, right, we will not have to check in decreasing order and in this case, if we are not getting it in increasing order, then we will check in decreasing order and if in both of these We are not getting the value. If we assume that if the target is at then A is not executing then when the value is not being executed then we have to do minus and return. Okay, now first let us see how the peak index will be calculated. Okay, so what will we do for the peak index, we have to check that if we assume, okay, here what is the peak index, this is 0 on the tooth, our peak index is okay, now we have to see. Is this value okay, is the value after this one less than that or is it more than that? Okay, if the value after this one is less than this, meaning like there is a forest here, then what will we know now that if If we want to find out the peak index then we will have to check it before this also, otherwise what we will do is we will check it before this. Now here what we are seeing is that this which is less than 2, we will know what it means. Now we know the peak index, we have used it, our peak index has come, now we will use binary search, in binary search we first check. We will check whether we are working in a decreasing ordered array or increasing order or increasing and decreasing then here we pass if and decreasing then passing this decreasing if we will first find the increasing index for increasing order then here But this decreasing what will be false now if we have this decreasing is false this decreasing equals false then what we have to check is if array if we have our array dot get because here we have direct our element. If we cannot access then we will have to use get is less than target. Now we will take an example like array ev 2 3 5 3 1 what if we have to extract like in this we assume our target value. Yes, it is okay, so in this, first the increasing index that we will get will come out between zero to the peak index, so the mid value that we will get will be 0. If it is 3 then what will be the mid value of our P? Here it will be two, so now we are getting the condition that if the target is more than the value of mid, if the value of our is more then what will we do which is the lower value which is the lower index going on here. That mid of ours will be passed, right? And if it does not happen, then the right value will become equal to the mid. Okay, this is what happens when we have a decreasing falls, meaning that the part before the peak index is before the peak index. Now let's assume that we have a new array, two fifths. Okay, so let's assume that our target is three here too, but now we will not get it in the increasing order, so now we will not get it. If we have to check in the decreasing order then if it is in the decreasing order then first of all we will check that if it is decreasing true then here then decreasing is true if decreasing is true then we will check that if it is array dot Get mid is greater than the target is okay. Now let's assume like if f and th are there then what is the value of f which is greater than r of these two. If we take the mid value is okay 0 T 3 4 Now this is what we If we have th and four then what are we doing like what will be the mid value of us like a plus a minus l byte because here we are not starting from zero nor we are starting from the middle index. That's why what will be the AP? 4 minus 3 divided by 0. This is our 10th plus 1 Batu. So if we assume that our mid index will still be F then it is F. Now this mid index of ours is F. What is the index which is our target, if it is more than that then what do we have to do? We do not go in this direction, we have to go in this direction, otherwise what will be the lower index of our people, what will it become? And otherwise, our right index will be equal to mid since what do we have to do, if we want to return the lowest index, then we will return L in both of them. Okay, now let's look at the code, I have here. The code is already written, okay, in this I will tell you how it happened because once we understand the process of doing this query, then the code normally is just that we have to write binary search and find the peak index. First of all, like we are finding the peak index here, we will run from zero to length mit because here we will check that mid and mid is less than mid p. If we reach a value somewhere where we have to check till the last index, then the index will show out of bounds. To avoid this exception, we are running till A-2. Okay, so we are running till A-2. Okay, so we are running till A-2. Okay, so here we are. Normally, here we check and return the peak index by using binary search in the same way as we use binary. After that, we false this decreasing here for increasing index. So if we Now what is it that here it is decreasing then it will work as true. Now what do we know that it is false? So if it is false then this part will be executed for us. So the conditions which I had mentioned there are written here and After that, if we get our increasing index then we will check once to verify whether it is equal to the target or not. If it is equal then we will return the index and if not then Then we will find the decreasing index, then what will happen here in the decreasing index will become true. Now this part of ours will be executed. Now what is here that I told there that if array do not get mid is If the target is greater then it will be mid-point otherwise the target is greater then it will be mid-point otherwise the target is greater then it will be mid-point otherwise the index which will be on the right will be equal to mit and if we get neither increasing nor decreasing value in both of these then we – If you return 1 then we – If you return 1 then we – If you return 1 then let's submit it now and we will run it and I will put the code of this question in my Git Hub and its link will be in the description, you guys there. You can access the code from Thank you for watching
Find in Mountain Array
two-city-scheduling
_(This problem is an **interactive problem**.)_ You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `mountainArr`, return the **minimum** `index` such that `mountainArr.get(index) == target`. If such an `index` does not exist, return `-1`. **You cannot access the mountain array directly.** You may only access the array using a `MountainArray` interface: * `MountainArray.get(k)` returns the element of the array at index `k` (0-indexed). * `MountainArray.length()` returns the length of the array. Submissions making more than `100` calls to `MountainArray.get` will be judged _Wrong Answer_. Also, any solutions that attempt to circumvent the judge will result in disqualification. **Example 1:** **Input:** array = \[1,2,3,4,5,3,1\], target = 3 **Output:** 2 **Explanation:** 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. **Example 2:** **Input:** array = \[0,1,2,4,2,1\], target = 3 **Output:** -1 **Explanation:** 3 does not exist in `the array,` so we return -1. **Constraints:** * `3 <= mountain_arr.length() <= 104` * `0 <= target <= 109` * `0 <= mountain_arr.get(index) <= 109`
null
Array,Greedy,Sorting
Medium
null
367
hey everybody it's me abdullah welcome back and today we will be doing another lead code 367 valid perfect square this is an easy one given a positive integer num write a function that should return true if it is a perfect square as far so 4 is the perfect square because it is negative 2 x 2 and 9 16 25 and you name it like you know what is the perfect square so but we will be doing how we will be approaching this is just buying research so let's get started starting from the very beginning to the very end right will be where the very end while our left is less than or equal to the right if but before it will be computing our mid summit will be left plus right and then ground dividing it by two so if mid multiplied by made is less than um num itself what we will do is just right the left pointer will be mid minus 1 and left pointer will be made plus 1 and r will be yes in the else case in the l if case that case made multiplier made if it is greater than num then what we will be doing is just decrementing our mid so in this case we know that we have found our number so we will just return true and finally if we made out of the loop we will just return false so that's it let's see if this works yeah this works and that's it
Valid Perfect Square
valid-perfect-square
Given a positive integer num, return `true` _if_ `num` _is a perfect square or_ `false` _otherwise_. A **perfect square** is an integer that is the square of an integer. In other words, it is the product of some integer with itself. You must not use any built-in library function, such as `sqrt`. **Example 1:** **Input:** num = 16 **Output:** true **Explanation:** We return true because 4 \* 4 = 16 and 4 is an integer. **Example 2:** **Input:** num = 14 **Output:** false **Explanation:** We return false because 3.742 \* 3.742 = 14 and 3.742 is not an integer. **Constraints:** * `1 <= num <= 231 - 1`
null
Math,Binary Search
Easy
69,633
238
hello guys Samuel here in this video we are going to be solving the aorin problem product of AR except cell this is a common problem in technical interviews and it doubles as a good brain teaser also so let's di writing giving an integer array Norms return an array answer such that answer I is equal to the product of all the elements of norms except Norms I the product of any prefix or suffix of norms is guaranteed to fit in a 32bit integer you must write an algorithm that runs in Vig of end time and without using the division operation there are several ways to solve this problem and to see these different solutions first I would like to ignore the two constraints in the problem the first constraint is the fact that the algorithm should run in bigger of end time and the second constraint is a fact that division operation should not be used now let's dive into see these implementations I like to Define two terms other products and current elements the other product of an element is the product of all the other elements in the array except that element while the current element is the elements whose other products we are trying to calculate so given an array 1 2 3 four what the already wants us to do is to calculate the other product for each one of these elements so for the first element I'll calculate the other product and that is 2 * 3 * 4 which is 24 for and that is 2 * 3 * 4 which is 24 for and that is 2 * 3 * 4 which is 24 for the second element the other product is 1 * 3 * 4 which is 12 for the third 1 * 3 * 4 which is 12 for the third 1 * 3 * 4 which is 12 for the third elements the other product is 1 * 2 * 4 elements the other product is 1 * 2 * 4 elements the other product is 1 * 2 * 4 which gives 8 and for the last elements the other product is 1 * 2 * 3 which is the other product is 1 * 2 * 3 which is the other product is 1 * 2 * 3 which is 6 so this is the array the question wants us to return for the first solution for each element in the array which I call the current elements I'll go through all the elements in the array so as to calculate the other products for that current element I'll make use of a variable I to keep track of the position of the current element and I'll make use of another variable J to itate over all the elements in the array then I'll create another variable product to keep track of the other product for each current element and I'll initialize this to be one so for the first element in the array since the current element is not supposed to be included in the products I and J are pointed to the same element I'll ignore the current elements so I'll move j to the next element in the array which is two now I'll include two to the product next I'll move j to the next element in the array which is three and I'll include three in the product next I'll move j to the next element in the array which is four and I'll include that in the product also so now I calculate this product this is 1 * 2 * 3 calculate this product this is 1 * 2 * 3 calculate this product this is 1 * 2 * 3 * 4 which is 24 and um I would include * 4 which is 24 and um I would include * 4 which is 24 and um I would include that in an array so once I'm done with this current element which is one I'll move to the next current element which is two but before I do that I'll reset the product back to one and then move G back to the first element in the array and now I move I to the second element in the array which is two now since I and J are not pointing to the same element so I'll include this value of J which is one to the product and now I move j to the next element in the array but since they are pointing to the same element I'm not going to include two since two is current element it should not be included in the other product so I'll move j to the next element in the array which is three now I include three in the product and finally I move j to the last element in the array which is four so I include four in the product Now 1 * 1 * 3 * 4 gives 12 so product Now 1 * 1 * 3 * 4 gives 12 so product Now 1 * 1 * 3 * 4 gives 12 so I'll include 12 in the array next I'll go ahead to reset the value of the product to one and then I'll move j back to the first element in the array and now I move I to the next element in the array which is three now I include um I include one in the products I'll move j to the next element in the array which is two I include two in the product now I move j to the next element in the arrow which is three now I'm not going to include three in the product because it is a current element I and G I pointed the same element and now I move j to the last element in the array which is four so I include four in the product and this gives 1 * 1 * 2 * 4 product and this gives 1 * 1 * 2 * 4 product and this gives 1 * 1 * 2 * 4 which is 8 now I'll reset the product back to one I'll move j to the first element in the array and then I'll move I to the last element in the array which is four now I include the value of J in the product the element J is pointing two I'll include that in the product which is one then I'll move j to the next element in the array which is two I include this in the product move j to the next element in the array three and I include three in the product now I move j to the next element in the array which is four but since I and J are pointing to the same element and the current element is not supposed to be included in the product I'll ignore it so now this product is 1 * 1 * 2 * 3 so now this product is 1 * 1 * 2 * 3 so now this product is 1 * 1 * 2 * 3 which is 6 now and this is the same thing as a result the question is expecting for us to return now the time complexity for this algorithm is big of n^ 2 and that is because for each n^ 2 and that is because for each n^ 2 and that is because for each current element I am going through every element in the array and that gives a Time complexity of big of n^2 now since Time complexity of big of n^2 now since Time complexity of big of n^2 now since the question ask us to return an algorithm of big of n I'll not be implementing this solution in code now for the second solution what I'll do is that I'll calculate the product of all the elements in the array and for each elements in the array I'll divide the product by that element so the product of all the elements in the array is 1 * of all the elements in the array is 1 * of all the elements in the array is 1 * 2 * 3 * 4 which is 2 * 3 * 4 which is 2 * 3 * 4 which is 24 now for each element in the array I'll calculate the other product and for me to calculate the other product all I have to do is to divide the product by the current element so 24 divided 1 gives 24 ID 2 gives 12 24 ID 3 gives 8 then 24 ID 4 gives six and this is the same as the array we are expecting as a result now the time complexity of this algorithm is bigger of end because I'm going through all the elements in the array just once but then the question told us not to make use of the division operation so I will not be implementing this um algorithm in code but for the first and the second solution you can find the code in the GI up link in the description now for the last solution taking element two as an example to calculate the other product for two I can multiply the product of all the elements to the left of two which is one by the product of all the elements to the right of two which is 3 * 4 and to the right of two which is 3 * 4 and to the right of two which is 3 * 4 and that gives 12 for the next elements in the array which is three the product of all the elements the left of three is 1 * 2 which is the left of three is 1 * 2 which is the left of three is 1 * 2 which is two and the product of all the elements to the right of three is four and this gives eight which is the order product for element three so I'll keep track of two arrays a left product array and a right product array so for each current elements the left product array will keep track of the product of all the elements to the left of it while the right product array will keep track of the product of all the elements to the right of it so let's populate the left product array first starting from the first element one has no element to the left of it so the left product for element one is one now for the next element two to calculate the other product for two instead of V trting over all the elements before it I can make use of the value we had earlier calculated so to calculate the left product for two it is the left product of one time one and that gives one now I'll be moving to the next element which is three the left product of three is the left product of two times 2 so that is 1 * 2 which gives 2 so that is 1 * 2 which gives 2 so that is 1 * 2 which gives 2 now the final element which is four the left product of four is the left product of three times 3 now the left product of three is two then times three gives six so I'm done calculating the left product for each element in the array now I'll go ahead to calculate the right product I'll be starting from the last element in the array this is because I don't want to iate over all the elements after a particular element to calculate Its Right product I want to make use of a value that had been earlier computed to calculate the right product for any current element starting from the last element in the array which is four there is no element to the right of four so the right product of four is one now I'll go to the next element before it which is three now the right product for three is the right product of four time 4 the right product of four is 1 * 4 gives right product of four is 1 * 4 gives right product of four is 1 * 4 gives four now go to the next element before three which is two the right product for two is the right product of three times 3 so the right product of three is four 4 * 3 gives 12 now go back to the first 4 * 3 gives 12 now go back to the first 4 * 3 gives 12 now go back to the first element in the array which is one the right product of one is the right product of two time 2 the right product of two is 12 * 2 gives 24 now I'll of two is 12 * 2 gives 24 now I'll of two is 12 * 2 gives 24 now I'll create another array called products and the element of this product array would be the product of each elements in the left product array times the corresponding element in the right product array so for the first element of product array it will be 1 * element of product array it will be 1 * element of product array it will be 1 * 24 which is 24 the second element will be 1 * 12 which is 12 the next element be 1 * 12 which is 12 the next element be 1 * 12 which is 12 the next element is 2 * 4 which is8 and the last element is 2 * 4 which is8 and the last element is 2 * 4 which is8 and the last element is 6 * 1 which is 6 * 1 which is 6 * 1 which is 6 and this is identical to the array we are supposed to return now I would like to talk about the time and space complexity of this algorithm the time complexity of this algorithm is bigger of n now why is it bigger of n to populate the left product array I have to go through each element in the array once so if you have n elements in the array that will take n operations so that is big of n time complexity now to populate the right product array I have to do the same thing go through each element in the array on and this gives we of nend time complexity too and to populate the product array I have to go through each element in the right product and the left product array once so that takes biger of n time complexity also so I have bigger of n plus biger of n that gives bigo of 3 n time complexity and in bigo notations the coefficient is usually ignored so these approximates to Big of n the space complexity of this algorithm is bigger of n why is it bigger of n for the left product array it require Bigg of n space and this is because if you have an input array of n elements you would require a left product array of n element also the same thing applies to the right product array it require an array of bigger of n space for the product array an array of bigger of n space is also required so bigger of n plus b of n gives big of 3 n and just like I explained earlier these are approximates to Big of n now I'll go ahead to implement this solution in code the first thing I want to do is to get the length of the input array I'll save that in a variable called L next I'll create the left product array the length of this array will be the same thing as the length of the input array now I'll create the right product array have the same length as the input array now I'll go ahead to calculate values for the left product array starting from the first element in the input array since the first element in the input array has no elements before it I'll set the left product for that elements to the one now our comput values for the left product array starting from the second elements in the input array the left product of an element is the left product of the element before it times the elements before it now I'll go ahead to compute values for the rice product array starting from the last element in the input array since the last element in input array has no elements after it I'll set the right product for that element to be one the last element is at index L minus one now I'll go ahead to compute the right product for the other elements in the input array starting from the second to the last element is at index Len minus 2 the right product of an element is a right product of the element after it times the element after it next I'll go ahead to create the product array so have the same length as the input array to populate the product array for each element in the left product array I'll multiply it by the corresponding element in the right product array now I'll return the product array now go ahead to run the code for correctness it has passed I'll submit it has passed also I already talked about the time and space complexity of the algorithm the time complexity of the algorithm is Big of N and the space complexity is Big of n also that's it for this video thank you for watching if you found this video to be helpful kindly hit the like button to get more content like this on programming education subscribe to my channel I'll see you guys in the next one happy cing
Product of Array Except Self
product-of-array-except-self
Given an integer array `nums`, return _an array_ `answer` _such that_ `answer[i]` _is equal to the product of all the elements of_ `nums` _except_ `nums[i]`. The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer. You must write an algorithm that runs in `O(n)` time and without using the division operation. **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** \[24,12,8,6\] **Example 2:** **Input:** nums = \[-1,1,0,-3,3\] **Output:** \[0,0,9,0,0\] **Constraints:** * `2 <= nums.length <= 105` * `-30 <= nums[i] <= 30` * The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer. **Follow up:** Can you solve the problem in `O(1)` extra space complexity? (The output array **does not** count as extra space for space complexity analysis.)
null
Array,Prefix Sum
Medium
42,152,265,2267
135
hello everyone so in this video we are going to solve a question of greed code that is candy this is 135th question lead code and this comes under hard category all right let's start with the problem statement there are n children standing in a line each child is assigned a rating value given in the integer area ratings so basically we have given an error ratings all right and you are giving candies to these children subjected to the following requirements so basically we are given two conditions okay so these two conditions are first one that each child must have at least one candy okay this is very important each child must have at least one country okay and the second condition is children with a higher rating get more candies than its neighbor okay so basically what we need to check is the person or the child which is having the higher rating must be assigned more number of candy than its neighbor okay so let's understand with an example so let's say in the first example we have one zero and two okay this is our first example so in this first example let's say we assign one candies as per the first statement is each child must have at least one candidate so let's assign one candidate to each child so let's assign one candy and now let's check the second condition okay so the second condition what we have the higher rating gets the more candies okay so let's say in this one is ever having greater rating than zero so let's increment the number of enemies here similarly this 2 is having more number of candidates than its neighbor 0 let's increment this rating this number of candy okay so total we have 2 plus 1 plus two that is equal to five so total we have five number of candies and this is the minimum number okay since we just incremented one candy here okay so this is the best possible answer or we can say this is the minimum number of candies we can assign to each child okay so this is the example i hope the example is clear to you and you know how can we assign the minimum number of candidates let's see how can we approach this question okay so to approach this question let's see so let's take the first example again there is one zero and two so in one zero and two we have let's say we assign one candidate to each of the child again and let's say we haven't this is our rating array okay this is our given rating array and let's say we make another array of number of candies here and initially we assign one to all the child okay and now what we can do is we can start checking let's say we have just completed the first condition okay we have already assigned at least one candidate to each child now let's satisfy the second condition is higher rating gets more number of entries so what we can do is we can check the neighbors here okay so how can we check the neighbors first we can check left neighbors and in the second iteration we can check the right numbers so let's start with the first iteration so let's say first iteration we do from left to right in this direction okay and in this direction we basically check the left one okay so what we are doing we are checking the ith index with i minus one is index we are basically comparing both the index okay if the iath index is having the greater number of candies then or we can say the ith number is having the greater number of rating that is what mentioned here higher rating gets the more candy so if the iath index is having the greater number of rating or higher rating then we need to increment the candies okay let's see so let's say we have since we are starting from i minus one so it must the first point will start from here because if we start from this then we do not have any i minus 1 here index so we will be starting from the second one that is 0 so we will be starting from here and let's check whether this 0 is greater than i minus 1 is or not that is i minus 1 is 1 so it's not great let's move forward and this pointer will come here okay now let's check for this is 2 so 2 is greater than 0 okay so when 2 is greater than 0 it means the rating is greater okay the rating of 2 is greater than 0 so what we have to do we have to increment the candies here so how can we increment the country since we need the minimum number so the minimum possible value we can assign is the number of candidates zero is having that is let's say zero is having x number of candies okay and we want the minimum possible number of end is to be assigned to two such that it is greater than zero so we can assign x plus one you can this two okay so let's say in this case zero is having one candy so we will assign one plus one that is two candies so two okay now we have completed the first iteration okay now let's do the second iteration here earlier we were just iterating from left to right now let's straight from right to left okay now we are rotating in the right to left direction okay so let's separate now we are basically checking i and i plus one net index okay we are check basically checking the right neighbor okay so let's say we start from this point because if we start from 2 we do not have any i plus 1 index so we start from 0 okay so let's check whether this 0 is having the greater rating than 2 or not it's not true so we will just move forward to here now let's check one is having greater rating than 0 okay so if this is having greater rating than 0 then definitely we need to increment the candies okay so we will just increment this with 1 plus 1 but it will be equal to 2 now we have completed both iteration okay now we have just completed both iteration and we have we got the updated array here so updated arrays 2 1 and 2 so at the end we will just add all the number of entities so this will come out to be five okay two plus one plus two is equal to five i hope the approach is clear to you this is pretty easy question i would say and yeah let's record it up if you still have it out in this question feel free to comment it down i will try to explain the approach again all right so let's move to the coding part yeah so we have let's say we take in and that will be storing the total number of elements or we can say total number of children so ratings dot size okay and also let's make a vector of integer that will be storing number of candies here so can these and let's initialize all the values with one all right also take also check one more condition that is the edge condition here because let's say we are checking i minus one and i and in the other case we are checking i n i plus one okay so for this condition there must be two element at least okay that's why we are checking this so what we can do is let's say if let me write here if n is less than two then we will directly return one here okay now let's run the for loop for left to right iteration okay so let's write in i is equal to one since we were just taking from the next element that is zeroth element zero element okay so i is equal to 1 and i should be less than n and i plus all right now let's check if the rating of i is greater than rating of i minus 1 okay if it is greater and also check one more condition whether we need to increment the number of entities or not if the number of candidates are already greater then we don't need to make any changes here so if it is not greater let's say if candies of i is less than equal to candies of i minus 1 then only we need to increment the number of candies okay so let's increment candies i with candies i minus one plus one okay so this is our first iteration so in this iteration we have just checked the left elements or we can say left neighboring elements okay so now let's check the right neighboring element in the next iteration that we will do from right most side to left most side so let's initialize and i is equal to n minus 2 okay and i should be greater than equal to 0 and i minus okay since we are decrementing from right to left okay this should be i minus all right now let's check if rating of i is greater than ratings of this is ratings here yeah so if ratings of i is greater than ratings of i minus one so in this case it will become i plus one okay since we are taking 0 and 2 that is i this is i and this is i plus 1 okay so we are basically checking i n i plus 1 here all right so if this is true and whether the number of candies are less than equal to or not if it is less than equal to the i plus one ethnic then only we need to increment the count okay so let's check if candies of i is less than equal to candies of i plus one then we will just increment candice of i with indies of i plus one all right i guess this is fine now and let's count the number of candies so let's store this into the answer variable and let's run the for loop so far and let's x and candies just add answer plus equal to x and then just written answer from let's just release yeah it's working fine so let's submit this yeah it's working fine so let's calculate the time in space complexity of our solution so the time complexity of our solution is big o of n okay since we are iterating through all the n elements so the time complexity is bigger of n and the space complexity is big o of n because we are storing the n elements into this candy vectors all right so i hope the approach and solution is clear to you if you still have any doubt in this question feel free to comment down please like this video and subscribe to our channel i will see you in the next video
Candy
candy
There are `n` children standing in a line. Each child is assigned a rating value given in the integer array `ratings`. You are giving candies to these children subjected to the following requirements: * Each child must have at least one candy. * Children with a higher rating get more candies than their neighbors. Return _the minimum number of candies you need to have to distribute the candies to the children_. **Example 1:** **Input:** ratings = \[1,0,2\] **Output:** 5 **Explanation:** You can allocate to the first, second and third child with 2, 1, 2 candies respectively. **Example 2:** **Input:** ratings = \[1,2,2\] **Output:** 4 **Explanation:** You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions. **Constraints:** * `n == ratings.length` * `1 <= n <= 2 * 104` * `0 <= ratings[i] <= 2 * 104`
null
Array,Greedy
Hard
null
210
so we are looking at leap code number 210 it's course schedule two and i made a video on course schedule one highly recommend checking that out this is just building off of that problem or that pattern that i use to solve that problem and what we're doing here is again we are first assessing what is this question asking and what is the underlying data structure or algorithm that we want to implement that's going to solve this particular question and so for this is a graph problem and more specifically it is a directed acyclic or cyclic graph and what we want to find out is number one is there a cycle if there is a cycle then we cannot take all these courses it's going to return an empty array if there's not a cycle then we want to sort these numbers in a way that you can take all the courses so let's go ahead and read over the prompt there are total of n courses to that you take and that are labeled from 0 to n minus 1. some courses may have prerequisites for example prerequisites of i is a of i b of i this means that if you take course bi before ai given the total number of courses num courses and a list of prerequisite pairs return the ordering of the courses you should take to finish all of the courses if there may be very if there are many valid answers return any of them if it is impossible to finish all courses return an empty array okay so again i highly recommend checking out course schedule 1 that i did because this builds off of that so what this question is asking is we have two courses if you want to take course number one you have to take course number zero now because there's no other data in this array that means that you don't there's no prerequisites to take course 0. so we can take course 0 and then to take course 1 we've already taken course 0. so there's two courses we can take in the order is that we're going to take course zero first and then we can take course one input number two or example number two there's four courses here the prerequisites are one and zero two for course two the prerequisite is zero for course three the prerequisite is one and for course three the prerequisite is two so again this is a graph and we wanna try to visualize it in that way so we can see that there is no prerequisites for zero okay zero does not come up in the zeroth index on any of these edge lists so there's no prerequisite for zero so we can take zero here and now we can take course one and we can take course two because we have taken course one and we have taken course two the first prerequisite for course three we can take that allows us to take course three or because we've already taken course two we can also take course 3. and so the output is 0 2 1 3 or it could be 0 1 2 3. and there's a name for this sort of sorting it's called topological sort and that is basically what we're doing here we're just running topological sort on a graph problem okay so let's get into this so now i'm ju if you've seen my course schedule one video i'm basically doing the exact same thing first what i'm going to do is i'm going to go ahead and build out my adjacency list okay we're going to take n and then we're going to take edges and what we're going to do here is we're going to create an array that's going to be our adjacency list and the length of this array is going to be n and the we're going to fill each one of the elements of the array with another empty array and again i want to reiterate that when we are creating this array we are filling each element of that array with a brand new array that is mapped to a specific place in memory it's not the same array if you do new array and then you do length n and then do dot fill and you toss an array this is the same array that's being filled in every element of that parent array which you don't want that'll cause bugs okay so now what we're going to do we're going to iterate over this let edge of edges and now what we want to do is want to pull out our source and our destination and that's basically just the first two elements of this right here okay so we're going to have edge and then our adjacency list i'm going to push in adjacency list at source we're going to push in the dest and this will create an adjacency list for a directed graph okay and then we'll return our adjacency list and again if we wanted to do an undirected graph then we would just mirror this we'd do an adjacency list toss in the destination and push in the source and what that does is that essentially creates an undirected graph but we want a directed graph so we're going to leave that out all right and now we are doing a depth first search and what we're doing here is we're checking to see are there back edges is there a cycle in this graph when we traverse it from each particular node from each particular vertex and if there is a cycle then we cannot have we cannot take all the courses and we just want to go ahead and return an empty array if there's not a cycle as we go through the traversal we want to push in each one of the elements as we depart it and that will go ahead and give us our topological sort in the order in the in topological sort okay so we'll do a const depth first search and we're going to add our node in we're going to have our adjacency list we're going to have our visited we're going to have our arrive depart and then we're going to have our result which is going to be our top sort and again if you're not familiar with this i highly recommend checking out the book introduction to algorithms um it's there's a chapter on graphs that's really comprehensive that goes over step by step you want to figure out the edge classifications and how to get edge classifications on directed graphs so good it's if this is unclear i highly recommend checking that out so what we're going to do here is we're going to have our arrive and this is a time stamp so at our node we're going to increment this we're going to have our visited at our node i'm going to set that to true okay and now we're going to just follow our basic pattern for depth first search so let neighbor of adjacency list at node and if we have not visited this we're going to check well first we're going to add this to neighbor to our visited okay and now what we want to do is check to see if there's a cycle so debt first search on our neighbor adjacency list visited arrive depart top sort and if there is a cycle we're going to go ahead and return true the other case where there might be a cycle is if the depart at neighbor equals zero meaning we never departed out of there that means we're going to return true okay and now what we're going to do is we're going to increment our departure at node increment that we're going to add this node into topsort and we're going to return false okay so it's a slight change if you checked out my course schedule 1 video you can see that the only thing we did was just add this top sort here and push in the node that's all we had to do everything else is the exact same code all right and now we do our main function here again this is just a pattern it's a template it's good to have these that way when you come across these types of questions it doesn't throw you off you know exactly what to implement and then you can just change things slightly to fit the current problem so first we're going to do is go ahead and build our graph our adjacency list i'm sorry build adjacency list and again they give this they give us this graph in a edge list so our n here is going to be num courses and our edge list is going to be prerequisites q-u-i-s-i-t-s q-u-i-s-i-t-s q-u-i-s-i-t-s now we have to go ahead and create all our variables so we have our const visited which is just an empty object our arrived and here what we can do is just use that new array syntax and this will be the length of the array that's our num courses and then we want to dot fill this in with 0. this is our time stamp that we're doing and so you can do it this way okay and then we have our top sort and we'll also set that to an empty array okay and now we're just going to follow a very classic depth first search we're going to do let vertex equals 0 vertex is less than adjacency list on length vertex plus if we have not visited this node or this vertex we're going to traverse and here we just check if at vertex okay so if this step for search at this vertex list arrived if this returns true that means there's a cycle in there then we just want to return an empty array right because if there's a cycle then it's impossible to finish all the courses we just return an empty array and if not then we have traversed through the whole graph and here we have sorted it topologically by going through that depth first search traversal we just return sort and that is it let's go ahead and run this let's see here dfs is not defined whoops lowercase okay and we are good yeah and so again it just shows that when you come across these variation variations by having these patterns ingrained or just having them on hand all you really have to think about is what is this question asking is it that first search is it breadth first search is it topological sort and once you can just map that then it becomes you can actually solve these very quickly and easily so yeah that is course schedule two i hope you liked it and i'll see you on the next one
Course Schedule II
course-schedule-ii
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`. * For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`. Return _the ordering of courses you should take to finish all courses_. If there are many valid answers, return **any** of them. If it is impossible to finish all courses, return **an empty array**. **Example 1:** **Input:** numCourses = 2, prerequisites = \[\[1,0\]\] **Output:** \[0,1\] **Explanation:** There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is \[0,1\]. **Example 2:** **Input:** numCourses = 4, prerequisites = \[\[1,0\],\[2,0\],\[3,1\],\[3,2\]\] **Output:** \[0,2,1,3\] **Explanation:** There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is \[0,1,2,3\]. Another correct ordering is \[0,2,1,3\]. **Example 3:** **Input:** numCourses = 1, prerequisites = \[\] **Output:** \[0\] **Constraints:** * `1 <= numCourses <= 2000` * `0 <= prerequisites.length <= numCourses * (numCourses - 1)` * `prerequisites[i].length == 2` * `0 <= ai, bi < numCourses` * `ai != bi` * All the pairs `[ai, bi]` are **distinct**.
This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
Depth-First Search,Breadth-First Search,Graph,Topological Sort
Medium
207,269,310,444,630,1101,2220
62
hello today i'll be going over lead code number 62 unique paths so the problem statement is that a robot is located at the top left corner of an m by n grid and is marked as start in the diagram and the robot can either move only down or right at any point in time and the robot is trying to reach the bottom right corner which is the finish line so for example we have the robot at the top left corner and it can move either right or it can move down and the robot is trying to go to the finish line so what we want to do is print out the amount of ways the robot can go from start to the finish line the main solution to this problem involves strategy and the way we think about this is how many waves are there to get from s to s there are zero ways because we already started out at the position s how many ways are there to get from s to this square the square directly to the right there is one way to get there and that is by moving to the right ones how many ways is there to get to the square two spots away from s there is one way you can move two spots to the right similarly for these squares you're going to move three four five or six spots to the right so therefore for example there um there's only one way to get from s to this square over here and that is to go to the right by six spaces similarly we will notice that to go down um the amount of ways to go down one square is one way for going down two squares it is simply just going down directly down two squares we cannot go right in this example so now the question becomes how many ways is there to get to this diagonal square from s there are two ways to get here you can go right then down or you can go down then right and what we notice is that this number two is composed of the amount of ways to get to the square above it the amount of ways to get to the square to the left of it and if we look at the next one um how many ways are there to get to for example this square here there are three ways you could go all the way to the right and then go down one you could go right down right again or you can go down and all the way to the right what you notice is that this three is just one plus two so what we notice is that if we fill out the table using this so for example the next square here will be one plus three four and what this is once we get to this square you notice that the answer is 28 which means that there are 28 ways to get to the square e which is our answer and the way this works or why this works is because suppose we're at this square and we want to figure out the amount of ways to get to the square to the right of it the way we do this is if we calculate the amount of ways to get from here to here we notice that we can just go down once and go to our square so if there are five ways to get to the square above it then there should be five ways to get to this square as well now for the score to the left of it if there are 10 ways to get to that square then there should be an additional 10 ways to get to the square to the right of it because in each of the patterns once we get to this where we can just move to the right once and get to the square which we want so that is why each square the amount of ways to get to one square is the amount of ways to get to the square above it plus the amount of weights to get to the square to the left of it so in our solution we first created an array where we started storing the values so let's create that array so in that array now we have to traverse through the array and fill in the values for each square so let's write out a double nested for loop now inside this for loop we're going to have two conditions we notice that on the top in the entire top row every single square had a value of one meaning that there is one way to get from start to that square and you same for all of the squares on the left-hand column the left-hand column the left-hand column all the squares had a value of 1 meaning that there is one way to get from start to those squares so we can write an if statement for this we can write if i is equal to 0 or j is equal to 0. then we're going to fill in that value as one because there's one way to get to that square if not then we're going to fill in the value of the square we're at as this value of the square above it plus the value of the square to the left of it and then at the end what we have to do is at the finish line we have to return the value of that square so given n and m and using zero indexing we'll notice that we have to return the value of r at position m minus one n minus one if we submit this to the testing website we see that it is successful
Unique Paths
unique-paths
There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The test cases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** m = 3, n = 7 **Output:** 28 **Example 2:** **Input:** m = 3, n = 2 **Output:** 3 **Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down **Constraints:** * `1 <= m, n <= 100`
null
Math,Dynamic Programming,Combinatorics
Medium
63,64,174,2192
1,674
hey what's up guys this is john here again so today let's take a look at the second last problem of this week's weekly contest number 1674 minimum moves to make array complementary i mean this one is a really hard problem to ma in my opinion i think it's more d it's even more difficult than the uh than the last problem so you're given like an integer array numbers of even number of integers and under integer limits so in one move you can replace any integer from the nums with another integer between one and the limit and in inclusive and then there and they then defines uh the complementary so complementary is the uh it's for all the pairs with the nums i plus nums n minus 1 minus i equals to the same sum so for example the rate this one is complementary because for all the indices you know they're all they're some they're all equal to five and then it asks you to return the minimum number of the moves required to make this num complementary so here we have some examples here right i mean so for example the for in the frame in example one here so 1 plus 3 equals to 4 and then 2 plus 6 equals here two plus four equal to six so we have a sum we have four and six and the limit is four which means that we can simply make uh we can make this 1 equals to 2 3. we can change this 1 to 3 because 3 is in the range of 4 so that you know both pairs have the same sum which is six right and example two here right so i mean the first pair sum is two the second part is four but in this case we cannot make one so the actually the optimal solution is the way is to make this one to three that will only be one but since we have this limit here that's why we have to make either make this two becomes one or this one these two ones becomes two right and the last one this is already complementary that's why the limit is two that's why the output it's zero which means we don't need to do anything so at the first glance right i mean we have a minimum you know when you see a minimum of course you will try to solve it within uh with different approaches you know first one is like what maybe binary search maybe you try binary search but can we solve this problem for visit binary search probably not because for binary let's say we are we're assuming we are given like uh a number of moves it's a given number of moves m can we find the hyper functions to help us i mean decrease the search range right so even give given like the number of moves which means that conv within using and moves can we make this num this numbers a complimentary right so for that we still need to figure out which sum we need to choose basically what which is the target sum for all the pairs right so that's not going to help us so that the meaning so the binary search is not an option and second one is what's the dp but for this one obviously there's no dp it's not a dp related problem because there's no what there's no uh state transition function right because it's not a sequence by sequence it's a it's all or it's everything was all the pairs should go to the same goes to the same um sum right i mean something even if you try to use solve this one with dp you're going to be like the dpi right so the dpi which means that it's the current sum right what's the minimum moves to make the to make all the uh the pairs complement complementary i mean this with this given some given sum here right and from here where and then basically we will try to figure out like state transition function with dp i minus 1 something like that but there's no correlation between a different sum right so and dp is not option either and then what else right so i mean maybe the sliding window or the uh the greedy but none of them works so if none of those projects works what shall we do right i mean then most likely we have to try something different i mean which means we have to try something very basic it's a more like a brutal force plus optimizations which means we will basically try all the parts of the possible sum within a range right and uh and then we'll but for that you know if we but so the range of the sum will be what so we start from two because you know the uh the numbers we have two numbers so the minimum for each number is one right and how about the maximum is the uh basically the maximum of the uh of the sum right so that's this is the range and we want to try each of the range each of the sum here within the range here and we'll see which sum can give us the minimum number but how can we uh how can we know the minimum number right okay so from here onwards let's take let's go back to look at the uh one of the constraints here so notice here that you know limit is greater equal greater than any of the numbers here right so which means that what does it mean it means that and so it means that you know for each of the pairs right for each of the pairs the actually the maximum movements we need what we need to do is that actually that one it doesn't really matter with this limit if you if it's greater or equal than the nums the uh you know the worst case scenario right is what is the uh for each of the pairs we can always change those two pairs from any from a number a and b to one and one right so which means that in that case you know all the basically all the other numbers will become there becomes the old one so that each pair so the total sum it will be two by uh by changing this a and b to one so we so it means that we need at most two moves per each pairs to make them a complementary uh array that's going to be the worst case scenario and then let's keep thinking right so when can we make one move to make them to a target sum right so what's the range for one move or zero move right let's say we have a so we have this one three and four right so let's see a at a is one b is three and the limit is four so what's going to be the range for this pair what's the sum range right the total range for this pair to only make one move right so the of course the smallest is what it is two right because two is always the smallest between two and what so the because for the smallest range we have we change um actually this is not a good example let's say we have three and five and the limit is four okay so for this case right so what's going to be the smallest range right the smallest thumb that we can make one move to make that to be that to make that total basically we pick the biggest we pick which one is bigger and then we change this one to one right so basically you know the smallest sum we have here is four which means as long as the sum is in is between four and what four and four nine right it's four at nine and then we can only make this one move why is that okay so go back to here right so the smallest we have is four that's kind of obvious right because the smallest we can get by changing one number between range one and four is we pick the bigger numbers and we change it to one so after doing that so the total will be is one plus three which is four and how about the uh how about the top of the right side okay sorry so since here you know we have oops five three and the limit sorry the limit will be uh let's see the limit is six okay because the limit is always greater than any of the numbers so that's why the minimum is four how about the maximum is what we basically pick whichever is smaller and then we plus the limit which is three plus six is nine sorry it's not the i'm sorry so is the we pick the smaller numbers and then we change the smaller number to six so now we have three equals to six so the biggest the upper bound is five plus six which is eleven so now we have a range here right which means that from 4 to 11 as long as the sum the total target sum or total target the total is between 4 and 11 then we only need one move to make this number a and b to equal to this sum right and for each of the pairs given two numbers plus the limits we can have like this at this range here so now we have a range for each of the pairs right and we have a limit we have the range of the sum and we just need to find basically you know so now the problem comes down we have a range here we have different range right some of them might be overlapping to each other you know some of them are not right so we have this kind of range here now we want to find what are what we're looking for here we're looking for like the most overlapped range because you know anything outside of this range any place outside the this range will need two we will need like uh we'll need two uh two moves for each of the pairs so which means you know in total we have unmoves right that this is the worst case scenario because you know the n is the length of nums right so every time when we enter like a range here it means that we can do a n minus one because now we have a if let's say if the sum is right here right and then we know okay so now we have we can remove we can use one last move to make this to make all the numbers complementary right uh with this current sound and if we keep moving if we are right here then okay so we have entered two ranges right and then the n can be at can do a minus one again right and here if we're at here right and then okay so we now we have a three overlapped range here so now we can do it that's minus decrease the total end by one again right same thing we when we exit this range here so if we are at here if we add here you know we have uh we're outside of the first range that's why we have to do a plus one no sorry not plus one so it's not we can only do a n minus two right same thing and then keep and then we just keep going forward so the way we're doing this kind of line sweeping thing is because you know let's say we have a range s and if we're trying to use that if we try to fix each of the sum here right the sum and then with others of the those ranges if we try to see okay how many if the sum how many ranges can this sum falls in right if we do it in that brutal force way it's going to be a o n square time complexity and basically uh with this uh the constraint 10 to the power of 5 that would tle so that we have to find we have to use this kind of line sweeping techniques to uh to improve this n square to a o n right to oh and basically you know every time you know when we uh enter like a range we do a minus one right so here is also minus one and when we out when we are outside of the range we do a plus one here we do a plus one we also do a plot a plus one and yeah so then we can just uh using this n as a base and then we'll see how many numbers how many last moments we need to we can make right while try while trying all the possible sums and i that's the basic idea here okay so for the coatings right so i have a sum equals the default of dictionary so i'm going to use two dictionaries to store the uh um the div right so i'm go i'm going to have a div here so default dictionary integer so and i have n here length of the nums right so first let's try to create those ranges right so like i said so for the ranges i'm not going to store those ranges so like i said i'm only going to mark that minus one or plus one on this 1d line here so that later on i can sweep this all the points from left to right so here we have one minus one plus one those kind of stuff right because if we do a range if we just store them with a start and end range here right and then for with a given sum right we have to search we have to compare with each of the i mean the range pairs that's going to be too slow for us so now we have i in range and n divided by 2 right since we are only need those half of the sides because we need a we are looking for a pair so we have a right because two nums i and then we have a b equals to nums and minus i minus 1 right so that's two numbers and then let's say we need i need a minimum of them which is a minimum of a dot b right and then i need the maximum of them as well equals to max a and b so and the left right so for this kind of range like i said the left is what the left is equal to the minimum plus one right so which one is smaller we use that plus the other one we change the other the bigger one to the to one that's going to be the left boundaries and the right boundaries it's uh on the other side right it's gonna be the maximum right plus the limit right so to calculate the right boundaries we change the smaller number to the bigger to the biggest to the limit numbers and then we plus the maximum that's going to be the right boundaries and then we have a diff right so now we can mark the diff so the left boundaries every time we have a left we do a we'll do a minus one okay and when we're outside of the right boundaries but we have to do a right plus one and then we do a class one because the uh because this left the left and right there are they're both inclusive that see they're both inclusive that's why whenever we have we're at the right plus one then we know okay we are outside of that boundary that range right and another thing we also need to do is that's why i use this sum here because you know we have we also here we're only considering the one move case but there is also like a zero move case which is the uh whenever the sum is equal to the same of the a and b then we don't need anything we can just do uh we only need to we just need to do zero moves that's why i'm also going to count the uh the total the sum right of this the count for all the sum so that later on i can subtract this number from our final loop here now the uh so we have what so the answer will be system dot max size right that's gonna starting point and let's say we have so we have a current let's say the current is n right so i mean n is our starting point but it's basically that's going to be our a worst case scenario right and then for us that's going to be the sum right for some in the range of like i said two to the max sum right maximum plus one this is our sum range and current plus so every time we have a new sum here we update the current basically we will see how many different uh how many last or how many more operations we need here and then after this one we'll just update the answer the minimum of the answer right dot current but don't forget to minor though there's two things because for this current one right i mean it also includes it not only includes the one move case but it also includes the zero move case that's why we have to subtract those zero move k's from this current so that this current will be the uh the actual accurate because let's say for example here where i have for minus one move since we're only marking we only mark the left and right side so this minus one this is a minus one you know it's only representing minus one case but you know if the sums is equal to the uh to this a at to this a and b besides minus one we also need to do another minus two because for those two for those like the sum the pairs actually we should do a minus two case right but here we only do a minus one that's why for those pairs we have to do another but another minus one okay yeah and then in the end we simply return the answer yeah i think that's it because we're maintaining these things right we're trying to get the minimum for each of the sum and the sum is simply like accumulating the uh basically the uh the difference by doing a line sweeping of this one 1d line here and then if i do a sum here okay did i okay nums why it's taking so long all right accept it submit all right so let's accept it i mean so i think the time complexity for this one is pretty straightforward right we have a on here we have four loop here which is o n and then we have another uh this is the o and this is the uh actually this is the maximum of the sum so basically we have a of what is its maximum of n or the uh or the max sum right whichever is it's bigger then that's going to be our the time complexity right and the space complexity is of course is it's a o of n right because of this two dictionary here yeah i mean that's basically the uh the intuition for this problem you know so i think what's make this one the hard problem is the way we're solving this kind of solving this range problem and basically we're using like a line sweeping by uh by and by mark this the starting point and ending point on this one d array here so we have minus one and this kind of technique is it's not a very common one and if you don't know or if you haven't seen this kind of techniques i think it will be really hard to solve these problems by yourself unless you have previously seen or know there's like this kind of technique that where that you can use to mark the range right so that's the first thing and the second thing is that's one of the prerequisites which means that you have to find out the range right you have to find you have to be able to find the range to make one move and anything that outside of that range will make two moves and then from there you can have like a base you can have a base here right and then for each and then you can do the line sweeping by every time when you enter like a range you do a minus one and every time when you're outside of the range you do a plus one and of course you also need to maintain the uh this zero case yeah anyway so basically a few small techniques combined together you know so and then you can solve this problem anyway it's a cool problem which is also a hard one and i hope you guys enjoy watching this video okay thank you so much guys and stay tuned see you guys soon bye
Minimum Moves to Make Array Complementary
minimum-operations-to-make-array-equal
You are given an integer array `nums` of **even** length `n` and an integer `limit`. In one move, you can replace any integer from `nums` with another integer between `1` and `limit`, inclusive. The array `nums` is **complementary** if for all indices `i` (**0-indexed**), `nums[i] + nums[n - 1 - i]` equals the same number. For example, the array `[1,2,3,4]` is complementary because for all indices `i`, `nums[i] + nums[n - 1 - i] = 5`. Return the _**minimum** number of moves required to make_ `nums` _**complementary**_. **Example 1:** **Input:** nums = \[1,2,4,3\], limit = 4 **Output:** 1 **Explanation:** In 1 move, you can change nums to \[1,2,2,3\] (underlined elements are changed). nums\[0\] + nums\[3\] = 1 + 3 = 4. nums\[1\] + nums\[2\] = 2 + 2 = 4. nums\[2\] + nums\[1\] = 2 + 2 = 4. nums\[3\] + nums\[0\] = 3 + 1 = 4. Therefore, nums\[i\] + nums\[n-1-i\] = 4 for every i, so nums is complementary. **Example 2:** **Input:** nums = \[1,2,2,1\], limit = 2 **Output:** 2 **Explanation:** In 2 moves, you can change nums to \[2,2,2,2\]. You cannot change any number to 3 since 3 > limit. **Example 3:** **Input:** nums = \[1,2,1,2\], limit = 2 **Output:** 0 **Explanation:** nums is already complementary. **Constraints:** * `n == nums.length` * `2 <= n <= 105` * `1 <= nums[i] <= limit <= 105` * `n` is even.
Build the array arr using the given formula, define target = sum(arr) / n What is the number of operations needed to convert arr so that all elements equal target ?
Math
Medium
null
1,577
Hello hello friends welcome to my channel should we are going to discuss problem from the list weekly contest us loud problem number of way number is equal to a pappu number 00 shri were given to interior is number one and studied and how to From this triplets inspector vaidya make the types of tablet sophie consider organizer sweet can like your feet consider development from the number one food security fail to the par after j&amp;k from namaskar and in fail to the par after j&amp;k from namaskar and in fail to the par after j&amp;k from namaskar and in type-2 type-2 type-2 and then can be like elements for the nine to Here And Its Quest Is Equal To Pair From The Nuvve Research And K 163 Product Has To Be Equal To The Square Of The Other Address Element Poking Saunf Vihar To Count The Number Of Different Replacement For This Software Is Very Simple App Is Look And Example 174 For the number one and 528 90 to solve withdrawal this is pay calculate square from buddheshwar 60406 36.81 98100 36.81 98100 36.81 98100 169 effect a fair from this tours from to 16 to my result 216 can have one trip louis limit from the definitely 6 and elements of the year from Do Subscribe Purva and Paschim Formal Wear Look Shri Radhe Refill Simplicity Others Like This in Our Words and Doing a Pyun to Map Oil Laker One Four Ji Namaskar and Rather Namaskar Oil Filter Element from First Exam Calculating Square and Storing in to the Road Map and Find Locations Like You Plus One OK Similarly When Doing Same Procedure For The Way Are Doing This Which Is Hair And Shocking Like For These Apps Have Repeat This Procedure For The 11.20 M Taking Repeat This Procedure For The 11.20 M Taking Repeat This Procedure For The 11.20 M Taking Appears From The Great Two Days CNN's Ratings The Product Of Switch Of The Element And asked him weather such kind of productive already present in the world map 1.1 come seven eden gardens youth map 1.1 come seven eden gardens youth map 1.1 come seven eden gardens youth elements of that which is that like it is matching method pair from the namaskar 10 simple trick when * on the namaskar 10 simple trick when * on the namaskar 10 simple trick when * on form for the in the self time and the Same Forum Sugar Fast Beat Rated 2.0 By And Forum Sugar Fast Beat Rated 2.0 By And Forum Sugar Fast Beat Rated 2.0 By And Collected All The Best And Check Again Switch Off Way Similarly They Are Doing It For The Correct And Appears From Death One Enters Its Products Is Already Present In The Map 250 This Is Present In Every Time You Are In Preventing Deflect Video in Particular Ghrit Account is Finally and Displaying also Answer Sur Resolution School Accepted on the List Why Can See It's Quite 192 Test Cases and Have So You Can Refer Resolution and You Like My Video Please Like My Video and Subscribe My Channel To get further updates thanks for watching
Number of Ways Where Square of Number Is Equal to Product of Two Numbers
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules: * Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k < nums2.length`. * Type 2: Triplet (i, j, k) if `nums2[i]2 == nums1[j] * nums1[k]` where `0 <= i < nums2.length` and `0 <= j < k < nums1.length`. **Example 1:** **Input:** nums1 = \[7,4\], nums2 = \[5,2,8,9\] **Output:** 1 **Explanation:** Type 1: (1, 1, 2), nums1\[1\]2 = nums2\[1\] \* nums2\[2\]. (42 = 2 \* 8). **Example 2:** **Input:** nums1 = \[1,1\], nums2 = \[1,1,1\] **Output:** 9 **Explanation:** All Triplets are valid, because 12 = 1 \* 1. Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1\[i\]2 = nums2\[j\] \* nums2\[k\]. Type 2: (0,0,1), (1,0,1), (2,0,1). nums2\[i\]2 = nums1\[j\] \* nums1\[k\]. **Example 3:** **Input:** nums1 = \[7,7,8,3\], nums2 = \[1,2,9,7\] **Output:** 2 **Explanation:** There are 2 valid triplets. Type 1: (3,0,2). nums1\[3\]2 = nums2\[0\] \* nums2\[2\]. Type 2: (3,0,1). nums2\[3\]2 = nums1\[0\] \* nums1\[1\]. **Constraints:** * `1 <= nums1.length, nums2.length <= 1000` * `1 <= nums1[i], nums2[i] <= 105`
Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of a draw is the sigma of probabilities of different ways to achieve draw. Can you use Dynamic programming to solve this problem in a better complexity ?
Math,Dynamic Programming,Backtracking,Combinatorics,Probability and Statistics
Hard
null
386
today we're gonna be working on your code question number 386 lexicographical numbers and you have been given a number and written all the numbers in the range 1 to n sorted in lexicographical order you must write an algorithm that runs in linear time and without any extra space okay so one if we have to return the numbers from 1 to 13 we're going to be returning 1 and then 1 0 1 2 1 3 2 3 4 five six seven eight nine that is a lexicographical one so algorithm is going to be like we're gonna be going from all the numbers which cannot if we just look at it at the first ten numbers one through nine right uh it can be one and then one zero and one so we'll be using that uh like we're gonna be taking one number like number one and then we're gonna be keeping uh we're gonna go all the way one and then one zero one two one three until we see that we have exceeded this one and then we're gonna take the number two and do the same thing until we see that we have exceeded the number n so that being said let's have a list of integer result which is equal to new array list okay and then we're gonna call uh for and i it's going to go through from zero i is less than 10 and then i plus and then we're going to call our dv uh dfs with i n and then the result and in the end once we come out of that we can return the result the dfs doesn't really return anything it takes and uh what is the current value all right and what is the n and the result which we're gonna be filling up okay sounds good now if the current is less current has become greater than n then we can just return we don't want to process anymore return okay otherwise else what we're gonna be doing is like we're gonna ups we're gonna be adding uh the current to the result and then again we're going to do the same thing for end i equals to 0 i is less than 10. i plus and if again uh we're going to process we're going to try to create our new number by multiplying the number of current plus current i'm multiplying it with 10 and adding the i to it if there is still if it is uh if it is greater than n right we're gonna return otherwise we're going to call the dfs with this new number 10 multiplied by the current plus i and then the rest is going to stay the same that should do it should be current language overflow error we said that the current is greater than n we should return that is true otherwise the result dot add is going to be added the current then we have our i equals to 0 and is this and same thing is going on here where i wanted to start from one not from zero yeah i should start from one looking good
Lexicographical Numbers
lexicographical-numbers
Given an integer `n`, return all the numbers in the range `[1, n]` sorted in lexicographical order. You must write an algorithm that runs in `O(n)` time and uses `O(1)` extra space. **Example 1:** **Input:** n = 13 **Output:** \[1,10,11,12,13,2,3,4,5,6,7,8,9\] **Example 2:** **Input:** n = 2 **Output:** \[1,2\] **Constraints:** * `1 <= n <= 5 * 104`
null
Depth-First Search,Trie
Medium
null
239
hey everyone welcome back today we are going to solve problem number 239 sliding window maximum first we will see the explanation of the problem statement and the logic on the code now let's dive into the solution so in this problem we are given an input array in nums and we have case size so the case size represents the size of the sliding window so we can only have three elements in the sliding window right so we need to move this sliding window from left to right so we need to take maximum at each and every case size sliding window so in this case it is three so after getting 3 we need to move the sliding window by one so again we need to take the maximum right so we need to move the sliding window till the end so we need to take maximum in each and every sliding window and we need to finally append these values in the result array right so now we will see how we are going to do this so initially we are going to have window array where we are going to store the indices of the current elements in the current window so initially we are going to pick the first element 1 and its index 0. so I will be having the index that is 0 and num will be having the current number one so first we need to check whether we need to throw any element out of this window in order to include this number in the window so in this case we don't have any number in the window so we can include this number in the window right so we are going to append the current numbers index in the window that is zero so I will show you guys the next iteration how we will append the maximum in the result so now we pick the next element 3 and its index so index is 1 and the current number is 3. so now we need to check whether we have case size elements in the window we don't have case elements in the window we don't have to throw any elements from the window so now we are going to compare the last element value in the window on the current element value so here we have the current element as 3 and we can use the last element index to get the value that is 1. so we need to check whether the current number is greater than the last number in the window if this is true this particular index element is not going to be maximum right it is going to be smaller in the current window so we can just pop this one then we include the current numbers index that is 1. so the idea is we are always going to keep the maximum element at the front so now we need to check whether we have K elements in the current window so we don't have K elements right we have only two elements but the K is 3 so we pick the next value that is negative 1 and its index is 2. so now we need to check whether we have more than K elements in the current window we don't have more than K elements we have K elements right now so then we need to compare the current number on the last value in the window so we have the index 1 so we pick the value using the index one that is 3 so here negative 1 is not greater than 3 so we don't have to pop one from the window we just append the current values index that is 2. so now we need to check whether we have K elements in the current window or not we will use the current index to we need to check whether it is greater than or equal to K minus 1. so in this case 2 is greater than equal to 2 so it is valid so now we will append the maximum value in the current window using the first index in the window so the first indexes 3 so we will append 3 to the result so now we pick the next value that is negative 3 and its index is 3. so the window has been extended like this so now we need to check whether we need to throw any indices of elements that are not in my current window so the current window is like this right so we need to take difference between the current index 3 and K that is 3 and we will add 1 to it if this is greater than the first value in the window we need to pop this particular index from the window right so here we are going to get 1 is not greater than 1 so here we have one right so we need to include these all elements in the window so here we could see that right 1 and 2 are included in this window this particular element has been already popped out from the window in the previous iterations so now we need to compare the current value negative 3 is greater than the last value in the window so here the last value is negative 1 since this is not greater we have to just append the index of the current number that is 3. so we could see that right in this is one two and three or in my current window so now we need to take the maximum in the current window which is nothing but the first index value in my window that is three so now we pick the next element that is 5 and it's index 4. so the window has been extended like this so now we need to check whether we need to throw any index that is not in my current window so here we could see that right the first index is not in my current window so we need to pop this one from the window so then we need to check the current number with a lost value in the current window so the last value is negative 3 so here 5 is greater than negative 3 we just pop this one from the window then we need to check 5 and the index value 2. so the index value 2 is negative 1 since 5 is greater than negative 1 we pop this one as well from the window so now the window is empty then we pop the current elements index in the window that is 4. so we always have the maximum elements index at the front right so now we pick the maximum element in the window that is nothing but the index value 4 that is 5. so we append 5 here so the window becomes like this right because we have thrown these two numbers from the window we only have this particular element in the window so now we pick the next value 3 so we pick number three and it's index 5. so now we need to check whether we need to throw anything out of this window so here we don't have to throw anything from the window so we just compare the current number three whether this one is greater than the value Phi right so we are just extending the window like this so here 3 is not greater than 5 so we just append the index of 3 that is 5 so we are extending this window right so the maximum element in this particular window is three so this particular window is actually nothing but the this case size window so in this case we have thrown this particular Arrangement since it is small right so since we have thrown we have only two elements in that window so the maximum element in this window is 5 so we append 5 to the window so we append 5 to the result so if we keep on doing that we will be having 6 and 7 the result as well so that's all the logic is now we will see the code so before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially we will be having result and window list then we will be writing a for Loop we will pick the index and the current numbers value right using the enumerate function then we will be writing a while loop where we will run the while loop until we have removed the indices of elements that are not in the current window right then we will be writing another while loop we will run this while loop until we have the maximum element at the front right then we will append the current elements index in the window then we will check if we have reached the case size we will append the maximum element using the first index available in the window to get the maximum value from the nums right then finally we will return the result that's all the quarters now we will run the code as you guys see it's pretty much efficient thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos keep supporting happy learning cheers guys
Sliding Window Maximum
sliding-window-maximum
You are given an array of integers `nums`, there is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position. Return _the max sliding window_. **Example 1:** **Input:** nums = \[1,3,-1,-3,5,3,6,7\], k = 3 **Output:** \[3,3,5,5,6,7\] **Explanation:** Window position Max --------------- ----- \[1 3 -1\] -3 5 3 6 7 **3** 1 \[3 -1 -3\] 5 3 6 7 **3** 1 3 \[-1 -3 5\] 3 6 7 ** 5** 1 3 -1 \[-3 5 3\] 6 7 **5** 1 3 -1 -3 \[5 3 6\] 7 **6** 1 3 -1 -3 5 \[3 6 7\] **7** **Example 2:** **Input:** nums = \[1\], k = 1 **Output:** \[1\] **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` * `1 <= k <= nums.length`
How about using a data structure such as deque (double-ended queue)? The queue size need not be the same as the window’s size. Remove redundant elements and the queue should store only elements that need to be considered.
Array,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
Hard
76,155,159,265,1814
242
in this video we'll go over lead code question number 242 valid anagram given two strings we have to return true if they are anagrams of one another and return false otherwise now an anagram is a word that can be formed by rearranging the letters of another word for example Knight and thing are anagrams because you can rearrange the letters of each word to form the other so our first strategy will be to sort each string then compare them if they are the same then they are anagrams this is the most straightforward method but since the cost of sorting can be no less than o of n log n if the length of the longer string is n then this algorithm runs in O of n log n time so to improve this the first Insight we have is that there's actually no reason why the characters need to be in sorted order the only thing we need to know are just the character frequencies in other words if two words use the same number of each character then they are anagrams we'll be using a python dictionary to keep track of each character and its frequency and as you'll see this will allow us to reduce the runtime to O of n now let's look at the code and solve this in Python let's assume the two strings s and t are Loop and Polo the first thing we'll do is create two dictionaries one for S and one for T that will store the character frequencies of each string the dictionaries will have a character as its key and its frequency as its value so we're going to be using a variable called Char to Loop over s now let's break down this line over here first we're going to be using the built-in get we're going to be using the built-in get we're going to be using the built-in get method of dictionaries to get the value that corresponds to the key of char so in this case the key is L now the nice thing about using the get method is that it allows a second argument which is what will be returned if the specified key doesn't exist in the dictionary so right now since the dictionary is empty the key of L doesn't exist so this part right here will return 0. then we add one to increment that value so 0 plus 1 equals one so now we have a value of one which we're then going to assign to the key of char which is again l so in the S frequency dictionary we're going to create a key of L which corresponds to a value of 1. this means that we have seen the letter L one time now you can also write this using IF else logic like this if the key exists in a dictionary then increment it else initialize its value to 1. this works but chose this way because I think using the get method looks a lot cleaner so then we'll move on to the next character which is o does not exist in a dictionary so again we'll create a key of O which corresponds to a value of 1. next we come across another o now since o already exists as a key this part will return its current value which is one we then add 1 to that to increment its value so we update the key of O to have a value of 2. finally the last character is p which is not in a dictionary so we create a key value pair of P which corresponds to one now we're done with s and we can move on to the next string T we're going to do the exact same thing here except store the character frequencies in the T frequency dictionary so the first character P doesn't exist in a dictionary so we created and initialize a value of one o also doesn't exist so it also gets a value of one and neither does l so we do the same thing the last character o does exist so we'll increment its value to 2 and we're done with this Loop now remember if two strings have the same frequencies of characters then they are anagrams so the last step is just to compare the two dictionaries and return true if their contents are the same and return false if not remember in Python comparing dictionaries with the equality operator compares the contents of each dictionary with the other so if both dictionaries have the exact same key value pairs then this line will return true and if the dictionaries were different from each other then that means that the two strings have different character frequencies so they are not anagrams of each other and we would return false so in this case both dictionaries have the same contents so we return true which means that Loop and Polo are anagrams of each other and we are done now before I end this I want to mention a couple of variations on this solution that you could do if you wanted to save space then instead of creating two dictionaries one for each string you could only use one dictionary for the first string you would increment the values in the dictionary but for the second string you would decrement the values in the same dictionary then at the end if all the values in a dictionary are 0 then that means that the character frequencies are the same and the strings are anagrams you could even get rid of the dictionary completely and use an array instead the character a would map to index 0 B would map to index 1 and so on this would allow you to avoid doing the hash calculations that are required when using hash tables AKA dictionaries so I chose the method of using two dictionaries because I thought it was the most straightforward way but if you're interested in solving this problem in a different way I would encourage you to try to implement these Solutions here as a challenge
Valid Anagram
valid-anagram
Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** s = "anagram", t = "nagaram" **Output:** true **Example 2:** **Input:** s = "rat", t = "car" **Output:** false **Constraints:** * `1 <= s.length, t.length <= 5 * 104` * `s` and `t` consist of lowercase English letters. **Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
null
Hash Table,String,Sorting
Easy
49,266,438
1,721
hey so welcome back and this is another daily code problem so today it's called swapping nodes in a linked list and so it's a medium level problem where you're given a linked list here along with an integer a k and all that you want to do is you want to swap the node that is like the kth node from the start which in this case is this one because the number is 2 here and well this is the first node and this is the second node and you want to switch places with the node that is the K from the end and so this is like the first last note is how I thought of it and then this is the second last suit swap four with two in this case so then it becomes four and then two okay so to do this uh the first thing is you want to check kind of the base case where okay what if there's nothing in that case we just want to return null so if you get a null list you can't swap anything anyways so you might as well just return it so if there is no head then let's just return the head or I guess really in that case you can just return none otherwise you want to keep processing it and so typically for these type questions we need to know like the given index of the node you want to First find out the length and so that way you can find out okay what is the case you can easily find out like and count forwards you know say you're given uh k equals two you just say okay one move over one and then two so you just travel it you know 4i in the range of one to two and you just hop twice but when you want something like kth node from the end you want to get the length with the which is the in this case five so this has a length of five and so to get the kth node from the end which is in this case this one you would just do five minus two which is then three which would then point to this one because this is one two three but then because we want actually this node here you just do five minus two plus one or really five minus K that's 5 minus K plus one okay and so that's basically it so we want to travel forward K times to get the like the kth node from the beginning and then we also want to grab the length of the linked list in order to travel five or like uh the length minus K plus one times to get the kth node from the end here okay so that doesn't make sense it might make a little more sense once we were out the code so at the end of this we're going to want to return the head of the linked list again but we'll have modified that linked list and so the first thing that we're going to want to do is let's find out the length of this linked list and so we just want to say okay let's have some node and we're initially going to set it to the head and we want to keep iterating and moving down this list once we reach the end so we just say while we have a node here okay while it's not none or not null and so we just keep saying okay node is equal to the next node that's just how we move down the list but while this is going we want to be incrementing the length starting at zero so teacher duration let's just add one to the length that's basically how we get the length of the linked list but now what we can do at the same time is just grab the kth node from the beginning as well and we just want to say okay once the length is equal to K that's the kth node from the beginning and so we can just set that here so we'll say like uh start node I'll call it and that represents the kth node from the beginning and that is initially going to be equal to null here and so we'll just set that here where okay if the length is equal to um k then let's just set that start mode equal to the current node great and so that's how we get our kth node from the beginning and so now we still want to find the other node which is the kth node from the end so let's find the kth node from the end and so to do this all that we want to do is say okay let's keep iterating down this list starting from the head again so we want to reset our node at the head and we just say okay let's iterate through this list um in the range of one to K or really the length minus K plus 1. and so I will just say okay between the range of one two in this case four let's just keep iterating through this list and all that we have to do is oh I didn't fill this out correctly for underscore in the range of that and so with each iteration we just want to move our node to the next node great so at the very end of this we're finally going to have the endnote and so actually we can just set this equal to end node and do the same thing here okay so now we have both the starting node and the ending node here and so all that is left is we just want to say okay um let's swap them and to do this you don't actually need like a deep clone of it you don't have to switch the pointers around although we have to do swap values and so we can just use a temporary variable which will grab the starting node value and then we can just update that start node value to the endnodes value and then basically repeat that process for the end node here to be equal to what we stored in that temporary variable great and so this is just swapping the two node values let's go ahead and run this oh uh just got a colon oh I think there's an infinite Loop here so while node believe we're doing node.next what's going on here recursion oh so we just want to set the value here looks good yes all that was happening is this ended up having a cycle in it so it was basically when we were evaluating this with different test cases and it would have iterated through the linked list um the linked list that we were returning had a cycle in it so that's where the recursion max depth uh error was coming from yeah so that looks good let's try submitting it and success so basically this runs in O of end time or really like o of 2 times n but it rounds down to ovin where n is the length of the linked list and that's just because we iterate through the linked list entirely you know at most twice and then for space complexity well this is just o of one or constant space because we don't use any extra data structures other than what's given to us and variables which doesn't really count so it's over one space but yeah I hope that helped and good luck with the rest your algorithms thanks for watching
Swapping Nodes in a Linked List
maximum-profit-of-operating-a-centennial-wheel
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
Array,Simulation
Medium
null
1,936
Hello hello friends today we are going to discuss we medium play list problem dad 1938 minimum number of friends a letter e did you give otherwise strictly increasing in danger rank date represents height of the rings on letter you are currently on the floor 80 And you want to reach the glass thank you are also given and teacher dist that you can only climb to the next is friend at the distance between where you are currently on the floor and on the next remedy is Adams dist is you are Able to insert the ranks and any positive interior height is ranks is not already this eternal minimum number of friends and that must be added to the letter in order to climb to last so let's under this to understand with sketch 168 that it is Like the Hindus are Vikram Exam but oh that and I want to reach today and after every day hai android koh der jab if we are not apps the distance between last a and s class number and to adjust number 10 greater noida distance between her to Insert something subscribe problem that and to understand you states like Bihar district two so they can make number to every other problem like this to Swadesh test kasi dekh lena thing but that Bihar initial years or so that your love to your self is initially 10 and they can make exam Point To Na Saunf 2012 And MS Word 1512 And Hai 103 Item Example Of To All Acts With A Pure Mind Can Reach At 5 Vikas Thi - 5 - Mind Can Reach At 5 Vikas Thi - 5 - Mind Can Reach At 5 Vikas Thi - 5 - Is Equal To Three Subscribe I Don't Discharge A And Sunao From 50 The Distance Between Right And Left the envelope that and don't see the distance and jam a wicket in just to your soul will need a number in between the were the would like to go to 7 nikal dec new delhi ko like to distance from the 5157 still ca n't mode 210 between Center Distances 23 24 August Need to Put Something That Between Heaven and 10th Impotent 90 900 Episodes Anything and 90 That When to 8 and 9 Agenda But When ₹ 10 Family Logic and 9 Agenda But When ₹ 10 Family Logic and 9 Agenda But When ₹ 10 Family Logic and Problem Content with Other Behavior Ajay Ko The First Space for That Were Initially 80 and explorer 9 views 123 development of wish born in india in i online from three vpn will rise jump 26 from big ass and distances garlic and another snowden sea and from the juicer also executed 298 agree vadodara 1820 dumper 8 this is not Less than from Jaipur train tomorrow morning in this case which does not need anything because of all the distances which is arm day 3 and it is similar to the word ocean Weightage for this test A lesson 10 and 31 marks here Science for this test Hai Virat Floor 3480 Makers Now 2 Sunao From 0 Can Go To Three Legal Defense And So On Ki Vihar To Play Something Year At One And To And Placid At One Day They Can Make Jump From 021 From Day 12303 06087 Hua Hai 210 Actually Dash Open that and decide what is the spinner 's problem for 's problem for 's problem for that election let's understand this problem that distances and one more day status that is like you will cancel four that and that distances were one that show the prime project derailed near following will Have To Check What Is The Distance Between East West Entrance Exam Distance And Meditation Plate Subject Also Do Not Need To Insert Anything But When A Guy More Than That Date That In Bed That Vihar To Calculate Astrologer In Recent Years Back To Insert That NDP Notice Jai Hind Is Case Orange Juice In Both Cases Were Supposed To Insert Seventh And Eighth Note 200 Basically Nothing That Bhatt 90 8 - 5 Hai That Is 8 - 5 Hai That Is 8 - 5 Hai That Is Divided By Hai To Main Subah Se Bol Tu Play Store And Disadvantage But In This Case Which Supports Two Places At warning 223 that your in this case is valid than but as they go through this a logic our logic solitaire 0490 then that divided by the one is that is equal to 4 state cabinet will have to generalized for all the cases is so but when does e Will do me difference e Will do me difference e Will do me difference that and divided by dist a that and reduce one from its member we are going to solve that and solve that and solve that and went 22 - one from and operation in bodhak acid 22 - one from and operation in bodhak acid 22 - one from and operation in bodhak acid like for - 121 like for - 121 like for - 121 hands free - 1the 2222 that Is the correct hands free - 1the 2222 that Is the correct hands free - 1the 2222 that Is the correct answer activity for this test kit and this will turn out to be true than so let's have pride record so angry bird spacing so initially behar and ground a how to replenish condition is e will and 202 lots of i morning from through like Bihar including rural and nine let's declare variables to track the phone number and In the day which face dot length - mind to main young that i plus ok now second and fluid rate today are 's nominees step and calculating difference a main to 's nominees step and calculating difference a main to 's nominees step and calculating difference a main to late declare variables diff that day present nothing's birthday distance between how to rans 116 distance Do it between that i plus one but that is also that tight customer - flash light to off egypt that we paste health care ki dev and tell a win over cardiff hai navya support to calculate that checked or an actually license ki judgment we can make And It's More Than A You Slept During This Activity A Great Dane That Dist One Day This Photo That We Will Hand Over To Calculation And Were Supposed To Calculate The Number Of One Under This Vacancy Needed In Iteration Were Going To Add Water Weight Number Needed For Free distribution for this is not PM discussed now give me maths dot in do this divine divided by that dist that and that which arrangement value em well reduce one from net that and now they can return acid number aaj morning delhi today to work ke Special Judge Logic That Is Electrolyte That Looks Like A Per King I Let Summarize That Your 24 Things And They Can Also Check Like Us That Your 210 Express Accepted Solution A Few Have Anything And Don't And Is Not Able To Explain Something Clearly Feel Free to comment thanks for watching a
Add Minimum Number of Rungs
maximize-number-of-nice-divisors
You are given a **strictly increasing** integer array `rungs` that represents the **height** of rungs on a ladder. You are currently on the **floor** at height `0`, and you want to reach the last rung. You are also given an integer `dist`. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is **at most** `dist`. You are able to insert rungs at any positive **integer** height if a rung is not already there. Return _the **minimum** number of rungs that must be added to the ladder in order for you to climb to the last rung._ **Example 1:** **Input:** rungs = \[1,3,5,10\], dist = 2 **Output:** 2 **Explanation:** You currently cannot reach the last rung. Add rungs at heights 7 and 8 to climb this ladder. The ladder will now have rungs at \[1,3,5,7,8,10\]. **Example 2:** **Input:** rungs = \[3,6,8,10\], dist = 3 **Output:** 0 **Explanation:** This ladder can be climbed without adding additional rungs. **Example 3:** **Input:** rungs = \[3,4,6,7\], dist = 2 **Output:** 1 **Explanation:** You currently cannot reach the first rung from the ground. Add a rung at height 1 to climb this ladder. The ladder will now have rungs at \[1,3,4,6,7\]. **Constraints:** * `1 <= rungs.length <= 105` * `1 <= rungs[i] <= 109` * `1 <= dist <= 109` * `rungs` is **strictly increasing**.
The number of nice divisors is equal to the product of the count of each prime factor. Then the problem is reduced to: given n, find a sequence of numbers whose sum equals n and whose product is maximized. This sequence can have no numbers that are larger than 4. Proof: if it contains a number x that is larger than 4, then you can replace x with floor(x/2) and ceil(x/2), and floor(x/2) * ceil(x/2) > x. You can also replace 4s with two 2s. Hence, there will always be optimal solutions with only 2s and 3s. If there are three 2s, you can replace them with two 3s to get a better product. Hence, you'll never have more than two 2s. Keep adding 3s as long as n ≥ 5.
Math,Recursion
Hard
343
23
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward you have not liked the video please like it subscribe to my channel and hit the bell icon so that you get notified when i post a new video without so without any further ado let's get started so the problem is merge k sorted list so in this problem what will be given an array of k linked list so a area will be given and it will have linked lists each link list is its sorted order so each link list is sorted we have to merge all those link list into one sorted link list and return it see this is an array given and it has these link list 145 is a link list 134 is a linked list and two and six is linked list we have to merge these three linked lists together and then we need to return the final link list this is the problem see so this is a linked list this is the linked list so we'll write it like this 1 3 so this is given to us just a second here like this is the input which is given to us right now this means that 1 four five this is a linked list then one three and four this is a linked list two six this is a linked list all right we have to merge this link list merging means we have to merge them so all the elements will be in sorted order in the final linked list so that is one there are two ones then two will come from this linked list then three will come from this linked list and four there are two fours so four and then five and then six so this will be the merge final merged linked list merged sorted merge means all the elements of those linked lists together and sorted these are sorted order in sorted order more sorted linked list right so see this is the output we have to return the sort one sorted linked list so this is the output right i hope you understood the approach uh like i hope you understood the problem let's see how we can approach this problem so there are many approaches for this we will discuss three approaches so for the first two uh like approaches we'll be discussing the approach only and for the last approach we'll see the code see so this is the output rate we have to see we have to combine all these all the elements of these linked lists we have to combine and then we have to just sort them right so see what you can do we sorting is coming now sort sorting is coming so you can think of using the sort function you can use of thinking sort function and sort function is on what a vector so what you can do is you can traverse this linked list like first linked list traverse store the elements in a vector then traverse the second linked list store the elements in the vector and then traverse the third linked list and store the elements in the vector now just do one thing just sort this vector so now this vector will become what 1 2 3 4 5 6 so this will be sorted so once a vector is sorted now you just need to make a new linkage you have to create a new linked list which will have all these nodes one node one so these this will be the output then just need to convert this vector into linked list you have to create a linked list so this was one approach so what would be the time complexity for this what we are doing we are stored we are traversing all the linked lists storing them in a vector sorting them and then making a linked list so making a linked list is of end time traversing these link lists will be you can say uh we have to go to each link listener so if there are k link list and the length of the linked list is n so k n will be the time for that because we need to go to each linked list and we need to add the values then we need to go to the second so there will be for loop and then for traversal in the linked list there will be a while loop so this will be the complexity and sorting will be o of n log n so time complexity for this approach is o of k n right because we like maximum is this one or if we say like how many linked lists could be there if you see the constraints k will be 10 raised to the power 4 right so it will be a bigger it is a bigger value now space complexity will be what space complexity we are taking a vector so it will be o of n or n where n is c n is what total all the total nodes all the total elements in all the linked lists so this is one approach right this is one approach and we can see like this is not efficient approach other approach which we can use is see yeah we have to merge all the linked lists we have to merge all the sorted merge case sorted link list see the question is merge k sorted linked list so we are given this k we will be given k linked list and we do merge them if you have done this problem merge two sorted link list so you will be able to approach this problem using that if you are not uh if you are not aware of how to merge two sorted link list i have made a video on it the link will be in the description so you can check that out first so merge two linked list see first of all we can do what we can merge these two link list it will give us what it will give us a merged link list that is one comma three comma four comma 5 it will give us this and then what we can do we can merge this to find this final one the merged one with the this one so then it will give us 1 comma here 2 will come then 3 4 and then 5 comma 6 so this is one way of solving this problem that is we can use the concept of merge 2 sorted linked list and every time we will be picking two link lists and we'll be merging them this is what we are doing we will merge these together then the final the merged one we will merge it with this one right so for time this also time complexity will be quadratic in quadratic so see merging two sorted linked list will be o of n time and how many link lists are there are k link list so for every time we have to do for that so it will be kn time complexity kn right and space complexity will be o of uh space complexity will be we are we'll be creating this now this one we will be creating this so extra space will be required for making this so it will be o of n right so this is the second approach which we can use this is also not efficient now let's see what will be the third approach so this is see we have every time what we are doing is we are getting the like okay and kn time complexity are getting so we have to reduce it somehow we have to reduce it so and here the concept of sorting is used now like in the first approach sorting was coming into picture because we have to sort the elements so whenever sorting comes now whenever sorting is there you can think of using heap because in heap either we can use minip so we can get the minimum elements and we can use maxi to get the max elements so what he which heap we will use in this problem what the output should be c output should be 1 comma 2 3 4 5 6 this should be the output so we have to get the minimum element first and then we have to get the like we have to go and then the maximum like this so this how we can do this we can do using min heap because mini heap will have every time will give us the minimum element and we will just make a linklish out of that right so what we will do see we what we will do is we will have this we will have a uh what we will do is we will have a sorry will we have a i mean heap now i am making this we'll have a min heap we have this meaning we will traverse this linked list we are traversing the link list so uh what it will be one uh this so all these elements will be stored at the mini we'll be traversing the linked list one by one because we need to store all these so these are three approaches of this problem so third approach we are discussing so one i'm like traversing all the so this will be something like this now uh so first of all six will be at the bottom then five four three two one this will be the mini so once we have stored all the elements in the mini what we can do is we just need to make a link list out of that so we will have a we will create a head and gradually we will make a new linked list node so this one will be the new link list then like basically we need to make a link list for this so i hope you know how to create a linked list for so this is how we'll create a link list so of kn will be the time complexity and space complexity will be off uh we are make we are using heap so of will be n is the total elements all the elements of these linked list so guys like as of now we have seen all the approaches which have time complexity kn right it's time complexity is gain so this is not optimized approach there is one more approach which is optimized and that time complexity will be uh n log k so that let's see how we can do that so in that also the last approach which we saw we were using heap and we were storing all the nodes of all these linked lists in the heap right so we will be using heap only mini hip only for this approach but there's slight difference what we will be doing see we will take a min we will have a min heap we have this mini hip but in mean earlier what we were doing we were storing all these linked list we were storing all these linked lists uh all these values of the link listener but here in this mini what we will do we will be storing only the head of the linked list only the head of the each linked list so we will be traversing on this k link list these are k link list we will be traversing and we'll be just storing the head of each linked list so minheep will have k elements why because they're k link list so k heads so k elements will be in the mean heap earlier there were all the elements were in the meaning earlier but now only k elements will be there in the mean heap so what we will do see what will be added in the mean heap one will be added then one will be added this is the one head and then two will be added so these are like addresses like these are addresses these like we are not adding the values we are adding the entire linked list node so this is a linked list note right this is a linked list node after that what we will do we have done this we have inserted the head of the linked list now what we will do is we will be creating a link list we will pop this element from the minihip we will make a link we will have a new head like new head we will have and we will be adding that we will like we will be creating a linked list right and since now there are two only two here so this one is popped out we will be now inserting its next element so this one was this one now four will be inserted so that is this one's next will be inserted in the min heap now so now our mini heap will be like this one node two node and this four node so every time guys see every time k elements will be there in the meaning we will be popping out the minimum element and its next element in the linked list we will be adding so now what will happen see one is in the link list now this one is popped out it gets inserted here and this one is next this one's next is what three is added in the mini so now our minip will be what two three four right now again what we will do we will pop this two add it and these this two is next what is this two's next six will be added in the menu so six will be added now what will happen 3 will be popped out because it's minimum and 3 is next is what 4 is added in the mean all right then what will happen see now this four will be popped out now this four you can take this also or this also any one you can take so four will be added here and fours next five will be added here so in this way see every time there are three nodes only in the mini so every time it has to arrange yet it has to do log k that is this much nodes k nodes every time here like mini path to arrange so log k will be that time complexity for that so uh now what will happen 4 will be popped out again 4 will be connected here and this 4 has no next node see it there is no next node now so nothing will be inserted here and then again 5 will be popped out 5 will be connected and this 5 also has nothing so nothing will be inserted in the min and lastly six will be popped out and our mini hip is now empty six will be connected so guys see every time what we are doing is we are uh popping out from the minip and every time we when we pop out we add the next node in the menu so right let's see the code for this approach i hope you understood this in this now the difference is between this approach and the previous mini heap approach that in that previous approach we were adding all the elements of all the linked list but here we are just adding the head of the link list so what we are doing is see we have this function merge k link list and we are like making this head and this temp so this is the dummy node we created we'll be returning heads next at the end you can that you cannot like if you do not want to make a dummy node you can avoid that then we are taking this temp and initializing it to head and this is a min heap we are creating now min heap see minip will now have the nodes these were the nodes now these are not the values lastly last approach we were adding the values so but here we are adding the nodes why nodes because we need to access that whatever node is being popped out we need to know its next so that's why we are having the nodes so uh this is a priority queue node star type and this is my compare function which will compare the nodes on the basis of their values so on the basis of this thing they will get arranged in the minip in the min heap they will get arranged using this property that's why we have passed this compare function all right then what we are doing we are going to each link list each the linked list and we are just if the head is not null we are just pushing that head in the priority queue and then we are what we are doing is we are going reversing the priority queue every time we pop the least element least node and we add it in the temps next and we move temp ahead and if the least node which is whichever is popped like here when two was popped so its next was six we added that in the link listener in the mean heap so if the least node which is the load which is popped has next like there is a next node after that so we will be adding that next node in the mean heap and lastly we'll be returning heads next so if you submit this is getting accepted java code will be in the description same code and over here see what will be the time complexity every time see we are iterating until the priority queue is not empty so there will be how many elements will come in the priority queue and n elements will be there always uh n times this loop will run because there are n elements because these are n so n elements will be there and how much time will be taken by priority q 2 every time arrange them will be log okay so time complexity will be n log k so for priority kits n log k and k y because every time there are k elements only in the priority queue meaning and space complexity will be o of k as we are storing this mean heap we have k elements every time so okay i hope you understood all the approaches guys very important problem and see we have discussed all the approaches i hope you understood the problem and the approach if you found the video helpful please like it subscribe to my channel and i'll see in the next video
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of `k` linked-lists `lists`, each linked-list is sorted in ascending order. _Merge all the linked-lists into one sorted linked-list and return it._ **Example 1:** **Input:** lists = \[\[1,4,5\],\[1,3,4\],\[2,6\]\] **Output:** \[1,1,2,3,4,4,5,6\] **Explanation:** The linked-lists are: \[ 1->4->5, 1->3->4, 2->6 \] merging them into one sorted list: 1->1->2->3->4->4->5->6 **Example 2:** **Input:** lists = \[\] **Output:** \[\] **Example 3:** **Input:** lists = \[\[\]\] **Output:** \[\] **Constraints:** * `k == lists.length` * `0 <= k <= 104` * `0 <= lists[i].length <= 500` * `-104 <= lists[i][j] <= 104` * `lists[i]` is sorted in **ascending order**. * The sum of `lists[i].length` will not exceed `104`.
null
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
21,264
215
hello guys welcome to my youtube channel and in this video i will be discussing the problem kth largest element in an array from lead code so let's first read the question given an integer array nums and integer k return the kth largest element in the array note that it is the kth largest element in sorted order not the clear the distinct element you must solve in off and time complexity so like here you can see the example nums three two one five six four and we have to tell the uh second largest element in this example one so second largest uh element is the fifth like suppose for example i have written the input in the degrees in order six five four three to one and the sixth position is the zero fifth is one so if i have to find the kth largest element so simply just i will minus k minus one so the value of k was 2 and minus 1 was 1 so the value at the one place would be the answer 5 is the answer so let's get into the code for better understandability we'll use the sort and creator and after that we will return the like i have said before the k minus one now check this code it runs perfectly now we have to submit the code so it runs successfully thank you you
Kth Largest Element in an Array
kth-largest-element-in-an-array
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element. You must solve it in `O(n)` time complexity. **Example 1:** **Input:** nums = \[3,2,1,5,6,4\], k = 2 **Output:** 5 **Example 2:** **Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4 **Output:** 4 **Constraints:** * `1 <= k <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
Medium
324,347,414,789,1014,2113,2204,2250
210
hey what's up guys in this video we are going to solve this little problem 201 uh course schedule number two so it's fairly similar to course category number one and uh but it's a little bit more than that so let's say uh the example in here uh number of courses digital two and so we have total two courses and uh that they are being uh cross zero and cross one and across zero is the prerequisite of course one so uh we did output the order in which we would be taking the course the courses so uh in this case as you can see we have to take uh course zero first and then take one because zero is the prerequisite of one and uh in this case uh example number two as you can see zero is the project of one zero is a paragraph of two and one is a prorack of three two is parallel three right so as you can see uh before taking anything we'll take care zero and then we're gonna take one and then we'll take uh two uh because in and then after that we can take three because two is a prerequisite three so three comes after two at the same time and one is a prerequisite regressor of three so we have picked one and two first before we're taking three right and also another correct answer could be uh zero one and two and three right because one and two they don't depend on each other so this is example number two and example number three is a trivial case and just only one course and there's no prerequisite to take that course um yeah so and this question was asked by uh well it's a very famous question uh from popular question um so amazon and google microsoft and speak names love this question obviously so let's uh solve this q question together so we first need some prep work we need a prerequisite dictionary and so the key being the course number and then i have an empty list to start off because um each of the i mean the list will be including all the prerequisites associated for that course and then after that we just filled up uh this dictionary by using this one so we look into all the prerequisites and each one is like is a list so this is a list of a list and each of the lists will be the course and also the prerequisite for that course and then we will append that to the list associated with that course right so it's just some uh preparation work and then after that we will do a dfs and that will be going through each of the courses and uh yeah we will do that together and uh we need to help us set up for us so one is attacking so basically keep track of what course we are currently taking and also another one is a cycle so basically we use this to detect any cycle in the courses so for example if the prerequisite list looks like this um let me show it to you what i mean by cycle it looks like this um sorry about that yeah so as you can see uh core zero is a prerequisite of course one at the same time cross one is a prerequisite per car zero so we can see a cycle so there's no way we can do that because we have to take one and then and take the other one first but the other one is also prerequisite of this one so you can see uh it's conjugated that's why i whenever there's a cycle we have to act accept from this uh function and return a false okay so that's why we need to cycle set and this if statement helps us to do exactly that and sorry so that the name of that first set should not be taking i should be completed so keep track of what course has been completed at that point so uh if that course in the completed set and we will return a true and this will be very helpful when we keep track of all the prerequisites if we see that all the prerequisites has been completed each one of the records have been completed and we're good to taking that particular course right and when we are doing the dfs oh sorry it should be dfs and we will temporarily add that course to the cycle and then at the end after we put into all the prerequisites we will remove it from the cycle and then now the problem comes from what we need to do is to fill up fill out the things in between where we will uh do all the prerequisites and do dfs on the prerequisite right so as you can see uh this is how we can do dfs on all the prerequisite natures we're using and this is why we need that our list in the dictionary and this is exactly how we can do a dfs if this guy returns a false and what it means is uh we detect a cycle and this automatically return across there's no way we can uh complete like this because there's no way to complete all the courses if there is a cycle that's why we return the false and also after we finish all the prerequisite and then we will finish the course itself right so uh in that case the completed set we can add that at that particular course after we're adding all the prerequisites and then we add in that particular course right because uh when we call the prerequisite it's already they are already in the completed set and also at the same time uh we can do oh we can we get a penalty answer uh which we will return at the end so again before appending that course we already append all the prerequisites already right and uh after that um if so if uh this if there's no prerequisite returning and false and that means that we finish all the prerequisites and of course itself and in that case we don't chew okay so uh that is basically it for the dfs function and next step is going to just trigger running so for the course in so this is uh this is how we can um run dfs through all the courses and if and this guy returns a false that means there's no way to complete all the courses and just return it onto this in other otherwise we return answer sorry i found a typo in here i need to put a range in there and uh because otherwise i it doesn't look through all the possible courses and let's run it works and let's submit it oops hopefully perfect um it runs it's pretty efficient as you can see yeah so this approach by using dfs and in terms of time complexity is a b or v plus e and this is from the official solution and v being the number of vertex and then e is being a number of edges so basically uh so it's always essentially we iterate through each node and which vertex in the graph ones and only ones so basically saying um is the v being the number of courses and e is being number of the prerequisite relationship um because we only do it once and because never do it again because there is this complete set so as soon as we look at one particular course and we look at all the prerequisites of the of that course and also the prerequisite of the prerequisite so it's like a chain it looks back all the way to the origin which um has no more prerequisites so that's why we only work on the graph ones and only once for the space complexity uh as you can see we need a completed set also a cycle set so um i would say the completed set is a big over number of courses right we keep track of how many courses we have we are completing along the way and also the cycle uh would be the number of relationships uh prerequisite relationship so uh this is basically the v plus e so it says we use the adjacency list to represent our graph initially and the space occupied is defined by number of edges because for each node as the key and we have all the adjacent nodes in the form of a list as a variances yeah so this is basically what we just said right um okay so this is so much about this solution i hope you like it uh if you do please like this video and subscribe to channel and that will be much great help to grow this channel and um yeah hopefully i will see you next video thank you for watching
Course Schedule II
course-schedule-ii
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`. * For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`. Return _the ordering of courses you should take to finish all courses_. If there are many valid answers, return **any** of them. If it is impossible to finish all courses, return **an empty array**. **Example 1:** **Input:** numCourses = 2, prerequisites = \[\[1,0\]\] **Output:** \[0,1\] **Explanation:** There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is \[0,1\]. **Example 2:** **Input:** numCourses = 4, prerequisites = \[\[1,0\],\[2,0\],\[3,1\],\[3,2\]\] **Output:** \[0,2,1,3\] **Explanation:** There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is \[0,1,2,3\]. Another correct ordering is \[0,2,1,3\]. **Example 3:** **Input:** numCourses = 1, prerequisites = \[\] **Output:** \[0\] **Constraints:** * `1 <= numCourses <= 2000` * `0 <= prerequisites.length <= numCourses * (numCourses - 1)` * `prerequisites[i].length == 2` * `0 <= ai, bi < numCourses` * `ai != bi` * All the pairs `[ai, bi]` are **distinct**.
This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
Depth-First Search,Breadth-First Search,Graph,Topological Sort
Medium
207,269,310,444,630,1101,2220
836
hey how's it going guys today we're going to be liquidating the rectangle overlap question so a rectangle is represented as a list x1 y1 x2 y2 x1 y1 are the coordinates of its bottom left corner and x2y2 are the coordinates of its top right corner two rectangle overlap if the area of their intersection is positive so to be clear to rectangle that only touch at the corner or edges do not overlap so if our input is two rectangles um and return whether they overlap or not so let me draw a little bit so let's see if this is rectangle one right and uh we got x1 y1 here uh the bottom left corner um here we got x2 y2 here right and suppose there is like a rectangle that is like overlapping how do we determine if um just according to the coordinates whether they are overlapping or if they are like for example like this um they are not overlapping right how do we determine this so if you think about how to determine the intersection it can be really kind of like difficult because well you have to say well like uh maybe like right what if like a rectangle one is uh to the left of rectangle two and what if it's like to the right and it's like becoming really complicated um so there is another way which is to determine how two rectangles do not overlap and if we can know um the condition that they do not overlap we can just like so for example like if in the uh some condition they do not overlap we just return false right and if those conditions do not satisfied they just return true so in for this question we are going to actually figure out in what conditions they do not overlap okay and um then it becomes like quite easy because for two rectangles um for them to be not overlapping to each other they are just basically either um the rectangle 2 is to the left um uh to the uh rectangle one or to the right or um to like uh which is like i think above rectangle one or under rectangle one right those are the four conditions so if for example if uh rectangle two is to the left of rectangle one so no matter like regular tango two can be like anywhere to the left right it can be anywhere like no matter how up or how done or how left rectangle two is it is not going to overlap with uh rectangle one right um similarly if rectangle two is to the right no matter how rectangles to like moves it won't overlap with rectangle one and the same goes to the rectangle above it or below it okay once we know that um we can write uh our codes because for example to make rectangle 2 left to rectangle 1 we just remember this is the x 2 y 2 right so we just have to make x 2 less or equal to x 1 right less or equal to equal is because in our uh question it asks it says that if two rectangles only touch the corner or edges they do not overlap so if they there is a rectangle to here it only touch the edges they do not overlap okay so let's code it up uh so first of all let's write uh the left one so let me if in this conditions uh return false right as else we just return to right so we have to first of all write the left so for this condition uh x2 rectangle so rack twos x2 you
Rectangle Overlap
race-car
An axis-aligned rectangle is represented as a list `[x1, y1, x2, y2]`, where `(x1, y1)` is the coordinate of its bottom-left corner, and `(x2, y2)` is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles overlap if the area of their intersection is **positive**. To be clear, two rectangles that only touch at the corner or edges do not overlap. Given two axis-aligned rectangles `rec1` and `rec2`, return `true` _if they overlap, otherwise return_ `false`. **Example 1:** **Input:** rec1 = \[0,0,2,2\], rec2 = \[1,1,3,3\] **Output:** true **Example 2:** **Input:** rec1 = \[0,0,1,1\], rec2 = \[1,0,2,1\] **Output:** false **Example 3:** **Input:** rec1 = \[0,0,1,1\], rec2 = \[2,2,3,3\] **Output:** false **Constraints:** * `rec1.length == 4` * `rec2.length == 4` * `-109 <= rec1[i], rec2[i] <= 109` * `rec1` and `rec2` represent a valid rectangle with a non-zero area.
null
Dynamic Programming
Hard
null
455
hello everyone this is sham Chi welcome to the very first video on our YouTube channel as we embark on this exciting journey together I want to extend heartfelt wishes for fantastic new year filled with growth and success for those of you who are new here this is growth with SH where we explore the fascinating world of programming and problem solving whether you are beginner or an experienced coder you are here to learn and grow together to kick off our coding Journey we are delving into an interesting problem known as the cookie distribution problem this is a great example to Showcase problem solving skills and algorithmic thinking making it an ideal starting point of our channel before we dive into the solution let's understand the problem statement we have a group of children each with a minimum Gade factor for the size of the cookie they desire on the other hand we have a set of cookies with different sizes the task is to distribute the cookies to the children in a way that maximizes the contentment the key to solving this problem lies in sorting both the great factors and cookie sizes in asscending order we then iterate through the lists assigning cookies to Children based on their grid factors and the available cookie sizes before we dive into the code I want to express my sincere thanks for joining us on this journey your support means the word to me as we step into the step in the new year I have exciting plans for this channel in addition to more coding challenges get ready for the problem of the day series featuring lit code g plus we will be working on weekly web development projects using month time now we will code for this question first we will declare a grid size variable grid size to G do size using this function we will get size and we will declare children size what is the cookie size Okay cookie size equals to S do size then we will if check we will make a condition of if first time for cookie size to be zero cookie size if cookie size equals to zero return false or zero then we will sort both the arrays using sort function passing arguments as G do begin and g. end as parameters sort s. beginning s. end now we will create a new variable called Maxum and assign it to zero we will return this Maxum as our final output next we will create uh two indexes for cookie array C index assign this value as cookie size minus one then second is grid index GD size minus one after that we will apply while pass the condition as cookie index greater than equal to Z and grid index greater than equal to Z now add a statement for checking the cookies cookie index of in variable is greater than equal to Green index uh C G value if cookie index of s variable s is greater than equal to grade index in G IND index now if this is true then increment the count of Maximum also increment cooky index and sorry we want to decrement the cookie index also grid index we will decrement the grid index and if this is false then only we will decrement the grid index at last we will return our maximum okay we will run this okay the sample test cases are running well let's submit the code to check hidden test cases Yeah the code ran successfully here the time complexity is dominated by the Sorting step resulting in bigo of and login time complexity the space complexity is bigger of one since we don't use an ADD addition data structures in conclusion the co cookie distribution problem is a fantastic starting point for on oning our coding skills I invite you to engage with the contest share your thoughts and join our coding Community as we navigate the world of algorithms and web development let's learn grow and have fun together if you enjoyed the video or found it helpful don't forget to hit the like button and subscribe for more content your feedback and engagement are crucial as we build this community stay tuned for upcoming code problem of the day videos and exciting months Tech web development projects happy coding and let's make this year a fantastic one together thank you
Assign Cookies
assign-cookies
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number. **Example 1:** **Input:** g = \[1,2,3\], s = \[1,1\] **Output:** 1 **Explanation:** You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. **Example 2:** **Input:** g = \[1,2\], s = \[1,2,3\] **Output:** 2 **Explanation:** You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. **Constraints:** * `1 <= g.length <= 3 * 104` * `0 <= s.length <= 3 * 104` * `1 <= g[i], s[j] <= 231 - 1`
null
Array,Greedy,Sorting
Easy
null
847
hey everybody this is larry this is day 26 of the league code daily challenge hit the like button hit the subscribe button join me on discord let me know what you think um yeah i miss you let me uh you know if you're not a new viewer you know that i usually start with a little bit of uh just i don't know anything really um update about life i guess um and today i wanna you know there is a lot of things going on in the world um i want to you know uh what can an idiot like me do right in the middle of uh right now in medellin but and just being american and stuff i don't know right but uh i guess the one thing that i can do is just give a little bit back and yeah um i'm doing a donation match up to a thousand dollars i know it's not you know a lot or whatever but it's uh you know it's something i hope uh and yeah and i also want you know people to kind of hopefully help out um you know come to the discord on my instagram send me your receipts and i'll match um some small amount you know every bit helps just a couple of bucks just to show people that we care and you know support and stuff like that um yeah let me know uh come to discord and just chat about it as well uh the world's been crazy and sometimes you do what you can right um anyway okay uh especially if you enjoy my channel you know maybe once or twice you know uh and you find yourself in a maybe fortunate place fortunate enough to get back a little you know uh discounted as a you know i never i've never asked anyone for money on this channel and i never will because i don't know because i because my opinion about that is that um you know i'm a decent software engineer and i can just have a job right and if you look up on a lot of different job software engineering job websites or like you know the salary websites i guess is what i'm trying to say um and if you look for those um you can kind of make good money without like you know uh convincing people to send you money on the internet you know like it's a good career um it's a very comfortable career so i would never ask you money as far as i know i mean unless i don't know i guess the world is a i don't know things can really go wrong but um so yeah so but i do uh and you know i hope that you do get into a fortunate place where you can give back whenever you can and that's always what i ever ask is you know um two things one is you know just some it doesn't have to be a big amount of dollar or two i know a lot of my viewers are college students or new grads or you know they might be in a country where um just like the income is not as lucky as it is in uh in the us or so um and yeah and uh and the other thing i always ask is just you know pay it forward right like would you find it helpful um answer a question that someone may ask in the future and try to be patient because i'm at that point i'm not a 100 either as well but uh but yeah um right thanks uh devoted excuse me uh yeah the world's in the crazy place i hope you all are doing okay and i hope that um you know our friends and families in ukraine um i don't know right just make it through it um and yeah okay i know i this is a long thing i haven't gotten to the prom yet uh thank you for kind of watching um i don't know it is i'm not gonna lie sometimes it feels like you know like what's the point of these stuff right so yeah okay so let's actually focus a little bit uh let me try to get back here as well um yeah so yeah follow me on instagram uh i post a little bit of details there and discord which is there just a lot of smart people there so also great for helping as well but uh but yeah uh so today's problem is shortest path visiting or nodes okay you have an undirected connected graph of n nodes labeling 0 to n minus 1 you're given an array graph where graphs of i is a list of okay so basically you're giving an adjacency list uh okay return the link the shortest path that visits every node you don't have to return the actual path right oh you may reuse edges okay oh okay this is kind of a silly problem because i would initially i was like okay well there are a couple of things right there's um just knowing the literature i think that's the tough part about some of these problems is knowing the literature and what i mean by that is that if you and not everyone has the computer science background but and i'm not trying to suggest that per se because you have to start somewhere and you know um but that said knowing the literature means in this case what i mean anyway is knowing what um what type of problems are mp complete what type of problems are mp hard and because as soon as you do that then you're able to recognize that okay there's no optimal solution if in the general case right so you could do one of two things one is see if there's some weird property of the problem that allows you to be like okay i know this is maybe hemp cycle for example or something like that but not this one but i just mean like looking in another form you'd be like okay this may be hemp cycle oh no but that you can only do this other thing because there's this constraint so therefore it's not ham cycle and i could do it in um you know not in polynomial time or something like that right um but that's one two is um yeah and then two is that you know you just in real life what people usually say is either you try to find maybe some sort of randomized algorithm or an approximation algorithm right because you know it's mp complete or mp hard depending on what you're doing that means that you don't have to waste time anymore to figure out a polynomial solution because none exists unless n equals np but yeah for the purpose of uh our sanity let's just say that you're probably not going to find a polynomial one though if you do let me know and uh we'll uh talk it together and then uh maybe share that price and also uh destroy everything that depends on and you go or np anyway though right so uh that's a little bit of a calm side joke if you know okay fine it's not a big deal um but yeah so this one i knew that it was going to be very one of those hard ones i actually don't remember so i accidentally scrolled down to be honest um and i saw that n is equal to 12 right and n is equal to 12 um is doable for np complete problems obviously because you can just prove force in a smart way um and that's all you are all you're trying to do i guess right but yeah and yeah so that's basically the idea um let's see return the link with the shortest path that we should do no mistake and stop it let me know okay so yeah so i mean a couple of ways to represent the states um that part is i'm trying to think about it matters but basically the states that i would kind of think about is maybe something like this where okay so um let's say let's go to visit it's a lame name but basically the co um the current uh node right so let's just say node um okay so i just want to make sure that all the or the numbers are from 1 to 12 or something right graphs of i just like okay so there's no internal uh it's uh symmetric and um i just want to see where graph sub i is they don't actually say uh maybe they mean it but i it doesn't actually say that graphs of i is um or each note each element of graph is between 1 to 12 and it's between the 12. the length is between 1 to 12 but it doesn't actually say that the inputs themselves so in theory if you want to generalize you could use a key but i'm just going to assume that this is going to be from 0 to 12 or 1 to 12. so it seems like from 0 to 11 i guess right um we'll see if that assumption holds so node will be the current node which is from 0 to 11 say right inclusive and then we want to do something like a bit mask uh or visit it right so let's just say resident so i do have a lot of i get a lot of questions about what it is a bit mask i'll try to do a little bit of a job here though um i think i'm not going to dwell too much on it so if there's some confusion here i leave it in the comments or leave it on the discord and we'll work for it but the way that i would think about it is that i explain always is that a bit mask is really not that confusing per se so let's say we have um let's say we have visited is equal to a boolean array right so that boolean array is going to have like four is true false and of course true right let's just say the sixth element or yeah that's six elements and then of course to write it slightly easier you could maybe compress it to a string right what does it look like as a string well it could look like f t right um and then another way of writing it is okay instead of writing f and t's you could write zero and ones right now you have zero one and then another way to say that of course is to say okay instead of using a string you just use a number right so now this is a binary number that's this and then another way that you could say is that okay now we have binary number what is this as a number right i have to do the math this one though uh this is one plus two so that's three four eight sixteen so nineteen right so that's basically what a bit mask is right so that is basically there's some boolean away um that you convert to a number and that's basically how you do it and then a couple of operations i'll show it when it comes up but that's basically the idea um for this problem um i'm not go i'm because i actually do want to get somewhere uh today or tonight so i will use this thing that is in private called cash but we will still go over the complexity so you cannot use it or one thing that i always tell people is that you should not use it unless you really understand how complexity works with dynamic programming and memorization um i mean you can obviously i'm not gonna police you but you shouldn't because that's when you run into trouble and you ask but i add cash how why is this still tlu i'm like well because you don't really understand it right okay so then let's go over the end states right um so what do we want the end state to be right well if visited is equal to two to true then we end right so that basically if where is it is you go two so and this of course it goes to one and one which is equal to um uh one times n kind of roughly speaking i mean obviously this is not um this is not the notation but i'm just you know wishing well and of course this is uh if you look at this number and you may see this sometimes right it's gonna be uh something like this right minus one so that so if you see this in other people's code that's basically the logic and basically the reason right it's just basically this uh n plus one minus one right so um yeah so and this is you go to one shifted n times to the left so yeah so that's basically if this is equal to do minus one then we this is good right so we return zero because we visited every node that's basically the idea let me think about this for a second i want to make sure that i'm a little bit careful because i think you can do it in a way such that you can have infinite looping back and forth and there are ways you can make it so that doesn't happen or harder to happen but um but for now i am going to um do it in another way which is because basically you can just do look at all the intermediate neighbors right you could be like okay one is neighbors or in this case example one is connected to uh let's see uh one is connected to oh sorry zero is connected one two three so you could be like okay zero let's go one two and 3 and then 0 could go to 2 can go zero and then 0 and that's where you're going to infinite loop right but another way of writing it is that you can only go to an unvisited node with an undetermined uh distance what i mean by that is that let's say you start at zero you go to two and then from two you wanna go to one or three because you already visited zero right of course this is two going to one i'm looking here again two going to one will have an edge rate of two right so that's basically the idea is that generating an alternate graph where that's the case and of course that's not that hard per se we just have to do it and i'm gonna try to um okay so let's put this ahead a little bit and then we'll use uh freud warsaw's algorithm there are other ways to do it of course but i'm a big fan of voids so let's go so distance is equal to let's just say infinity uh times and for to do right so now we have an n by n um n by n uh distance matrix right and it's infinity so of course the first thing you write and now we pause the input graph so now for edges in graph uh let's enumerate this as well uh what did i press so yeah so for node i so then now we go distance of i of uh well that's actually oops for edge in edges uh distance of i of h is equal to one right so that sets it up uh i think we should also do i don't think this matters maybe not for this one anyway but it's just my the convention that i'm usually doing and that's um this is a compelling reason why uh that's not the case right so that's basically um yeah that's basically what i'm going to do here um yep um and then now this allows us to go from okay let's say for i and range of n right and then we ask ourselves okay if visited of i of course that's not the notation because as we said uh there might be actually no that's good i think um so if visited was a billion in a way that's what we would do right if this is not resident whoops so if this is not visited we go visit it right so we visit it right so that's basically what we do but of course we're dealing with a bit mask and a bit mask as we said it's going to be like you know some number one zero something like that right and then the idea here is checking whether the i fit is a one so the way that we do that is just um take a number that's left shifted by i um and then see if that's a one right and that's basically the idea of getting this bit mask is if um let's see um one shifted by i if we end this with division it right if we end this in is equal to zero that means that this is not visited because if you add these two numbers for example um oops it'll be a it'll be non-zero if we one it'll be a it'll be non-zero if we one it'll be a it'll be non-zero if we one shifted whatever but if you had shifted here um then this would just be a zero right so then that's why this is checking to see if it's unvisited there are of course other ways to write it but that's the way that i'm explaining it and writing it so um because you know it's but all of them have the same logic it's just different um different way of writing it right so yeah um okay so then now if that's not the case then uh oh i have to do the best is you go to infinity i didn't set infinity actually so i just that's just a big number it doesn't really matter um because this is connected so you always get an answer that's like i don't know what is the worst case answer like n times two maybe something like that if you look if you visited every edge twice maybe um i don't know if that's true but by the way if you choose a big enough number it should be okay um okay so if that's not the case then best is to go to min of best uh we visit just note i we toggle this node um all right and then we add that by the distance so now this is the distance from node to i right hopefully that makes sense i think the only part that's confusing especially if you haven't done bit mask is this one but basically this is same thing as here right so we know that this overlap is zero so that means that you all those two together then this one will make this a one and when you do the recursion right so that's basically the idea and of course the cost of that node is all this stuff cluster plus the distance and then at the very end we just return best of course this is not memorized but let's take a look um but of course and also this is assuming that um some stuff which we have to go right so then now outside we start again um because we want to um we want to be able to start from every node to see what's best so we should do that so for i is range of n let's say we go we visit um i and then visit it right i guess technically you gotta kick off like negative one or something weird but this is probably a little bit cleaner um and that should be good even if it's a little bit slow let's actually run the test cases to see if we at least have the right answer um we might time out oh do i have a typo somewhere oh is this not visited oh yeah because that should be just zero so you should kick it off with one note being visited um okay so we're wrong here that's a little bit awkward maybe i did something weird um oh i have to update this though actually um oh i'm dumb sorry friends what i forgot to do is i mean i constructed this but then and i talked about it but i forgot to actually code it uh which is the foid wall show part right so uh so that's what we're gonna do so here we go for uh k in range of n will i in range of n for j in range of n uh distance of i j did i mix this up no i think this is okay it goes min of this i j uh or d sub i okay and this is just void washer right let me write it up so you could google if you like okay now hopefully this should be good and that makes sense because it would run out of loops anyway okay so this is right but obviously too slow so we the thing we want to do is memorize this um i'm a little bit lazy on this one today uh to be honest hopefully this is already a good enough explanation so but i will analyze it to know that this is fast enough of course if you had um if you're doing it for a contest or even an interview you would analyze it first otherwise you wouldn't implement something too slow in this case note is from 1 to 12 or 0 to 11 i guess actually but this is 12 or o of n um and then visit it as you know this can be for every i bit it has could be zero 1 so this is actually o of 2 to the n or 2 to the 12 in the worst case um so that's the number of possible inputs right for each input um so yeah let me write that first so possible input is equal to o of n times two to the n and then now each input text uh each input will do an end loop so that means that each input will take off and time so then um possible the time uh total time is o of um n squared times 2 to the n and of course oops what and of course possible total space is o of um n times two to the n because now this is time over one space right because we're just throwing it away and that's basically what cache does kind of uh let's just say it does um and yeah and of course this is also linear but each chord is going to be over one so this is just linear then that's why we don't mention it um here then let's get you know some uh one on the code real quick it looks okay let's give it some minute and hopefully that's okay and we don't have any typos or silliness uh if it is that's fine too we can fix oh i didn't see plus last time that's interesting uh yeah so we did finish it yay we did bit mask dynamic programming uh hopefully this is a good one it's a 697 day streak that's good too uh that's all i have for this one um yeah we already did the complexity curious what i did last time did i do it recursively uh i did do it recursively okay i did do the fourth warsaw as well so yeah okay cool i don't think i have anything else to say about this one so um i urge you to you know take care of yourself take care of others if you have the opportunity to um stay good stay healthy to go mental health and um and yeah to you know good luck to all our um ukrainian uh friends and family you know anyway see ya
Shortest Path Visiting All Nodes
shortest-path-visiting-all-nodes
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge. Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges. **Example 1:** **Input:** graph = \[\[1,2,3\],\[0\],\[0\],\[0\]\] **Output:** 4 **Explanation:** One possible path is \[1,0,2,0,3\] **Example 2:** **Input:** graph = \[\[1\],\[0,2,4\],\[1,3,4\],\[2\],\[1,2\]\] **Output:** 4 **Explanation:** One possible path is \[0,1,4,2,3\] **Constraints:** * `n == graph.length` * `1 <= n <= 12` * `0 <= graph[i].length < n` * `graph[i]` does not contain `i`. * If `graph[a]` contains `b`, then `graph[b]` contains `a`. * The input graph is always connected.
null
null
Hard
null
13
Hello Guys Welcome Chalkar Times Deals In This Video You Will See The Question Romantic When Roman Numerals Are Represented By Different Symbols And Rules While Writing Roman Number Largest From Left To Right Away For Not Return Gift Item Number One subscribe And subscribe The Amazing Main Iso Mapping Choose the symbol with number Let's see how they can solve question What is the value of element Last character Subscribe Result for example from this Is the value of the character Must subscribe this channel That Aayi Wah Leaf Vwe New Fight End 105 pages - 04 somi update result throw was great value for which gives no value of the subscribe result will be doing now finally no result particular question well 152 under mapping for this symbol and value ka map android app loot the meaning tomorrow morning you will have added All the se value hindi map now will start with result variable value response to the last character of district on om namo will read overdue string starting from the second last which happened in 10 minutes to compare values ​​for in 10 minutes to compare values ​​for in 10 minutes to compare values ​​for character and the highest position and i Plus one position on I am India I am the velvet is listed and evaluate I plus one position and extraction from result hua tha this time brother I video edition so second within 20% I video edition so second within 20% I video edition so second within 20% test change to edition Softwares for all and mid term result select friends To Oil Test Cases The Latest Tiranga Perfect Result Flats Apartments Code To Turn WhatsApp Message Sumeet Time Complexity After And 10 Particular Pro Things After And Administrative Those For Values ​​And Administrative Those For Values ​​And Administrative Those For Values ​​And All The Characters In The String And Space Complexities We Just Need To Stories Say Values ​​And Details Contact us, please Values ​​And Details Contact us, please Values ​​And Details Contact us, please like the videos of these commissions that have been caught safely by LIC Hanuman Children Planning.
Roman to Integer
roman-to-integer
Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. **Symbol** **Value** I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, `2` is written as `II` in Roman numeral, just two ones added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: * `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. * `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. * `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. Given a roman numeral, convert it to an integer. **Example 1:** **Input:** s = "III " **Output:** 3 **Explanation:** III = 3. **Example 2:** **Input:** s = "LVIII " **Output:** 58 **Explanation:** L = 50, V= 5, III = 3. **Example 3:** **Input:** s = "MCMXCIV " **Output:** 1994 **Explanation:** M = 1000, CM = 900, XC = 90 and IV = 4. **Constraints:** * `1 <= s.length <= 15` * `s` contains only the characters `('I', 'V', 'X', 'L', 'C', 'D', 'M')`. * It is **guaranteed** that `s` is a valid roman numeral in the range `[1, 3999]`.
Problem is simpler to solve by working the string from back to front and using a map.
Hash Table,Math,String
Easy
12
59
we are given a positive integer n and we need to return a matrix of n rows and N columns filled with the first n Square integers in a spiral order for example if n equal to 3 then we have n Square equal to 9 and therefore this is the Matrix we need to return before continuing you may watch this previous video for a better understanding let's say we are given n equal to 3 so first we will be creating an empty Matrix of 3 rows and three columns also we should have a counter for generating the first n Square integers to be filled in The Matrix we will initially set the counter to 1. we will now Traverse through the metrics starting from the first cell 0. we will set the counter value to this particular cell and we will increment the counter from this cell we will be moving in the right direction for that we will be adding the direction indexes 0 and 1 respectively to the cell indices we will continue the traversal and after reaching the cell 3 we cannot move forward because the next cell is out of The Matrix so we will take a right turn from this particular cell and therefore we will be moving downwards for that we will be adding the direction indices 1 and 0 respectively to the cell indices we will continue the traversal and after reaching the cell 5 we cannot move forward because the next cell is out of the Matrix so we need to take a right turn from the cell and therefore we will start moving in the left direction for that now we will be adding the direction indices 0 and minus 1 to the cell indices we will continue the traversal and after reaching the cell 7 we cannot move forward because the next cell is out of the Matrix so we need to take a right turn from this particular cell and therefore we will be changing our Direction upwards now we'll be adding the direction indices -1 and 0 be adding the direction indices -1 and 0 be adding the direction indices -1 and 0 respectively to the cell indices now from cell 8 we cannot move forward because the next cell is already used and we need an empty cell to set the counter values so again we will take a right turn from here now from cell 9 we cannot move forward because the next cell is already used so we will take a right turn again from this cell but even after taking a right turn we cannot find an empty cell here that means we have completely used up the metric cells and therefore this is the final result now let's call the solution first we will create an empty Matrix of n rows and N columns initially all the cells will be containing the value none since we need to start the traversal from the first cell 0 we will set I and J to 0 initially also we will be moving in the right direction initially therefore we will be setting the direction i n Direction J to 0 and 1 respectively for filling up the Matrix with n Square values we will use a counter with the starting number one we will use an infinite while loop to Traverse through the Matrix in the current cell we will set the counter value foreign we will store the next I index and J index in these variables now to check whether the indices are inside the Matrix and the cell is not yet used we will write a separate function if the cell indices are inside the Matrix and not yet used then we will update the inj to the next indices else we will take a right turn and add the direction indices to the cell indices I and J foreign if the suddenly disses are not inside the Matrix and unused then we have already completed filling the Matrix and therefore we can terminate the program now let's try running the program it's working see you in the next video
Spiral Matrix II
spiral-matrix-ii
Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order. **Example 1:** **Input:** n = 3 **Output:** \[\[1,2,3\],\[8,9,4\],\[7,6,5\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 20`
null
Array,Matrix,Simulation
Medium
54,921
332
Hello Guys Welcome To Gautam Samay DC Today We Will Go Through The Dates Problem From June Recording Challenge Reconstructed Very Please Like This Video Fuel forget to subscribe our Channel Sugriv Never Miss Any Update Your Laptop Airline Tickets Are Presented A Foot After Departure Don't Forget Reports From * Reconsider In Order To Avoid You To The Man Who * Reconsider In Order To Avoid You To The Man Who * Reconsider In Order To Avoid You To The Man Who Departed From Chief Pims Begin With GF During Then Note Step To The Problem Here Multiple Valid Reasons You Should Begin The Redressal Smallest Lexical Order Venerated As A Single String All At Airport Represented By Three Capital Letters Zoom In Zoom And Tickets From At Least One Veterinary One Must Have Used Oil Certificate One And Only Once Given Two Examples Of Play List Example And Hanging House Without Poached Eggs Error In Totally Free Appointment And Regret Not From 9 To Be Connected With A pension input now let's start building battery e will also have reduced to keep the final battery acid will start from jeb k will take dead thousand starting point no exact k into the result least now from gfk we can either go to airtel and f4 increased the question Clearly mentioned result has been in lexical order will go to airtel and the same in result again they have two options show will go to z k navodaya recent visitors notes from gfk subah 264 and went to t&amp;c the 264 and went to t&amp;c the 264 and went to t&amp;c the indian 2f again they have used all the tickets or vacancy Travels and the Apps Sudesh Begum Kar Final Result No Let's See How to Solve at Co Device Will Force Ne Slider Has Time with Source List of All Destinations From Shoes Value The Map Looks Like This Nonveg Unobtrusive Result to Electrical and Double Shortage List After Stopping Thum happy look like this no will to sensitize the result list ki aisa itni himmat start from jio app hai absolutely no method don't MB calling naseem mein additional shivling no vacancy they rich destination from death k bade govinda want to absolutely order will take it and author Unless I am also they will remove the elephant and less talk Chief's is a novel method in first beneficial giving job's nine only have value absolutely the method does not know the value from Delhi staff and will continue to reconcile equal the method oil bank water resources With no value on name s be richest source with no destination to visit villages or into the result and distorted action will be taken to previous mode not have any discrimination in the world in the results for the way will not let the same time It into a that sbi bank tractor initial method and gf vouchers don't have any unwanted note loop we editing or last and returns as a new delhi approach battery for its called rogers algorithm the basic idea of hair oil sir garm is f5 construction of The Urine Cycle Pred This Cycles To Be More Specific Oil Hot Consists Of Two Steps It's There And Not And Flows In Army Trees And Vegetables To Ne Bigg Boss Steps Repeated And 122 Steps That Include A Series Of And Cycles Under Graph Avadhesh Cycle Cover All Notes At assuring cycles and algorithms for ministers rs1000 cycle stand with animated images and construct another cycle to whatsapp tour in this question as closed setting note clearly format and find the urine thing using her shoulders algorithm that time complexities of multiple dialogues by brother deepesh Complexities That Of We Plus That Number Of Flight And More Number And Roots That Hair Pack Record Se Pattern Tomato And Share A Link With Java Coding Description Bills That Thanks For Watching The Video Flag Video Please Like Share And Subscribe Our Channel Latin American Fashion Model Think About The Video
Reconstruct Itinerary
reconstruct-itinerary
You are given a list of airline `tickets` where `tickets[i] = [fromi, toi]` represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from `"JFK "`, thus, the itinerary must begin with `"JFK "`. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. * For example, the itinerary `[ "JFK ", "LGA "]` has a smaller lexical order than `[ "JFK ", "LGB "]`. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. **Example 1:** **Input:** tickets = \[\[ "MUC ", "LHR "\],\[ "JFK ", "MUC "\],\[ "SFO ", "SJC "\],\[ "LHR ", "SFO "\]\] **Output:** \[ "JFK ", "MUC ", "LHR ", "SFO ", "SJC "\] **Example 2:** **Input:** tickets = \[\[ "JFK ", "SFO "\],\[ "JFK ", "ATL "\],\[ "SFO ", "ATL "\],\[ "ATL ", "JFK "\],\[ "ATL ", "SFO "\]\] **Output:** \[ "JFK ", "ATL ", "JFK ", "SFO ", "ATL ", "SFO "\] **Explanation:** Another possible reconstruction is \[ "JFK ", "SFO ", "ATL ", "JFK ", "ATL ", "SFO "\] but it is larger in lexical order. **Constraints:** * `1 <= tickets.length <= 300` * `tickets[i].length == 2` * `fromi.length == 3` * `toi.length == 3` * `fromi` and `toi` consist of uppercase English letters. * `fromi != toi`
null
Depth-First Search,Graph,Eulerian Circuit
Hard
2051,2201
700
hey what's up guys it's Nick Dwight I do tech and coding stuff on twitch and YouTube and I do all the weaker problems so I have a channel YouTube channel yeah a YouTube channel with a playlist with like 50 of them so far and we're gonna keep doing them ten a day or something like that until we do them all so check those out yeah everything else in the description this one's super easy it's gonna be a couple minutes only search in a binary tree just traversing a binary tree and looking for a node super easy you can do depth-first search you do you can do depth-first search you do you can do depth-first search you do breadth-first search in or a pre-order breadth-first search in or a pre-order breadth-first search in or a pre-order post order traversal so you can just do level orders for any traversal in traverse the tree you check each node and if obviously what we're gonna do let's just read a real quick given a roof value of a binary tree and a value need to find the node in the binary search tree that the nodes value comes to give them value return the subtree rooted with that node if such node doesn't exist for turned off so we're just returning the node we're doing recursive calls on the left and right children until we find this is the main condition if rooftop Val equals Val return root that's it super easy and obviously this is always at the top if we're equals null and then what do we have to do what's the only hard part of this is how we're going to recurse and search the rest of the tree so if we have the value we return the root returning which returns a subtree don't get confused by returning the sub for you just return the root of the subtree and return to so would just refer to the value that we're looking for sorry I'm in a library and there's people talking so first of all if val is less than root dot val so we're on we search on the current node and if the values on the left side well I don't know if you guys know how binary search trees work but smaller values are on the Left greater values are on the right so if the value that we're looking for is be less than the current value we're gonna go to the left so what to do is recurse on the left side search BST i'm we've got left with the same value that we're passing in otherwise the value is greater than or equal to so we search BST on the rights and bow and the only thing we have to do is put return before these because we're returning the node when we find it so these recursively go traverse the whole tree once if the valleys null we were turned off if we find the value we return the roof that's it so easy easiest problem ever there we go solution hundred percent and that's pretty much it guys I mean that's one of the easiest problems on leak codes for trees especially so please check out any of the other ones we go through a lot of harder and medium ones so check out the other videos and please subscribe and like thank you guys for watching and I'll see you next time
Search in a Binary Search Tree
search-in-a-binary-search-tree
You are given the `root` of a binary search tree (BST) and an integer `val`. Find the node in the BST that the node's value equals `val` and return the subtree rooted with that node. If such a node does not exist, return `null`. **Example 1:** **Input:** root = \[4,2,7,1,3\], val = 2 **Output:** \[2,1,3\] **Example 2:** **Input:** root = \[4,2,7,1,3\], val = 5 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[1, 5000]`. * `1 <= Node.val <= 107` * `root` is a binary search tree. * `1 <= val <= 107`
null
null
Easy
null
1,452
hello friends so today we gonna discuss this problem one four five dual problem named people whose based off favorite companies is not a subset of another list this problem came in the bikini contest one eight nine so now problem statement states that you are given the array favorite companies where favorite company I is the list of the favorite companies for the IH first indexed from 0 so as you can see like the for the first person or the single person these are the favorite companies before to world Facebook for this person will indexed one degree other favorite company you have returned appendiceal of all those people who is visto favorite companies is not a structured of any other list of you become he was it returned them in the increase mode okay so now as you can see this person so this person for this person if we check and all the other companies so if we like check this come Google aunty this person's list is actually a subset of this because this person also want the company Google and Facebook but it also want need food but this person only one Google and Facebook at us both of these companies and come under this person also that this person's indexed is like a subset of this so we don't include it in our final outfit so we only output all those illnesses most companies are like whose names are not subset of any other person okay so they can be multiple ways to do it but I have done it in the most simple away and it phase God accepted because actually the constraints are very small okay so what I have done is I have to first do a lookup so what can I do is I can maintain two pointers one point at the first person so we what we do is become pay every person with every other person and we will find the intersection okay so for every person every two person like I point at zero person and a pointer at the first person and we - holder and we will do a for loop over - holder and we will do a for loop over - holder and we will do a for loop over all the persons but when I equal to J we will not do the process because if ing are same which means we are talking about the same person then it is a subset of that person only because this person is absolute sub subset of itself so everyone will get cancelled so we will do the matching or the subset for foundation in food hypocrite okay so now what we will do is listening to the poor so who becomes very quickly we've said whether so for the is person lead foot we will want to check whether this person consists of beautiful so we can either into it over the whole list and check whether the input is there or for fast because we can maintain a set and for even past become we can return an ordered set so I have done the same vector of an unordered set of strings we will iterate over all the strings and first push for is person all the strings in that set so that for all the ayat all the persons we will do to the property for now I took two point like Flags flag one and this bag so now for every person I and for every person J we will do this matching substance powerful like we will check whether the substrate or not when I and Z are not same now we will initialize those two flags with zero under these four conditions so now what we will do is we will check whether this is person is a subset of any other person okay so what we will do is for every a string of present in I we will check whether it is present in any all the strings of this is present in any other person so we will take the first string and mj's equal to one on this person we will check whether the input is there or not you check we will just search it in the state so for all the like strings and I you will go and look up and started in the jet-set if it is not present so in the jet-set if it is not present so in the jet-set if it is not present so what does this mean it means that for our target all the completement must be present for the i8 company to be a subset of any other person all the companies is present so in any of the companies is not present it means this must not be a subset okay because for like example for if we check for this person Google is present in person one fit Facebook is present in person one thread so if everything is present then this will remain to be 0 this condition is not met if everything is everything else found in another person then this will remain to be 0 now we will check if this is 0 it means that we are doing a negation of like 1 which means if flag is 0 it means all the elements of a opposite injury so we increment our flag to burn and it means that I should not be taken in that final vector because it is a subset ok because now if this remains to be 0 it means that this condition is not met and every element of I is present in some other Jai person and if it is present then the increment of that will be 1 which means that this is a subset and if the ADEA subset then will not push in the vector final vector B if this flag is not made equal to 1 which means that this is not a subset and we have said for all the possibilities and this will not turned out to be 1 it is remained to be 0 then we will remain check that flag is equal to 0 yes so it means it is an odd subset of any other person then only will push in dancer but now because you're moving from 0 to 1 so it is also in order and tell me test it will turn which is consistent older person entered and this is accepted I hope you understand and object as well as the port if you still have any doubts all better solutions please mention on the coin box thank you watching this video as until next time
People Whose List of Favorite Companies Is Not a Subset of Another List
restaurant-growth
Given the array `favoriteCompanies` where `favoriteCompanies[i]` is the list of favorites companies for the `ith` person (**indexed from 0**). _Return the indices of people whose list of favorite companies is not a **subset** of any other list of favorites companies_. You must return the indices in increasing order. **Example 1:** **Input:** favoriteCompanies = \[\[ "leetcode ", "google ", "facebook "\],\[ "google ", "microsoft "\],\[ "google ", "facebook "\],\[ "google "\],\[ "amazon "\]\] **Output:** \[0,1,4\] **Explanation:** Person with index=2 has favoriteCompanies\[2\]=\[ "google ", "facebook "\] which is a subset of favoriteCompanies\[0\]=\[ "leetcode ", "google ", "facebook "\] corresponding to the person with index 0. Person with index=3 has favoriteCompanies\[3\]=\[ "google "\] which is a subset of favoriteCompanies\[0\]=\[ "leetcode ", "google ", "facebook "\] and favoriteCompanies\[1\]=\[ "google ", "microsoft "\]. Other lists of favorite companies are not a subset of another list, therefore, the answer is \[0,1,4\]. **Example 2:** **Input:** favoriteCompanies = \[\[ "leetcode ", "google ", "facebook "\],\[ "leetcode ", "amazon "\],\[ "facebook ", "google "\]\] **Output:** \[0,1\] **Explanation:** In this case favoriteCompanies\[2\]=\[ "facebook ", "google "\] is a subset of favoriteCompanies\[0\]=\[ "leetcode ", "google ", "facebook "\], therefore, the answer is \[0,1\]. **Example 3:** **Input:** favoriteCompanies = \[\[ "leetcode "\],\[ "google "\],\[ "facebook "\],\[ "amazon "\]\] **Output:** \[0,1,2,3\] **Constraints:** * `1 <= favoriteCompanies.length <= 100` * `1 <= favoriteCompanies[i].length <= 500` * `1 <= favoriteCompanies[i][j].length <= 20` * All strings in `favoriteCompanies[i]` are **distinct**. * All lists of favorite companies are **distinct**, that is, If we sort alphabetically each list then `favoriteCompanies[i] != favoriteCompanies[j].` * All strings consist of lowercase English letters only.
null
Database
Medium
null