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
282
so hello everyone this is Akshay here and welcome back to the another great day of our Beauty streak of day 2012. so today's question is a hard question so let us see what the question says and how we can solve it question name is expression add operators and given a string guess that only contains the digits from 0 to 9 and integer Target return all possible strings to insert the binary operator plus minus or multiplication between the digits s so that the resultant expressive evaluates the result value okay there is also a note written here that the operands in the return expression should not return leading zero still leading zeros and if no solution is found return an empty string here is so first we have to make that as well you have one star two star three and one plus two plus three figures so we have this thing as one two and three right so definitely we have to cover each and every path right so we have to cover each and every sub problems like if it is below 25 then definitely a question then definitely that question would be solved by only one approach that is recursion if the constraint is below 25 itself right take it and this thing I have explained in my time complexity video as well that how to fix the constraint how to learn from constraint ticket so let us start the first subscribe we have we will have one and for each and every we will have three option right so we will have plus minus and star so the next is 2 and then again we will have plus minus and star again 2 here and 2 here right and we will have plus minus star again plus minus and star now we have 3 here right again three now all the string has been ended all the characters have been ended we have started from y equals to 0 and we have it rated till I equals to 2 right so hamare pass if we calculate it if we calculate that what is the uh what to say the value is accumulated so 1 plus 2 plus 3 that gives you as six and here 1 plus 2 that is 3 minus 3 that will give you a zero then again 1 plus 2 if you take this part one plus two star three so it would be three star three nine correct and again 1 minus 2 plus 3 so it would be minus 4 similarly minus 3 am I right I'm writing it correct so it would be 2 right first it would be 2 then minus 4 then minus 3 and then you will have 5 then 2 ones are two and minus 3 it will give you as minus 1 and then it will give you a 6. now we have to observe that wherever the target value is equals to 6 that path is my answer and you will have an error list of answer error list of string right you'll have to append in that appending it in the path so you can clearly see the path available here is this one so or let me highlight it the path you are available is this one and then you have as this one right this is the path rest everyone is not giving you target value now I have one question I have one task for you please pause the video now and try to think that have I written these values right are these values you are disagreeing with me some values that yeah let's say yeah if and why right please try to think of it come back to my video again in one minute okay so maybe if you have thought uh if you have read this technique you would have read this technique as board months right that is the Precedence given to the operators so what I did when I was in this path right this path so I was doing one plus two what I'm calculating one plus two star three and what I did first plus and then multiplied it and that's why I'm saying 6 but actually mathematical is first we will do the multiplication and then plus so definitely up in nine now okay this should have been six right similarly one minus two can start yeah so one minus two star three will give you as three to six and minus y minus 5 so this is also wrong right we have to make sure that whenever you are using a multiplication sign at the last like minus multiplication or plus multiplication whenever you are using this thing you have to make sure that you take the track of your previous values right you have to take the track of your previous values okay we will see that how you can handle it the third point they have mentioned is that you should not have any leading zeros in your path right let us decide that what should be the parameters involved in that function right so we have a function let's say what should be the parameters first of all the answer is because in this we have to append our all path right then what we will have then we will have a path at whatever path you are taking in is initially it would be an empty string then we will have the Target right if I'm not wrong let me see that or yep also the string is also given you as the given string has given you as num so you have to pass your given string so this is nothing but given string because in this only you have to trade then you have to pass your Target in PC say we have to compare our base condition then you pass have to pass your index which will be your type int this will be of time print this index is nothing that but we are iterating in each and every character of your given string what rest parameters are involved then you have a path right so in this path you can clearly see when we went from one to two we uh this was the character right but each and every point we have to maintain its numerical value as well so this is 12 right 1 plus 2 will give you as 3. it's similarly for each and everything you have to maintain the path value right as long path value and then we will have one more parameter as long previous this previous is to handle this case that what if the multiplication come after the plus after the addition or subtraction figure again please pause this video again because there is one more test case given if you can see in the third case that s is equals to 1 Target is 12 then what they have said is that at s itself matches the Target no other strings are possible so that means we have we do not have just three recursion right we have one fourth Branch also to recur and this fourth branch is saying that you just have to include your other characters in yourself right so that means it will become as one two right you have added two here right and then for this one two you will have to do again three requested four recursive score right that would be plus minus multiplication and then again add three so what will happen here is that 1 12 plus 3 it would be what it would be 15. then we have 12 minus 3 it would be 9 it will start three it would be 36 and then you have 12 uh one two three right this would be the case am I right so I think that uh let's read the question once again so we have to run in all possible strings to insert the binary operators plus match between the digits of the S so that the resultant equation okay so that means that this thing is not possible that 15 9 and 36 is not possible yes we can take one two and we can take one two three yep yes okay but again we have to make four recursive call that is for sure right so what would be the base cases let us decide the base cases right and this is for sure that for each and every character for each and every uh character we have to recur for all possibilities recover for all four cases correct so what would be uh this thing so first of all we will check our base condition when our recursion was stopping and we were checking the target value we can see whenever it was at this my last level where I value becomes the string length right 0 1 2 and 3 it becomes 3 so that means whenever my index is becoming the shrink length then that means your recursion tree has ended at that point so I will say my if index is equals to what string dot length and string is here written as num I will say if it is equals to one sec num dot length right and then what you have to compare that your path value is equals to Target or not correct so you will check that if path value is equals to Target then you will include that path in your answer I will say answer dot add path return so this would be our first base case now what we have to do for each and every character we have to record so how many graphic for look for I equals to what index I less than length members I plus right now we will include that character one by one right so I will say long again why I'm using the long here because at worst what is the maximum uh value of the number that would be calculating so plus minus multiplying right so whatever be the length of the string let's say length of the string was given you as 10 right so in the worst case you will be multiplying 10 numbers as 1 star 2 Star 3 star till I get 10 numbers right and each and every number will give you as one zero right so definitely you are exceeding the power of 10 power 10 or you are up you are like touching the value of 10 power 9 almost right and integration right so there's a high chances that this for this third branch of multiplication you can get a overflow of integer right so that is why we are using a long variable right so from a string how can we pass our integer value so for that we have to we have a long Dot Parts Long right similarly if you have to pass the integer you will write long dot parse integer and one more thing again I would like to add here that please try to understand the logic and code here because at the last then I will show you the direct code please try to understand the pseudo code I have already explained you how the flow is there so it's just now the only part is to how we can summarize or just discussed approach into a code so let us do that so yep here is a long current we will longer to you use a parse long and then what I need is that first I need this string first one and then I have to recover all the possibilities right two and then negative for all possibilities then I need one two and regard again right and then I need 1 2 3. right I will just s dot substring of magistration boom right I am at position IND and I will take I Plus 1. correct take care and then I am checking that if index is equals to zero so function again the answer the path and then what we need to do in the path now we have to handle the plus sign and under the plus and then I will give my current right so this is the three recursion steps that you have to write right first you have to handle for plus then minus and then multiplication right then you have your this current character that you have just included right that would be going into your path and then you have this your current given string you have the Target and then you have this you have to recover for next character so since you're at I then you will require for I plus 1 and then you will have the path value again and then you have path Value Plus current plus current which will give you the number right you are doing one plus two so this will give you as three right so this is storing the as soon as that you are moving from one point to another like from one you recover the branch of plus two right so this will have now one plus two that is three what is this current is nothing but it is doing storing the previous value right so when I am doing one plus two so this entire 3 is getting stored into P Value Plus current and this 2 is getting stored into this here so for the multiplication case what we need to do is so let's say you have like this you have one plus two and then you have to do star three right so I know that this is my pul plus current so I am writing p V plus C right and I know this is getting stored in my previous variable right no not this one this is my previous variable right so this is getting stored here previous and this 3 is my what this 3 will be my current right and what I want that instead of one plus two star three I want two star three value calculator and then o plus one can we write something regarding using these variables if I do let's say p Val plus c minus previous p l plus C is pointing to 1 plus 2 that is three previous pointing to just this number so 3 minus 2 which gives you as one so definitely m is okay right now we just need to add multiplication of two star three which is here previous star current right so I can just write previous star current right and now since this was my what this was my uh the current character which I for which I did the processing and now this will become my uh this 6 will become my previous character right so in the function I will just pass instead of here it will be replaced by this for the multiplication part right and this current this previous parameter will replace by previous star current right Time Low take your time and try to understand how I have written this right so for the plus and minus this function will do the work but for the multiplication thing we have already discussed why we need to maintain this previous variable here right this previous and now it is helping us so let me shrink the code a bit more yes I hope it is visible okay so I hope we are clear at this at okay so I hope we are clear at this point that how why this two parameter changes these two parameter changes for the multiple things and everything remains same now please pause this video right and try to code this step um just write the skeleton of it I will explain you how this is coming right and for the rest of the things will remain the same please for this we don't try to code it and then we'll resume again okay so I have coded the entire solution only two things left to remain so but let me give you the code workaround so we have made an analyst of answer right and we have this pre-check condition and we have this pre-check condition and we have this pre-check condition that if the string is null then the answer there would be nothing in the answer right so we'll return or if the string length is 0 so we'll return the answer and then we are calling Alpha function which is taking the answer the empty string the given string the target the index the part the web the path value and the previous value we have to make we have to keep it just to track the previous to make sure that it can help us and this multiplication case right we have already discussed so rest of the thing goes same uh we have this base cases that if index is string dot length and in that case if the target is equals to uh P value path value then definitely add that path in my answer what happens next that's for each and every element you have to recover all the possibilities as I showed in you the recursion tree again now we are storing the each and every character whenever we are start iterating and then we are calling these three recursive steps for the Plus for the minus and for the star I have explained you very well I've tried my best to explain you how this expression has changed the second thing was the leading it should not contain any leading zero so that is why I have checked here that if the particular index the character particular indicative is zero then you don't have to do anything do not recover in all the directions for this particular character and break it from there right now let me tell you what this is doing now why this is required right because whenever you have a current character let's say let me copy this code and then our next so what I was saying is that what is the important of this particular line so right what is happening is that first you have an empty string right you're passing your uh helper function but then you have in this using this long current when you are at I equals to zero you have this one now for this using one you have to recover rest of the part right so that is what is happening you have this current and you your path is what path plus current is indicating what path is nothing but an empty string current is not about one right so you have to again call the helper function saying that now my path is actually pointing to 1 and recurve for rest of the characters now that is two and three right that is why it is needed here other let's say this if was not there right then what would have happened that you would have called the this three recursive call for an empty path which is not right at first you should have at least your first character and then you need to recover for an empty path how will you recover everything right what will happen nothing will happen now right so that is why whenever we are first calling the recursive function we have first of all we are checking that if it is calling for the first time right if it is calling for the first time then first you need to make a path with the first character and then you have to move on right so if I do the system.print.ln at this step what it system.print.ln at this step what it system.print.ln at this step what it will print is it will give me as one then the second path is one two and the third part is one two three so one recap for the rest and everything consider all the possibility one two and then again Rica in all the three directions and then one two three recall the two directions where is the fourth recursive call that you were talking about actually so this is the fourth recursive call as you can see that one and two are getting attached as you can see now in one and two three is getting attached right that was our call right so one vehicle for plus vehicle for minus V equal for star and then the string become as one two correct okay if you can just use the print statement here as well it will give you the printing as one two comma one two three right and trying all possibilities for each of this formation right so I think the code is very clear now but if at all if you have any doubts another further doubts regarding this code because explanation was very simple uh recursions for the smaller cases like I do I show you the Dragon for the smaller case that is one to create don't ever try to go for the larger cases because uh for the larger cases you must have to have this recursive leap of faith and everything will work fine so let me see what's the problem is here some brackets okay somehow this class solution was I don't know how it was deleted let's compile it on and again and what would be the time complex complexity so let us do the time complexity analysis as well so what are we doing as you can see expected in output matches let us see the time complexity now so what is the time complexity that for each and every let's say for one we were making the four recursive course as you can see right and how many elements are there and so and how many recursive calls are you making four so it would be n into uh n power four right this would be a time complexity what would be the space complexity um uh for each and every you have three choices right although we are making foreign given in the question what choices do you have three choices right so that means three power correct also it would do not end powerful you have four choices for any uh and every element has four choices it would be four power and similarly given as three choices for each and every element so it's three power n but if you remember the recursive three I made right so you can see for this one you have three choices right and you made the three choices and you passed the entire string for this recursive call right and this recursive call itself will make you will need the space complexity of O of n because you pass the entire string for each and every character right so that means you have three choices uh so that means three uh three power n but for each and every call you are using a recursive stat space of n as well so it would be n into three power right so I hope clear on this point let us now submit the code and we will see so great as you can see all the test cases has been passed successfully and we have done a hard level question as well again this question was easy to understand I can say the only trickier part the only thing that we needed to think of okay when we made this recursive uh tree diagram because it is very mandatory to made for the small case and when you made it you have to see that okay we have to follow the board Mass rule as well right so some of the paths were giving you the wrong values wrong answers so in that case you need to handle that multiplication case here as we have derived this multiplication case right and that was it that was the only cash here and let us meet tomorrow in the tomorrow's three o'clock day uh 213. a few last thing that you can start and Fork my DSA repository to get up with the source code and let me show you the C plus code as well and then we'll end this video okay so that's the C plus code as you can see again the same thing is happening I don't think there is anything change you know instead of errorless we have a vector maybe C plus is user will relate it well and let us compile and then and I'll not hit the submit button and I will again push it in my DSL Repository yes let us compile yep so it is running fine right you can submit this code and let us meet tomorrow in the tomorrow's freak of day 213 until then keep learning keep going goodbye and take care and do not forget to post your second day of streak of 30 days of Challenge on the LinkedIn right it is also uh a good task uh mandatory task as you can see it will help you eventually in growing right let us meet tomorrow bye
Expression Add Operators
expression-add-operators
Given a string `num` that contains only digits and an integer `target`, return _**all possibilities** to insert the binary operators_ `'+'`_,_ `'-'`_, and/or_ `'*'` _between the digits of_ `num` _so that the resultant expression evaluates to the_ `target` _value_. Note that operands in the returned expressions **should not** contain leading zeros. **Example 1:** **Input:** num = "123 ", target = 6 **Output:** \[ "1\*2\*3 ", "1+2+3 "\] **Explanation:** Both "1\*2\*3 " and "1+2+3 " evaluate to 6. **Example 2:** **Input:** num = "232 ", target = 8 **Output:** \[ "2\*3+2 ", "2+3\*2 "\] **Explanation:** Both "2\*3+2 " and "2+3\*2 " evaluate to 8. **Example 3:** **Input:** num = "3456237490 ", target = 9191 **Output:** \[\] **Explanation:** There are no expressions that can be created from "3456237490 " to evaluate to 9191. **Constraints:** * `1 <= num.length <= 10` * `num` consists of only digits. * `-231 <= target <= 231 - 1`
Note that a number can contain multiple digits. Since the question asks us to find all of the valid expressions, we need a way to iterate over all of them. (Hint: Recursion!) We can keep track of the expression string and evaluate it at the very end. But that would take a lot of time. Can we keep track of the expression's value as well so as to avoid the evaluation at the very end of recursion? Think carefully about the multiply operator. It has a higher precedence than the addition and subtraction operators. 1 + 2 = 3 1 + 2 - 4 --> 3 - 4 --> -1 1 + 2 - 4 * 12 --> -1 * 12 --> -12 (WRONG!) 1 + 2 - 4 * 12 --> -1 - (-4) + (-4 * 12) --> 3 + (-48) --> -45 (CORRECT!) We simply need to keep track of the last operand in our expression and reverse it's effect on the expression's value while considering the multiply operator.
Math,String,Backtracking
Hard
150,224,227,241,494
84
Hello Viewers Welcome Back Door Sign In This Video You Will See The Largest Rectangle In Histogram Problem Swiss Roll Number 400 Latest The Problem Statement In This Problem Negative Entries Representing Subscribe Latest Example No Problem Thursday Triangle Thursday Subscribe The Channel subscribe 15623 for Back Representations Give No Veer That I Can Be Formed In This Is Program And Have Already Mandaladhish Triangle Dhund Sach Rectangles For Dance Vansh Tagged With One Another Rectangle And You Can Improve The Center Will Be The Largest subscribe The Video then subscribe to the Page if you liked The Problem No Latest Examples in Order to Get Some Observations Subscribe The question is What is equal to three units for the area in a specific way to do three Subscribe to form in Yadav rectangle You have tried to form a Rectangle but only interact one-to-one subscribe to the Page if you one-to-one subscribe to the Page if you one-to-one subscribe to the Page if you liked The Video then subscribe to subscribe and subscribe the Channel Today at site will be 39 area where is the largest area In the lava the center 4 * 4 largest area In the lava the center 4 * 4 largest area In the lava the center 4 * 4 all the best all subscribe liquid calculation of the third largest subscribe to the Page if you liked The Video then Yudhishthir very important observation for solving its problems node triangle contains at least one full day find the area of Rectangle To Maximum Rectangle Subscribe And Subscribe List In 100 Latest Servi Not Withdraw From All Girls Which Will Be At Least One So Subscribe The Channel subscribe this Video Do And Dowse Vicente So Effin Loot Bar One In Full The Largest Rectangle Area Equinox Wallace To The Page if you liked The Video then subscribe to the Page if you all the way Maximum hua tha so this will be and answer ok swapan dosh ke is the maximum as the first so this is the witch Can be included in the app Will get the maximum regular basis subscribe our YouTube Channel and subscribe the Channel Please subscribe and subscribe the Channel subscribe Simple a Bird The First Step Needs More Observations OK Know How to Solve Adaptive 9 Questions as to How to Find the Area for latest and e want to thank you can reduce can include all and e will give the current president will not what will be the and happened just one which is 2nd shift bar which is encounter diploma From December 2004 Limit This Point And Will Stop Limit Order Want To Right Side This Current Seervi The Last subscribe and subscribe the Channel and tap on the two What is the - - - Quest Most Limit Plus Awal Bhi and Internet and Will Be Multiplied by and Life Hit the center thing will be in a positive step in the year again when they all know what is subscribe and subscribe the Channel Number of elements in the Muslims will require a ho traversal Britain to dross and skimming and this time hair and was Total Time Complexity This Crispy and Options but Know How to Do It is the Solution Can Find the Best All the Best Limit in Just One Time Complexity Solution subscribe to the Page if you liked The Video then subscribe to Loot 100 Basically they want to remember the previous elements How to keep track of the previous year will have to take away your data structure to keep track of elements in remembering the elements in increasing with the most Dangerous subscribe The Channel and subscribe the Channel Different hit show will just also writing in 10 big and limited index no what is this point from ok no veer singh this element in to the subscribe The Channel Please subscribe and subscribe the he will not move to the next one so before moving porn bhi nutrition this index one into 10 to 15 Nov 18 Dec 3D 125 limit for be id for the top of the The Way You Want To Limit Subscribe Limit For Be Id Subscribe 9 Moving Onto The Next Time Will Be Watching This Into 10 To 19 Let's Move To The Next Visit In Decorated Serving Hitech Want To Know About The Limit For This One Of Your computer and subscribe sudhir and middle age limit for this point to the plus top a five-year shoulder limit of the is this 62 five-year shoulder limit of the is this 62 five-year shoulder limit of the is this 62 years ok novel ask this point to take off baroda center histogram All the lower hit which is that index 6 Vishwavidya right limit for this is the number of birth 1234 must subscribe my channel subscribe plus one will B Coming To Know What Is The Number Of Virat Minus Plus Subscribe And This Time That No One Has Been Know How To Calculate Area Latest Straight Run For Solving Different Problems Noida Authority Will Be Using Stack And Dividend Will Be Traveling From Left to Right in Order to Find the Nearest Limit on Thursday Subscribe Now to Receive New Updates Will Not Having Any Limit subscribe to the two Subscribe Thank You Will Not Have Any Clue No One Will Dare Attack You Text to Me Shopping Hee 225 No The Top of the Lake is having it does for this is modeler the limit for this Oct12 Top 10 plus one to the limit for watching this is the one to three subscribe The Channel Please subscribe and subscirbe Will not take the volume to the point in this way You Will Be Index Rising Value One Should You Will Be And Limited And Limit Top 10 Value Subscribe Element Subscribe Now To The Thing They Loot Limit subscribe and subscribe the Channel And Clear Interest Novel Let's Move From This Point Subscribe To Shailendra Right Most Valuable Best Wishes Minus One Vidic Similarly When Moving From Left To Right Some Will Be Having Been Washed And Indicating That Will Stop At The Subscribe subscribe The Channel and subscribe Hour Best 19 To The Previous Element Wishes For the 409 We moving from left to right in which element will subscribe to it Subscribe to that no will want to the previous element before movie will push this index on top 10 tracks PM ON To the next element This is the President 1259 The Video then subscribe to the two and the person and subscribe 2014.the hike will reduce subscribe This is the Light limit that index bane limit so will include all the best students and so will write n Essay on the last time notice of intellect will be included in the previous elements for this element is having worked to the limits of - one with no time is having worked to the limits of - one with no time is having worked to the limits of - one with no time limit for bid candidates from this point to minus plus while the great the right minus Plus Vwe The Lave The That Among Those With A Single 62 Years 9 Bishop First Time Bloody Mary - 06 Intuitive Who Will Know First Time Bloody Mary - 06 Intuitive Who Will Know First Time Bloody Mary - 06 Intuitive Who Will Know No Longer Than One Plus One To The Value Of Three Plus One Subscribe Left Right Left Side Value Auspicious Ratri And Destroys 5051 * Dahej Auspicious Ratri And Destroys 5051 * Dahej Auspicious Ratri And Destroys 5051 * Dahej All The Resources For All Difficulties To Find The Area For Getting In Noida And Observation Maximum Rectangle subscribe to the Page if you liked The Video then subscribe to The Amazing Maximum Variable And Calculating Subscribe The Giver Has Time Complexity For This problem will be harder in this case will be moving one time from left to right in order to calculate the left here one time from right to left in order to calculate the right and once loop limits for observing calculated and finally will use this end travels From laptop to calculate the subscribe veer the limit points 98 ajay devgan will feel this loop festival after filling this will be feeling 10800 subscribe and subscribe the maximum travel from left to right will calculate the maximum * Video plz subscribe problem hi problem comment subscribe like share and subscribe don't forget to subscribe our channel thank you
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
1,046
and today we have this problem it's called The Lost system weight you are given an array of integral Stones where the stones of eye is the weight of eye stone we are playing the game a game with the stones on each turn we choose the heaviest two stones and smash them together suppose the heaviest two stones have weight X and Y with X less than y less than equal y the results of this smash is x equals y both stones are destroyed X doesn't equals y the stone of weight X is destroyed and the stone of weight y has a new weight y minus X okay the end of the game there is uh is at the most one stone left we turn the weight of the left remaining Stone if there are no Stones left return zero okay so we have this Stones array and the output should be one because first of all we take the biggest two seven and eight and the remaining will be one and we will have a just three five and I guess to about two four one and three ones yeah and after that we have two and four and the remaining would be two so three two one and then we have two and one the remaining will be one and it will be have three ones and rest after that we just have to one and both of them destroyed each other and we have one lost and let's just because I want let us think about this problem because there is tons of different approaches to uh to this problem you just Okay so if you remember with the reason let's say that we have the array okay that's it that we have another that I have like one and two and four and uh six and maybe uh seven nine and that's it and we wanna just we'll take the biggest two things like if we take the book these biggest two things we will have two okay so the array will be one and two and four and six and two and we'll take the biggest two of them like that will be only two so it will be uh one two and two if we take these two things the both of them are destroyed so we have one and two so if we take one and two it will be we left with one so how can we solve this problem there is tons of different ways we can just first do a brute force and yeah I guess the time complexity will be of one squared we can do a heap or we and this will be the uh I don't know but the it will it could be in Logan or something like that because he will be give us that things because we will use a priority queue or there is multiple different approaches but in my mind the coming one specific approach which is to use a recursion first of all we didn't build uh used a recursion for a very long time in our channel so this is one second it's efficient so let's see how we can do this recursion so we create the function okay and first of all we will sort the array I've already sorted so we don't have to carry about that but just make sure that we should sort that way first of all we say that if the we when we have a recursion function we build the piece keys so the best case if will be if the length is equal then or less than one or maybe if the stones uh and if the sounds that means equals one will return one if the if there is no length maybe like all the sudden destroyed each other will return zero however let's just started and how we can solve the code so first of all we install it this store this area is already stored so after storing we will just take um X and take y let's just see this is X and this is what okay and um and Y the new y will because we will have like just equals let's say that it will be the new one we will add y uh that way again okay and stone the push we will push this way this new one to the array okay and after that we will keep calling this function under this array until the length of the array becomes one or less than one or zero so this is the what we are going to do okay so let's installed into it so first of all we have a recursion function what we should do in the first thing we should choose what is our base scenario our best case it will be if I meant I'll say if um stones Dot length less than or equals one I will say and if it's less than or equal one there's two uh possibilities the length is equal on and if the length is equals one if Stones dot Lin equals one I will return tones of zero okay however if it doesn't equal the normal that means there is no remaining uh elements maybe like everything was destroyed everything was full of the equal stones so I will return to you because there's nothing to return okay we finished the base case I will say else I will see uh Stones first of all we sort the sort a and B and a minus B okay and I will say um X will equals stones dot Bob so it's the biggest one and why it is the next biggest one so I will say um net X and net y and I'll say y um first of all I want to make sure that if I and x equals to each other I just pop them and I just remove them from the they are already removed in the array the thing that I want to do is that I want to um I want to push this first of all let's just take the remaining of them I will say y will equals y minus X okay and I will say that if no let's just say that if X doesn't equal y so we do that we do this calculation otherwise we don't have to do it because if they equals each other that means both of them are deleted so just that's it and I will um I will push Stones Dot push I will say uh storms first however I just pushed the array Stone stop no sooner does not push I guess minus y because if Y is the smaller and it's minus five to like minus one sequence uh equals what's this equals the positive so we return this array again this function again and we pause the new stone array that we implemented that we remove the last two elements and after that we click the device the remaining and we put the remaining to the array and we call the function again else if they are not if the if they are not equal to each other that means they are equals each other if they are equals each other I also FDR equals to each other I'll just call that array I will just call the function again I don't have to push anything to the array and I guess that's it okay there's something with it look this is like was a few seconds ago like 15 minutes it when it was beating 90 right now it's beating only 40. however let's just discuss the play I'm gonna take this one because this one looks better it's the same solution right just looks better yeah because I don't have to um manage everything okay so let's just describe what we have let's just add this one because the recursions problem needs a lot of description so let's see that we have the stones and we have this other okay and I'm saying that Stones dot length first of all this is it will be a recursion function and all the time that we when we start recording we just build our piece case and our piece case here it should be if the length is one or less than one that means there is nothing more to compare so there is nothing more to compare we return the remaining otherwise if there is no remaining we return 0. okay after that we start to uh to this one we sold the array first of all we sold the array so let's just sort that way so it will be one two no one two four and seven and eight okay and after sorting the array we will say that we are popping X and Y so let's just have X and Y first of all we popped in X will equal eight and Y will equal seven and we pop them so we're deleting them from them and Y will equal the minus X and Y so it will be one however I'm saying that if y doesn't equals x a x is equals and this is what we have so y will equals one and we push one here okay and we call the function again we call this function again and we just go from the app if the stones dot length less than or equals one no this is not right so this emphasis is not working so we just sort again so when we sort we put this one and to the end so okay and after that we will have X and Y and it will be 2 and Y will be four and then your y will be 2 because 2 minus four will be two and we will push and we just delete these two four and we'll put the remaining which is two okay and we call this function again okay and we'll just to go back is the standard length less than or equals one no they are still four okay so ignore this sort that array so we're sorting again however that is sorted no problem so I'm taking x dot Stones pop I'm taking y and x it's one and the remaining will be one and I push this one I will delete these two things first and it will the remaining will be one okay and uh I'm calling the function again and I will go with the function again I will say if Stones dot length less than a person know there are three so we thought that Ray is already sorted and I'm saying that if x doesn't equals y but this is will not do that because x equals y so we just pop them and we just it doesn't do anything okay we have remaining Y and we call the function again and in this function we say the interlock function we say that stores dot length equals one or yeah it's equals one so if Stones the lens equals uh sorry Stone means less than or equals one yes okay if stones that last equals one return the first one so we'll return one and that's it so that's it for this video I hope my solution is quite good if you like my solution make sure to subscribe hit the notification Bell so you will never miss a video and see you in future problems
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
22
hello everyone welcome back to sudokudo those who all are new my name is raveena I am a software engineer and I solved algorithm uh problems I also have a data structure Series so be sure to check it out if you are new to coding or just want to learn how to apply those data structures in competitive programming or just programming in general so today we are going to solve problem number 22 which is generate parentheses let's start by reading the question it says that given n pairs of parentheses write a function to generate all combinations of well-formed parentheses combinations of well-formed parentheses combinations of well-formed parentheses so what the question means is that you'll be given a number so for example here we have n equal to 3 and then we have to create possible combinations valid combinations of parentheses such that they are valid so here you'll see that this is one of the valid parentheses where you know you have Open Bracket close bracket and then open close so kind of a nested thing here we have to open close and then that is nested within this big open and close bracket so basically you have to find out all the combinations of the valid parentheses based on the input number n so today we are going to solve this using a more intuitive approach which is backtracking and I'll be drawing some boxes and going through and actually explaining how it happens step by step so let's move on to my notepad we are going to use example of n equal to 2. so what do we need for this first thing we are going to solve it using backtracking and that is nothing but DFS and let's see what do we need three things for the DFS function we need number of left brackets so basically l the right number of right parentheses which is r and then a string s this string is going to basically be the result as in the substrings inside the array so we need three things for the DFS function now let's talk about what should be your breaking condition since you are you know using a recursive algorithm that's super important thing is to have a breaking condition because if you don't have the right breaking condition you can never reach the right solution so the breaking condition here is let's think about it if I have n equal to 2 how are my combinations gonna look like one combination would be something like this the other combination can be you know something like this so are you seeing a pattern you'll see that if there is n equal to 2 that means I have two opening brackets and two closing brackets so that means each and every time with a valid string that I produce that I create I'm gonna have 2 into n length of that string so if you also look here it is you know two opening brackets and then two closing brackets so that means it has to be 2 into n so whatever our n is if my length of s is equal to 2 times the length of n that's when we know oh we actually found a string and then we add it to a result since this particular uh expect this particular solution has a result has an array so we are going to create a result array and we are going to stuff all our strings in here so to start with what did we talk about the first condition was if my length of s is equal to 2 into n if that is the case then I'm just gonna add it to my result uh now let's talk about the second condition so my second condition here would be if I don't have the match that means I still I'm gonna go on and create my you know start building my string so that means that I'm gonna check I'm gonna first check if my left number of parentheses are those less than n that means I can add more left parentheses so the next check I'm going to do is if my left is less than n if that is true then I'll call the function the DFS function and what I will give it I'll add one left parenthesis to it and I'll also increment the count so my I'll call my DFS function I will increment the count of L I will keep my right as it is because I did not really add anything and then I am going to add a opening bracket to my S that's all I need to do it's gonna call the DFS function again it's gonna you know Loop through it now I have considered all my opening packets what about my closing bracket so I'll have the last condition where my last condition would be if my R if my number of write brackets are less than the left brackets that means I need to add more right brackets remember here I'll not check if my right brackets are less than n because I want to match the number of right parentheses with the left parenthesis so that's why I'm going to check if a r is less than l number of right brackets are less than number of left brackets if that is true then I am going to Simply call the DFS function this time what did I do did I touch the number of left brackets no so I'm going to keep it as it is I added one of one right bracket so it's gonna be R plus 1 and then I'm actually going to add the right package so it's going to be S Plus the opening bracket and that's all you need to do that's all you need in the recursive backtracking function in order to work with this so let's see this how we can you know actually solve this with n equal to 2 example so to start with I'm gonna have a l which is 0 my R which is 0 and then my S which is actually empty and as you know I like to create a box for every recursive function so that it's easy for me to keep track of things so I have this now I come in I check is my length of s equal to 2N no it is not my length of s is actually 0 right now there's nothing in it so I'll go to the next condition my next condition says if my left is less than n my left is actually 0 so this is left this is right this is s so my left is actually 0 that means it is less than n so I'm going to call my DFS function which is right here I am calling my DFS function with L is with left plus 1 so this is 0 is going to become 1 and then my R is going to stay the same so it stays 0 and then my S is actually S Plus opening bracket since my S was actually empty it's gonna look something like this to make it you know visually uh not confusing I'm gonna use curly braces here because opening and closing parenthesis can become a bit difficult to understand so I'm gonna call my DFS function since this is gonna get called it's gets its own box in the Box what do we receive we received one we received 0 and then we received an opening bracket okay I'm going to the top of the function again remember because it is calling itself so I'm going to go to the top of the function again I'm going to start at the Top If my length of is my length of s less than uh sorry equal to 2N which is actually 4 so is my length of s equal to 4 no it is 1 right now it just has an opening parenthesis in it so we move on I check if my L is less than n uh yes my L is actually 1 my n is 2 1 is less than two what it does it calls the DFS function again so I am going to call the EFS function again where L becomes L plus 1 so this becomes 2 R stays the same and then opening parenthesis is added so you get this oops Yeah so I have two opening parentheses here so I called a DFS function so that needs its own box so we go here we create a box the input was to 0 and then two opening brackets I go up again I check if my length of s is equal to 2 N that means my length of s is actually 2 is it equal to 4 so 2 equal to 4 no okay I move on to the next condition is my L less than n my L is currently 2. is 2 less than 2 no okay move on to the next condition I have my I'll check if my R is less than n yes my R is less than and it is 0 right now so that means I need to call my DFS function and what I'm going to do this time L is going to stay the same R is going to get incremented by 1 and there is going to be a closing parenthesis to my string so my two week stays the same I am calling the DFS function two stays the same 0 becomes 1 my opening parenthesis and then I add a closing parenthesis here keep using the opening parenthesis so since I called my DFS function I get to it gets its own box so I have it here I got 2 1 this and this okay uh I go to the start I check if my length of s is equal to 2N so my length of it is actually 3 2 opening brackets N1 closing so it's not equal to 4 so we move on is my L less than n no my L is 2 N is 2 is not less than 2 we move on we come to the third condition is my R less than n 1 less than 2 yes that means I call this function again so I call my DFS function I keep my L as it is I increment my R by 1 so my R becomes 2 my S my uh a closing bracket gets added to the S so it becomes like this I go to the uh since I'm calling it again it's gonna get its own box it's gonna be 2 and something like this okay I go to the start I check is my length of s is equal to 2 N so this time my length of s is actually 4. it's equal to equal of s is actually 4. it's equal to 2 into n which is actually 2 into 2 is 4 that means this particular string gets added to my result so I'm gonna add this string to my result so it's gonna be this and one more thing once you add it to your result you don't need to actually process anything so what you can do is you can simply return so when you return it's going to go back to its previous cursor and for us it goes from this box to this box now if you look at it this when it goes to this box this was actually I we added enclosing parenthesis here that means this particular method was executed this particular if Loop was executed and this is the end of the method so that means we are already at the end we'll go back to this cursor when we go back to this cursor it was actually also at the end of the DFS because you see we added a closing parenthesis here so that means we already reached here which is the end of the method we will go back once we go back we come to this particular instance okay um here what we are going on here we are we were right here when it called so the next thing that we have to do since you know I can determine that because I added this particular string was opening parenthesis was added to the input this is the input and so I know that this particular if Loop the second if Loop was executed let me actually rub everything off so that we can do you don't get confused okay so we are here in this particular box right now here what was the input it was 1 0 in the opening bracket now we go to the next if we check is my R rest less than L yeah my R is 0 my L was one so what do we call this particular DFS function so it gets its own box right so we create we will be creating a new box which is gonna be okay so first we write our DFS call here which is going to be one my left stays the same my right becomes R plus 1 and then my string actually becomes string plus closing so I only already had an opening bracket I add a closing bracket so that is going to be my DFS call so whatever I get 1 and this I go to the top of the function I check is my length of s equal to 4 no it is 2 right now I just have one opening and one closing I go to the next condition is my L less than n yes my n is 2 my L is 1 is less than 2 I'm going to call my DFS so I call my DFS function what do I do L plus 1 so 1 becomes 2 R stays the same and then I add an opening bracket so I have this put this string and then I have a opening packet here since it's a DFS call it gets its own box we have 2 1 in this it goes to the start of the method it says it checks is my length of s equal to 4 no it is 3. uh okay moving on is my L less than n uh no my L is 2 n is also 2 is not less than 2 we go to the next if condition is my R less than n l so uh let's check my R is 1 my L is 2 okay yes so that means this last EFS function gets called so I have a DFS function L stays the same so 2 R increments so R becomes 2 and then my S up closing parenthesis gets added to the S so like this since it's a DFS function it gets its own box it is 2 and this oops yeah this so it goes to the start of the method we check is my length of s equal to 4 um yes my length of s is equal to 4 that means I added to my result so my result is gonna be this now it has one more additional element and then I return so when I return it's gonna go from this box to this box since this was already the end of the method because we added a closing parenthesis here it's gonna go back now we check is my R once we are in this box we check is my R less than l no my R is 1 my r s l is 1 so we go back to the previous cursor we are here we already have exhausted my left my right because these are these were the two conditions and these were the two recursive methods that we called so we are at the end and we go back to the main call and here when we come back to the main call we are actually we have actually exhausted all the uh backtracking patterns so that means that we whatever we have in our result array is the solution is the result that we wanted so I hope this explanation was helpful let's see how we can convert this into code all right so the first thing that we need is a DFS function so we are going to Define that it's going to be definition of TFS I have my left and then I have my right and I also have my string s the first condition was to check if my length of s is equal to 2 N so that's what I'm gonna do length of s if it is equal to n into 2 if this is true then I add it to my result I add my string to my result and then what do we do once we have a match we just return my next if condition was that if my left is less than n so my left is less than n if this is true then I am going to call my DFS function I'm going to increment my left I'm gonna keep my right as the same and then I'm going to also alter my S so I am going to add my opening parenthesis here so that's what we did for left what did we do for write we checked if my right is less than left that means I need to add some close in parenthesis here I call my DFS I keep left as it is I increment my right count and then in the end I add my closing packet to my string that's all the DFS function does now what did we read we needed a result array to store rather result and then we do a DFS call what how did we call it we called it with left 0 right 0 and string as empty since we did not have anything at the moment and then in the end what we do is we just return results Let's see we can run it okay let's submit yeah as you can see this one is accepted with uh acceptance of 84 percent so let's talk about the space and time complexity of this particular algorithm the time and space complexity of this problem is a bit uh complex to calculate so let's see I'm gonna use my notepad uh so here but think of it as a binary tree it's not going to be exact time in space complexity because as you might have seen from the solutions it's pretty work so we are going to do it in a simple way in the DFS function you'll see that we have two uh things we have two DFS calls sorry one is for the left where we are adding left plus one and the second is when we are doing it for the right so it means that it's going to be you know bifurcated into two and if you look into it um time complexity wherever you have something which is you know just splitting into two it becomes the crime complexity actually becomes 2 raised to n and this is very similar to what we have right now here we have you know left is less than n right is less than left which is uh here which is here so two if conditions so since we have these two we know that it's going to split into two each function is going to call itself two times so that is where 2 raised to n comes in since r n here is actually 2N if you look at it n verse 2 but we had to create a string where it was you know four card four characters so that actually means that n in this scenario which should be actually this is actually 2N so that means that it is going to be 2 raised to 2 N so the time complexity of this particular algorithm is going to be 2 raised to 2 N now let's talk about the space complexity uh since it's gonna be this is a backtracking problem and this is a DFS problem the space complexity is also going to be the same we cannot just only look at the result that we are using since this is storing this can store you know any number of strings uh the memory that is getting used for a DFS function is actually the time that is it's you know the same as the time it's taking to process so the space and time complexity of this particular algorithm roughly is going to be 2 raised to 2 N which is what you can ex you know interviewer can expect from you rather than having uh you know calculating some bizarre time complexities as you can let me actually show you what I'm talking about so in respect to you know what they have here 4 is to n divided by root n no one expects you to come up with this so I hope this explanation was helpful the code for this problem is going to be on my GitHub Channel and I will actually mention a link to that in the description below please uh give me a like and comment uh that really helps my channel click on the Subscribe button if you want to see more of my videos I also have some data structure videos coming up so stay tuned for that I hope you have a good rest of the day thank you so much bye
Generate Parentheses
generate-parentheses
Given `n` pairs of parentheses, write a function to _generate all combinations of well-formed parentheses_. **Example 1:** **Input:** n = 3 **Output:** \["((()))","(()())","(())()","()(())","()()()"\] **Example 2:** **Input:** n = 1 **Output:** \["()"\] **Constraints:** * `1 <= n <= 8`
null
String,Dynamic Programming,Backtracking
Medium
17,20,2221
133
welcome back to our js today's question is leak code 133 clone graph so given a reference of a node in a connected undirected graph return a deep copy of the graph each node in the graph contains a value and a list of its neighbors so with the test case format for simplicity each node's value is the same as the node's index for example the first node with value equal to 1 the second node with value equal to 2 and so on the graph is represented in the test case using an adjacency list so an adjacency list is a collection of unordered lists used to represent a finite graph so each list describes the set of neighbors of a node in the graph the given node will always be the first node with value equal to one you must return the copy of the given node as a reference to the cloned graph so as you can see in example one we cannot exactly return the original graph we also cannot return a copy of the original graph if the nodes are not in the correct position we need to return a copy or a reference of the original graph where the nodes are all in the correct positions and they are pointing to the correct neighbors okay so there are two ways we can do this we can either use bfs or dfs in this solution we are going to be utilizing dfs because it's a slightly more intuitive solution within this we need to create references so we need to create copies of each one of these nodes and we need to make the connection between these nodes as well because remember this is an undirected graph so that means that this pointer right here is connecting both ways which makes this problem a bit trickier like any dfs recursive solution we have base cases that we need to create so we have base cases and we have a cancellation so the base case firstly if we had the smallest graph possible so we had a graph which was just equal to null so if node is equal to null what are we going to return from this well we are just going to return node right so we're going to return node which is the value of null now within this as i mentioned there is an undirected link between all the nodes within this graph and we're going to have some kind of visited object that is going to store the nodes mapping to their copies and the reason for this is to stop an infinite loop from a current so say we did a recursive call from one to two is obviously going to check its neighbors as well so it's gonna go back to one is going to check its neighbors it's gonna go back to two so we need to make sure we have a visited object to stop that from occurring so let's put our visited object here okay and this is going to be a mapping between the node and its copy so let's start out this dfs recursive call so say we start at one we want to check if the node is equal to null which is not we're going to have copy which is going to be a reference and we're going to have neighbors which is going to be the neighbors that are going to populate within here so before we carry out a recursive solution to go to two we need to add this within the visited set right we need to add this within visited so we need to create that mapping so one is going to be mapped to a copy now this asterisk means copy in this case so we can add this within the copy now we can go to the next neighbors okay so we can go to two and we can go to four so let's say we went to two right so we're currently at node two let's add the references so copy and neighbor we check if the node is equal to null it is not we need to check whether node and the copy is within visited so this will be another base case so if visited at node.val at node.val at node.val because remember these are objects here and node has a value property does not equal null then we have already visited that node so we can just return that value immediately so that's the second base case sorted so at this node we've checked if it's equal to null we've checked if it's in visited it's not so what do we add it to visited and we create that copy so two copy goes up here then in order to populate these neighbors we need to recurse to its neighbors so we go to three and we go to one let's say we went to one we checked to see if one is within visited it is so what do we return that value so we return one here so it's going to be the copy so that part of the recursive call has been done for two now we go to three so we're at three we check if this is equal to null no it's not we check if this is within the visited object it's not so we add it within the visited object and we can add its reference so three it's neighbors so in order to get its neighbors it needs to carry out the dfs function so we go to two and we go to four so say we started off with two we check if two is in visited it is so from here we can just return a copy of two so this arrow right here has been resolved we can remove it we go to four we're at four now we check if it's equal to null it's not we check if it's in visited it's not so we can add it to visited so we create the copy look at the neighbors so in order to get the names from this one we go up to one and we go back to three if we go to one we check if it's equal to null it's not we check if it's in visited it is within visited so we can return a copy of one so one copy goes in here this arrow is being resolved then we go back to three now three is within visited so we return the copy of three so three goes into neighbors now we have a node that is completed so it has a copy it has both of its neighbors as copies so what do we do in this situation so basically what are we returning up the call stack so what are we going to pass back to three well we need to pass back the node right so we're going to pass back four so four is going to go in here we're at 3 has been complete so we can actually tick these off so what do we need to return to 2 well we need to return 3 and then once we get back to 2 we can add 3 into neighbors we can remove this arrow the node two has now been complete we need to go back to one but what do we need to pass back well we need to pass back two so two goes along here two goes into neighbors here we remove this arrow as you can see we only have one neighbor within our copy so we need to carry out the recursive call going to four here so we go to four we check if it's in visited it is within visited so we return the copy of four so that is that and then we can just remove this and finally we are left with a complete copy of the graph and that is the basic understanding of how to solve this problem time complexity for this problem is o n plus e where n is equal to the nodes and e is equal to the edges and then space is equal to o of v where v is the values we've envisited so let's start this off by creating visited object let's create the dfs function we're going to pass a node as parameter we need to return dfs passing in node so remember the first thing to do is add the base cases so if node is equal to null we can return node then we need to check within the visited object whether we have the current node and its copy so if visited at node.val does not equal null at node.val does not equal null at node.val does not equal null then we can just return that otherwise at this point we need to create a new node so we need to create a copy so root is going to be equal to new node passing in node.val passing in node.val passing in node.val then we need to set in visited at node.val at node.val at node.val to root so we need to set to the copy we just created and lastly we need to create the recurrence relation and the way we do that is we loop through the node's neighbors so let neighbor of node.neighbors got to make sure i spelled this right because it's the american spelling now here's the tricky part we've just created this new copyright we've just created this copy we've passed in node value so at this moment in time neighbors is going to be empty so it's going to be an empty array so what we need to do is we need to allocate some values to that so neighbors sorry neighbors we need to push in and what we're going to push in is the dfs function passing in neighbor so we are passing in or pushing into neighbors of our copy the result of this recursive call passed in neighbors and what this will do is it will create the connection between each node and then finally we need to return root so what do we need to pass back up the recursive call stack well we need to pass root in order for the neighbors of the copies to be populated let's give this a run submit it and there you go
Clone Graph
clone-graph
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph. Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph. Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors. class Node { public int val; public List neighbors; } **Test case format:** For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list. **An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph. **Example 1:** **Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Explanation:** There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). **Example 2:** **Input:** adjList = \[\[\]\] **Output:** \[\[\]\] **Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. **Example 3:** **Input:** adjList = \[\] **Output:** \[\] **Explanation:** This an empty graph, it does not have any nodes. **Constraints:** * The number of nodes in the graph is in the range `[0, 100]`. * `1 <= Node.val <= 100` * `Node.val` is unique for each node. * There are no repeated edges and no self-loops in the graph. * The Graph is connected and all nodes can be visited starting from the given node.
null
Hash Table,Depth-First Search,Breadth-First Search,Graph
Medium
138,1624,1634
174
hey everybody this is Larry this is day 21st of the June midco daily challenge let's get started hit the like button to subscribe one let me know what you think join a discord for a chat and dungeon game the demons had captured the princess p.m. put imprisoned her in the princess p.m. put imprisoned her in the princess p.m. put imprisoned her in the bottom right corner of a dungeon the dungeon consists of M times and worms lay down a 2d grid our night was positioning positioned initially positioned in a top left room and must fight his way through the dungeon to rescue the princess the night has an initial help point represented by a positive integer if at any point is health point drops to zero or below he dies immediately some of the rooms are guarded by demons so the night loses health upon entering these rooms under website either zero or contain magic orb stat increases the Knights health positive integers in order to reach the princess as quickly as possible tonight decide to move only right word or a downward you need step Y the function that determines the Knights minimum initial path so that he is able to rescue the princess for example you have this thing okay hmm there's no upper bound couldn't contain power-ups hmm I think one thing tower power-ups hmm I think one thing tower power-ups hmm I think one thing tower maybe think about is that well there's no constraint on the problem which is a little bit tricky but I think there a couple of ways to think about is farm the way that I know and I don't know if just once in time but one way to think about it is that this is dynamic programming and the question is well let's say you solve a help of X health if you have X health can you get to the bottom right with more than so health along every step of the way right and you can do that's a way standard dynamic programming it's not an easy turn every programming but its standard ish and if you say and I say you are given that then you're able to do a binary search from that K from you know I'm I guess not zero but one to some infinite number and then you just have to want that every time and that will give you n times M for the dynamic programming times log of K where K is the range of the possible health I think however though you can also use just regular dynamic programming and in that way it's a little bit greedy but the trick observation to note in this problem and I think I've done a similar problem in the past where it didn't work out for me instead and one thing that I want to point out is that in a lot of dynamic programming problems and these two one stat on lead code there the you could solve them symmetrically and what I mean by that is that you're having a matrix or in a way which is a 1d you know where your 2d matrix what do you mean is that going from bottom oh sorry top left to bottom right or going from bottom right to the top left it's symmetric in that you could go either way and it's the same answer or if you have a 1d version going from left to right or right to left however in this problem because of the constraint that you can not drop to 0 or die then that means that there's a strict ordering right and that means that you cannot just go you know there has to be an invariant that you hold where the solution that every cell means that you are still alive right so based on that knowledge we should be able to come up with the solution and okay so having said all of that let's think about how to do it which is Emily let's just implement it top-down I have a video on dynamic top-down I have a video on dynamic top-down I have a video on dynamic programming that converts top-down at programming that converts top-down at programming that converts top-down at memorization - bottoms up dynamic memorization - bottoms up dynamic memorization - bottoms up dynamic programming take it a look and then we'll figure it out together but for this one that's just solved a thing right which is that's given a you know calculate just from X Y or actually R or C four rows and columns let's just two rows is you go to the length of the dungeon columns is you go to the length of the first elements and now let's just check that it was a zero we return actually it's not clear that we know what we should return so let's just say one right goes do we turn one okay and then we could return calculate from zero right - all the way to from zero right - all the way to from zero right - all the way to whatever and at each cell what we want is get the minimum to the minimum health that you can be on this current cell right so what does that mean well base cases if R is equal to Rose and wait now this is minus 1 close minus 1 so this is the base case and in this base case I guess we have to be at least 6 because you want to end with more than one right so what is that so return dungeon of I see they just say hmm so we want the end to be at least one or the negative answer plus one right because if it's negative fire you want it to be you want the answer to be sex if it's you know so forth uh-huh and the other you know so forth uh-huh and the other you know so forth uh-huh and the other cases of it's positive what happens if it's positive well if it's five then that's fine your health coming in should still be at least one so that's that worry - that's what it's referring that worry - that's what it's referring that worry - that's what it's referring to okay I think that's okay and then otherwise if okay I think that's the only base case we need depend on how we get to the edge so yeah so now we just do so best is you go to let's say infinite health can we do better than infinite help well we go to the right so we go R plus 1 C but this assumes that if R plus 1 is less than rose what this gives us the minimum thing oh yeah so actually the that's cool there's a lot of cases so I'm trying to do it really slowly because I'm thinking about it for but basically I say I mean I and there's some symmetry here anyway but so you're going from one cell to another what does this mean well let's say negative 5 to 10 well the 10 means that the minimum health going in has to be 1 so okay I'm going to say now have a helper function that gives me the score of a given cell so that I don't have to keep on busy is the same logic here but it allows me to focus on the code a little bit so hmm it's really tricky to get exactly right but okay so now the better the score down here is that well it has to be at least six right so actually this should be the score of the current cell oops and then now so we have to take one of two paths right and what is the clean way to do it because there's two cases and we want to okay path is equal to zero and we want to take the case that is the minitor so we want to take the path that gives us the min and then we have to check that against best okay so this should be infinity and then path is equal to 2 min of path and calculate L plus 1 C and if C plus 1 is less than number of columns then path is equal to min a path calculate C plus 1 and then we turn the max of these two it because it's the current score or path so okay so we turn best max the best and path and I think that's all you need and yeah ok that's not great the question now is whether I'm off by one or is it just Wang all right let's take a look and I know that I haven't done the memorization yet don't worry I won't get to it but debugging zouzou it's at 6 so ok let's look at some base cases where so 2 is gonna be 6 here we need to help to be 6 oh I didn't add to score here I keep the minimum but I do but I don't take a counter and addition so that this means that coming here ok so I just think I didn't consider a part of it that's all so here it needs to this ends it to be at least 6 here that means going here and the answer could be 5 all right yeah so I only considered a case but in add things so ok so we just have to so the good part is that we just have to change this a little bit hmm but in what way I just want to be careful so this is one then this path would be yeah so this is this has to be 6 so this just has to be 5 right so okay so the path yeah and then the path I was you're trying to think okay the score thing maybe I just got it confused right so now path plus G goes to and one of these has to be true because otherwise this is true so we don't have to worry about just being infinity but as you go to dungeon of or see if it's 1 or minus this because we won't wonder inverse of that I think there is we do need to consider it a little bit I don't have path up I don't have press we do have to be a little bit careful because I think the consideration is that it cannot be negative right so in that if it's negative then we have to return a different answer so let's do this for now and then we'll see what the answer is okay this is not wait see when it's negative 24 what yeah okay so the time instead of it's 1 it gets too dirty and then I guess that makes sense in some sense but ok what's 1 2 okay so that's 5 - that one's correct but these are the - that one's correct but these are the - that one's correct but these are the ones that we talked about ones are the ones that we talked about where you know you cannot go negative so it's one good enough yeah I guess so we just have to do this okay who is this way because well mentally think a little bit yeah because this is the minimum a health to make it one right so okay I hope this is right I don't understand this you know there's a bit awkward but let's do this dynamic so this is just a recursion way there's no memorization there's no dynamic programming so what do we do now is think well how do we convert this to memorization well looking at all or can all can only be between zero two rows right and see can only be between zero two columns so that means that the these are all the possible inputs to this function right and because of that means that there's it's gonna take all of our times C times because that's the number of possible inputs and for each of these inputs we're only doing all of one operations you know joining meters but that's okay so in that sense the complex there we are times C which is the number of possible inputs and of one which is how much each input how much work does each input - and then how much work does each input - and then how much work does each input - and then total time is equal to o of times C times one I guess which is you go to Oh of all the times C and then space well it'll be more obvious so I'm gonna you know hold you in suspense for now but that's implemented dynamic programming then the memorization so cash is equal to with let's just say so it doesn't really matter times cause plus 1/4 so this just it's times cause plus 1/4 so this just it's times cause plus 1/4 so this just it's way it's very pythonic but it basically creates a columns plus 1 times R always plus 1 matrix so yeah so then and then just to check that we were done then already calculate it is you go to basically this okay for us and we'll use it in a way that most see in a second and then here well we still want to return this just a base case but otherwise well let's see if it's cash if calculated of r and c then we return the cash otherwise at the very end at the way and we set the calculated result is the I'm sorry the cashed we sell and it's equal to this thing we set to calculated is equal to true because we calculate it and then we return the cash result and that's all there is and going back there's space complexity it's gonna be O of n times M or low Sam's columns because well that's how many cells we have in the matrix we have two of these matrix these but otherwise is the same so let's run it again just to be sure okay looks okay let's test some base cases or like edge cases whether empty array and to rate the other way negative 5 from the beginning uh doesn't have to be at least two I don't know I guess it doesn't it's not clear but yeah negative five in the beginning and then let's just say what wafer so that we see and in the other way we're made the princesses have a negative and nothing else that we have to count the last one that's her which one is that this is just a leak Oh specific error maybe I maybe these are not valid input to something let's try that again first inside is our but just have a typo okay I think I just have a typo somewhere oh I missed commas okay well seems like some of the empty cases cannot be happen so let's just remove to her and Iona okay so that looks good are there more places I guess let's just do a couple more for funsies and then just add disappear or positive numbers which should give me just one okay cool so did that looks good that's submit sweet okay cool yeah so that's kind of the problem for today I think for this one as I point out it is great if you are trying to you know it's up solve this and practice converting this from memorization - converting this from memorization - converting this from memorization - Bottoms Up dynamic programming and I urge that you do it's good practice I have a video below on the link somewhere but also keep in mind that the order matters and that's what I said in the beginning where you know you cannot go the other way because at a certain times because max dysfunction this match the path is m1 it could get into a situation where you can go in one direction with a lower number than D then the answer going from the other direction so be careful about that or if you want to just learn about the properties of why that is play around with that and see why that is the case and that's like one of the best way to learn is not only looking up good solutions but playing around with bad solutions and try to figure out why they're wrong in this case it comes up in random places for dynamic programming but yeah in terms of interviews I think this is a little bit on the hotter side but still doable so I recommend practicing it and oh boy there's a lot of things and there's you're very good at dynamic programming and I still don't consider I am there's a lot of things to practice on but - a lot of things to practice on but - a lot of things to practice on but - caching and stuff like that and then converting it to bottoms up and then do the space optimization yeah and for compared programming this is probably very standard and you really need it to be good at stuff like this because it comes up all the time yeah that's all I have for today's forum let me know what you think and - like my let me know what you think and - like my let me know what you think and - like my little subscribe button and join the disco chatter and I will see y'all tomorrow bye
Dungeon Game
dungeon-game
The demons had captured the princess and imprisoned her in **the bottom-right corner** of a `dungeon`. The `dungeon` consists of `m x n` rooms laid out in a 2D grid. Our valiant knight was initially positioned in **the top-left room** and must fight his way through `dungeon` to rescue the princess. The knight has an initial health point represented by a positive integer. If at any point his health point drops to `0` or below, he dies immediately. Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers). To reach the princess as quickly as possible, the knight decides to move only **rightward** or **downward** in each step. Return _the knight's minimum initial health so that he can rescue the princess_. **Note** that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. **Example 1:** **Input:** dungeon = \[\[-2,-3,3\],\[-5,-10,1\],\[10,30,-5\]\] **Output:** 7 **Explanation:** The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN. **Example 2:** **Input:** dungeon = \[\[0\]\] **Output:** 1 **Constraints:** * `m == dungeon.length` * `n == dungeon[i].length` * `1 <= m, n <= 200` * `-1000 <= dungeon[i][j] <= 1000`
null
Array,Dynamic Programming,Matrix
Hard
62,64,741,2354
244
how's it going guys down here in this video we're going to do number 244 shorts or distance number two so we're asked to design a data structure that'll be initialized with the string array and it shouldn't answer queries to the shortest distance between do two different strings from the array so we want to implement the word distance class starting with initializing the object with the strings away word stick so in this particular case we basically just want to simply initiate our right here so that we can use it later and then we want to launch a shortest uh distance which we want to call the shortest and shortest we give it a word one and a word two and a word one in word two it's going to return us the uh the minimum distance so this is really uh similar to shortest word distance one which basically you use the sliding window i don't know if i actually did the video but let me know in the comments section below if you want me to solve this particular problem i'd be very happy to anyway basically what we want to do is uh in summary we want to initialize our uh word stick tier and then we want to find what the shortest value is between the words one and word two that's given over here right so how do we do that well let's start nice and simple with the init function so basically what's happening here is we want to initiate the hashmap right so the question is how do we do that well in python we have a very convenient uh function called the default dict that we could probably use and that's going to be pretty uh straightforward so we're going to call it hashmap because i'm very not creative so default dict list so that's going to launch our hashmap and we're simply going to store the values so what i'm going to do is i'm going to write what's going on over here while we're going through the code right so for index and word in a new narrate words dipped what we're gonna do is we're going to append all the values into our hashmap right so self.hashmap word got append and we're going to append the index right so this would be the word for example so all of these are going to be the word and we're simply going to represent that by index below so we take a look over here i would be like practice zero etc that's kind of how it works there so zero one two three and four right so now that we have that in store uh the one thing that we can probably define the time complexity at this point or not the time complexity but the space complexity given that we're using a hash map we know that our space complexity will take oven time all right so how do we define the shortest well i'm going to talk about the brute force way to do it and then i'll talk about the optimized way so let's write that down so the root so the brute force solution is going to be an o of m by n times solution and it's going to be a basic one-liner and it's going to be a basic one-liner and it's going to be a basic one-liner basically we're just going to return the minimum of the absolute value of i will call it index 1 minus index 2 for index one in self dot hash map word one basically we're finding the word one inside of the dictionary and we'll do the same thing for word two as well for idx2 and self dot map word two and that should work all right submit accepted uh 155 milliseconds but the question is we probably can do better than an o of n by n we could probably do uh o of m plus n instead so how do we do that well i set up a little example here what we can do is you can find the exact locations of exactly what the locations of each of the word is in our hash map and then as you go along as you start to iterate through both the word one array and the word two array we find out we keep track of the minimum and then basically we return the minimum so we're going to start off with a minimum value of infinite right and now we have to define exactly where our each of the words are right so i'm going to take four examples here or rather two examples and it's become it's going to become clear because obviously if you do the first example we know that coding occurs once at index 3 and practice occurs once and we know that this is going to be three minus zero is going to be three whereas we have makes which occurs twice at index one and index four this is where the tricky part comes into play because if it only was this it would be pretty easy you just take the two of them take the minimum and you're kind of done but you're not because makes can occur twice inside of the array here and then coding here appears once at index three so what we could do here is we know that minimum is infinity so if we go here we compare say one and three so three minus one obviously we're taking the absolute value of this we know that our minimum sorry if you can't read that but that basically just says minimum so 3 minus 1 is 2 is obviously greater than infinite so we're going to pass so that's going to be 2. that's our new end minimum right and then we move one step over and we represent this 4 right and then 4 minus 3 absolute value is going to be one and that's what we're going to return right and we see here that it is indeed what we're going to return here right so now the question is how do we represent that in code right we have the brute force solution but how do we represent the optimized solution so let's do that of m plus n all right so the first thing that we want to do is we want to initiate our indexes so these are going to be our indexes here so index one is equal to self dot hash map word one similar to what we did up there index 2 is equal to self.hashmap is equal to self.hashmap is equal to self.hashmap word2 alright and then we want to have a pointer because we want to go ahead and represent one as i and one as j right so as you start to go over as you start iterate if we see uh we iterate over i if we get to the end of i then we're going to start iterating over j right so what we're going to do is we're going to iterate i is equal at position zero over here inside of our right here and we have j is equal to zero and we're going to set uh our answer to start with an initial value of max size so i'm going to import from sys import max size all right so we're going to take the minimum of that so that's going to go away pretty quick as you can see here you could also use float infinite right so float but i prefer using max size just give you guys some alternative ways to do it so what do we do here we're going to set a wild condition so while uh i plus then length of uh index one and j is less than the length of index two so basically we're just iterating through the way here if we ever get to the end of both i and j we're gonna break out a loop and we're just gonna return the answer right let's write that down here all right so what do we do here so we're going to take the answer is equal to the minimum of answer and the absolute value of index 1 i minus index 2 j right and all we're going to do is we're going to set an if condition so if index 1 i is less than index to j what we're gonna do is we're gonna increment i plus one right else j plus minus one so you might be asking yourself what's happening over here and why uh i want i plus one uh the index of i to be less than index uh why i want my index j to be over here and obviously they didn't really give us very good examples here so let me explain that real quick let's just say that we had a different array here and we had the numbers uh three five and seven right so the reason why we want to have uh j here going first is we want to have a kind of this one trailing right because no here generally uh if we take these numbers here so 7 minus 4 then we're going to have uh it really doesn't matter exactly what area you do it but this is just uh my preferred way uh it's gonna work both ways but as long as this one's gonna break out of the while loop then that's really what matters at the end of the day as long as you're incrementing i first and then j or j and i first that's really what matters at the end of the day right so if you run this code we can see here that we have improved our run time here and that's an o of n by n right so if you guys enjoyed the video don't forget to hit like comment subscribe let me know in the comment section below if anything was unclear i'm sure that uh questions can come up so don't be don't hesitate to leave your comments down in the comment section below and i'll see you next time
Shortest Word Distance II
shortest-word-distance-ii
Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array. Implement the `WordDistance` class: * `WordDistance(String[] wordsDict)` initializes the object with the strings array `wordsDict`. * `int shortest(String word1, String word2)` returns the shortest distance between `word1` and `word2` in the array `wordsDict`. **Example 1:** **Input** \[ "WordDistance ", "shortest ", "shortest "\] \[\[\[ "practice ", "makes ", "perfect ", "coding ", "makes "\]\], \[ "coding ", "practice "\], \[ "makes ", "coding "\]\] **Output** \[null, 3, 1\] **Explanation** WordDistance wordDistance = new WordDistance(\[ "practice ", "makes ", "perfect ", "coding ", "makes "\]); wordDistance.shortest( "coding ", "practice "); // return 3 wordDistance.shortest( "makes ", "coding "); // return 1 **Constraints:** * `1 <= wordsDict.length <= 3 * 104` * `1 <= wordsDict[i].length <= 10` * `wordsDict[i]` consists of lowercase English letters. * `word1` and `word2` are in `wordsDict`. * `word1 != word2` * At most `5000` calls will be made to `shortest`.
null
Array,Hash Table,Two Pointers,String,Design
Medium
21,243,245
429
hi friends welcome back today we are going to solve it code problem for 29 in early 3 level order traversal so given an n retrieve written level order traversal of it nodes values nr3 input serialization is represented in their level order traversal each group of children is separated by the null value see examples below so they have given us two examples so let's just take this first example and we will discuss how we can implement this uh so as you can see here they have given us the node class and the node class has you know it has a value integer and every node will have list of nodes as their children so as you can see one will have children three two and four so uh the number of children any node can have varies so that's why it is an arri tree in general binary tree we only have you know left and right children so only two children max maximum but this is the energy tree so we can have many more children than two so uh let's just take this example and let's just discuss over here so we are actually going to solve this problem uh using uh you know like a level order traversal of a binary tree so uh this is a ah not a binary tree actually this is a narratory because it has many more children so but the concept is same you know like the same concept we can use that we generally use for binary trees so we are going to use a queue of nodes here so let me just take this pin here so we are going to use a queue of nodes uh and what we are going to do is as we travels each level you know we are going to put the children of that node in that level you know into the queue so for example uh so for example if we let's say uh every tree has a levels you know so this is a first level of this tree this one is a second level of this tree and this is the last level of the tree so this is the last level of the tree as you can see so uh here this element is 5 i think it's not visible but yeah that element is 5 it's just going uh in the back side so what we are going to do is we are going to start level by level so first we will start with the root right so we are starting at the root so we will take 1 and we will insert this value into our queue so this is our q and we insert 1 here and we are going to like i'll show you the implementation at the same time when we are you know discussing the solution so here we are going to you know get the root in the level order and we are expected to return a list of integers so i just re defined the result of a type list of integer that we are going to return at the end here and first we will check if root is not then we are just going to return that empty list right because we don't have anything to return in that case but uh here i defined the queue it is just a new linked list and we first offer a route to the queue you know and then we will add that q that roots value into the list of integer because for every level that we traverse you know we will have a list of integers that we keep adding into this result right so that's how it will work so uh after we are we added the root into the queue then we will just iterate through the queue until it becomes empty right so all the way like all we will iterate all the labels all the nodes and we will keep pulling the nodes you know from the uh queue so let me explain here so first we actually added the root into the queue so one then when we go to the next iteration into that while loop then we will add we will pull that one from the queue and we already have list of one right here so we will have only one element in the list because only one element for the level so next we will um get all the children of this one right three two and four that we will actually when we fall the one we will iterate through all its children and we gradually put those children into this queue so we have like three then two and then four because we add these children into the queue as you can see here so here we uh get the q size here and then we are just looping like a for loop until i zero i is less than psi is i plus so we will keep pulling the nodes from the queue and we will get the children of that nodes for each node there will be multiple children and so we will get a list of nodes here right and we are going to again loop through all the children and we will keep adding into our list those children's values here right and at the same time we will be offering that uh children into the queue so uh as you can see this once this for loop completes then we will have the list for that level basically right so here you will see that as we traverse now we are done with level one so we are done with this level now we are traversing and we are doing the next level which is this three two four so we will keep pulling element and we will keep appending this element into the queue right so we fall the element three here we added into our list here and at the same time we see this five and six as a children of three right so we will keep adding this into the queue right so five and six we added but when we start like for that level we already know that we have to only pull three because we already got that size here right so first we get the size of the queue in the start of the iteration so we follow three then we added the five and six children into the queue then we pulled two from the queue then we added into our list and we call four and we added into our list so that's how we have three to four list as you can see here so one is the first list which is a sub list basically of the output right then three to four is another list so we are done now at this uh level two right we are done now so now we have this another level which is like 5 and 6 right so we will now again uh define another list here for next level so as you can see here we always in this while loop first thing we do is we def we create a brand new linked list because we don't want to reuse the other list right that we had in the previous iteration it should be a brand new list for every level that's why we created a list so now again we will call first element 5 does not have any children here so as you can see 5 does not have any children and 6 also does not have any children here right so we just add five then we pull six we don't have any children to add and then we will just return that five six here as the third sub list right so this is how we got this output by using a leveled level order traversal of n arry tree so we use the queue of nodes right so queue of nodes we used here as you can see this is q of nodes and this is just a new linked list right so that's pretty much it i think i explained it in pretty details that we go each level by level we keep adding the element into the queue and once we pull that element then we will keep adding its children actually into the queue so uh and then you know we'll keep processing until we are done with all the children right so for example let's just modify this example little bit for more things so let's say if two has more children let's say it has a two children let's say right say one and eight here so 7 and 8 right here so when we are processing this 2 here then we now let's just uh consider this example from the beginning right so we processed a 1 first which is the root so we added this and we have this list as one now we are again now processing this three two and four right so we added three here then we added two because these are children of one so once we add these two here then you will see that two has a say one and eight as a children right so for three we have five and six already added so we have to add the seven and eight here right in that case say one and eight and then we will have four here right four does not have any children to add then in the next iteration which is the third iteration we will be processing this new this level right this whole level so we will have uh it will like we will keep pulling the element so we will have five here five does not have any children so we don't add anything in the queue six here six also does not have any children then we will add seven and we will add eight at the end say one and eight they also don't have any children so this is how it works actually so uh i am going to push this code into my github repository and i'll give you the link so you can take a look into details but we actually took let's take the both examples that they gave us so first one is the example that is there and let's take this another example here and let's just run these examples first so yeah so both examples are passed so let's quickly submit this solution so the code got accepted it runs to ms and it's like 85 percent on runtime so i hope you uh like the solution of uh nre tree travels tree uh level order traversal using queue uh so if you like the solution please click on the like button and subscribe to my channel i often keep posting the lead code problem solutions and java j2e related interview materials so if you are interested please subscribe to the channel thanks for watching the video
N-ary Tree Level Order Traversal
n-ary-tree-level-order-traversal
Given an n-ary tree, return the _level order_ traversal of its nodes' values. _Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples)._ **Example 1:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** \[\[1\],\[3,2,4\],\[5,6\]\] **Example 2:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** \[\[1\],\[2,3,4,5\],\[6,7,8,9,10\],\[11,12,13\],\[14\]\] **Constraints:** * The height of the n-ary tree is less than or equal to `1000` * The total number of nodes is between `[0, 104]`
null
null
Medium
null
114
hey guys welcome to algorithms made easy my name is khushbu and today we are going to see the question flatten binary tree to a linked list given the root of a binary tree we need to flatten the tree into a linked list the linked list should use the same tree node class wherein the right child pointer will point to the next node in the list and the left child pointer will always be null the linked list should be in the same order as pre-order traversal of a binary order as pre-order traversal of a binary order as pre-order traversal of a binary tree which means that you need to first process the root then left and then right given this example the pre-order traversal for this example the pre-order traversal for this example the pre-order traversal for this would be one two three four five and six and so we are going to append these nodes into the right of the nodes so it becomes one two three four five six and all the left nodes for these are null similarly you are given examples two and three now the follow-up over here is that can you the follow-up over here is that can you the follow-up over here is that can you flatten the tree in place with o of one extra space that is no extra space at all so let's first try out a simpler solution and then we'll go with the follow-up follow-up follow-up so here's the tree that is given to us and now we need to convert it into a linked list so firstly i need the pre-order so firstly i need the pre-order so firstly i need the pre-order traversal and this is what it would look like and now i need to join this as a linked list but since we need to use the tree node itself we need to have two pointers that is right and left so the right pointers would be the nodes and the left pointers would be null so our linked list becomes like this which is shown in a tree format so that's about the visual representation of the question that is given to us now let's see how we can solve this so firstly we will see the recursive solution let's just take these three nodes to make the process simpler so now we know that we need to go in the manner root left and right and attach all the nodes in right side so after 1 we need to attach 2 in the right and after 2 this 5 will go to the right of 2. so what we are going to do over here is we know that we need to move this 2 to the right of our root node that is 1. so we do that and we take this 5 in a temporary variable because we need to attach this 5 to the tree as well so now when we have the left tree attached to the right side we need to attach this right tree to the right side again and so that gives us this particular tree which is in fact our linked list now we also know that we need to make the left of this node as null so let's break these steps further down and see how it looks like so we'll take this tree we'll take the left in a temporary variable and make the left of the root as null next step is to attach this to the right so we need this in a temporary variable also and then attach 2 to its right which gives us 1 attached with 2. now this 5 is still not attached properly so we need to attach this 5 to the right of 2. so this is about the solution for just 3 nodes that is the smallest we can have now what if we are given a bigger tree if we are given bigger tree we need to do the same steps but instead of taking the left and right we would be having a left and right tree and we need to flatten these two trees also so here's what the algorithm would look like we'll take a temp variable to store left and right as we were doing for only three nodes then we'll make the left of our root as null and then we'll recursively flatten the left tree and the right tree after we have the flattened trees with us we are going to attach the left one to the right side and then traverse to the bottom most part of that left tree because we need to attach the right part to the end and so we are going to traverse till the bottom most node in the attached part that is the left part that we have attached and then attach the right tree to it that we have already flattened so that's how we applied the same logic that we applied for three node to a bigger tree by just calling these function recursively for left and right now let's go and write some code for this and then we'll come up with the solution for the follow-up that is for the follow-up that is for the follow-up that is given in the problem we are going to use the same flattened method which would be called recursively on left and right so initially we say that if my root becomes null i just need to return or stop because that is the exit condition then we need to take the left and right in a temporary variable so let's take that after taking the temporary variables i need to make the left as null so i do root dot left equal to null and then i need to call the functions recursively to flatten my left and right trees that i have got so i will call flatten on left as well as on right now that i have my trees flattened with me i need to just attach it where it is necessary so my root dot right becomes the left part that i had and then i need to go till the last of the currently attached temp lift and then attach my right to it so let's take a node that is a current node that would be my root node and then while its right is not null i am going to update my current to point to the right most node so in this way i will be reaching the bottom most node in my flattened left tree after i am done with this i'll append the right flattened tree to this current node so that is going to solve my problem so this completes the process of attaching the left part to the right and making a linked list out of it so let's see whether it runs perfectly and it's giving a perfect result let's submit this and it got submitted so over here the time complexity is of n that is the number of nodes that we are going to have in the tree and the space complexity would become the height of the tree for recursion stack now let's see how we can reduce the space to o of one to reduce the space in a tree traversal one of the methods is to use morris traversal and that's what we are going to do in this particular problem so let's see how it works so we are going to start from the root that is from the node 1 and then we'll take the left of it while the left is not null we are going to go to its rightmost node and attach its right to become the right of my route so you see what is happening over here is that the path that i am going to travel is 1 2 3 then i'll go to 4 and instead of traversing back to 1 and then going to 5 i have 5 attached to my node 4 itself and so that is the way i am storing the next pointers in this particular traversal by not using any extra space but changing the structure of my tree so over here i am connecting the next of four to the right of this root node after i am done with that i am going to remove these pointers the left of my root node would become null and the right of my root would become this left tree so that goes like this that is i have taken the left part and have put that into the right of my root and i have made the left of the root as null again we will be performing the same steps so we'll be going to the right side of my root by taking this node 2 and then i'll repeat the process so for that i'm going to go to the left and its right most node since 3 does not have a right the right of 3 would be attached to the right of 2 which is 4 because this is the next node that i am going to traverse and so now i am going to break these links and attach this left to the right and make the left of root as null now if you see my tree is having all the nodes in its right itself let's flatten this out and see that's how my tree looks at this particular stage now again i'll be going to its next and i'll repeat the process since this 3 does not have a left i'll still go to the right node and complete the process till the end and in this i am also having this null nodes attached to my left so that's how my morris traversal is working that is i am using the null pointers of my leaf nodes and i am re-routing those to the correct and i am re-routing those to the correct and i am re-routing those to the correct nodes in which i want to travel and that's how you save the space so that's all about the morris reversal let's write the code for this one now so this one is going to be an iterative solution i'll still take if root is null just return because we do not need to do anything and after that i will take a while loop while my root is not equal to null now what i am going to do is i am going to check whether my left is null or not so lets do that so if my root dot left is not null i am going to go to the right most child of that left node so now let's take a few variables i'll take a left which would be root dot left and i need a temporary variable to traverse in the right side so i will take this current and that would also be initially equal to left and i'll take a while loop and while current dot right is not equal to null my current would go to current dot right now once i have reached here my current dot right would be equal to the root dot right that is i am attaching a pointer to the right of my root node so this is exactly what we are doing in morris traversal main step once i have this now what i want to do is i want to detach my notes from the root and make its left as null so my root dot left becomes null and root dot right becomes left that is everything i had in my left tree so this is going to attach everything and this will take care of the loop now if that is not the case i also need to update my route so at the end i am going to do root equals root dot write so this would go to the next iteration and finally when the root becomes null wheel return from here and that would be our flattened tree or the link list and this will be a capital n and let's try to run this and it's giving a perfect result let's submit this and it got submitted so over here we do not have any recursion we are not using any extra space and so our space complexity is o of 1 and the time complexity still remains o of n because we need to iterate on each and every node in our tree so that's it for this video guys i hope you like the video and i'll see you in another one so till then keep learning keep coding bye you
Flatten Binary Tree to Linked List
flatten-binary-tree-to-linked-list
Given the `root` of a binary tree, flatten the tree into a "linked list ": * The "linked list " should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`. * The "linked list " should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree. **Example 1:** **Input:** root = \[1,2,5,3,4,null,6\] **Output:** \[1,null,2,null,3,null,4,null,5,null,6\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-100 <= Node.val <= 100` **Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
Linked List,Stack,Tree,Depth-First Search,Binary Tree
Medium
766,1796
76
now I will just try to solve the minimum window substring profit give us doing s and the string G find the minimum window yes which will contain all the characters in T internment camp in capacity pick an example include s equal to the he equal to the output note there is no such window in a circus uncapped in t that we will return empty string if there is that window your guarantee that they will always be only one unique minimal window yes I think it's a classic problem which will use the sliding window technique what is the study window technique basically is similar to the two pointers technique which we will add first we use two pointers low and high and the adverb gimme the high end the lower are all above at index 0 and we'll move high forward to find of the little window now they will move low forward to get a minimal valid window so basically it is the idea okay let's do it first we will do some education check if our sorry if se-ho true now or s start lengths if se-ho true now or s start lengths if se-ho true now or s start lengths equal to 0 which means we'll never find a finder any our window so it'll return empty string then we need a map to get each character's frequency but this problem only have ASCII code so we can use a inter array but if you have under other characters of all you can use a hash map in this case we can just use 128 so sorry you eat 128 and then we iterate in the string T to care to the frequency of the characters to char array yes the map c plus okay now we get to the focus let me sink oh how many more do we need first we need up out why we want to see such as G less equal to 5 then you should find the four captures so the characters should be the dance when account when a counter variable equals with you we know that we have found a window right niche initially the count equal to 0 we saw will also need a minimum dance to keep sir let me know let us know that now we have minimal Nestle window the first layer will be initiative like integer max value and we also need a two variable which is minimal start next one and minimum and you would connect one because if they are still active one at the end we should find the empty string do not forget that okay now we need the two points and low equal to zero high equal to zero okay for high equal to zero hi less than s star let's type plus okay if let me first check if the char at high is larger than zero which means our culture should have last class because it occurs in the tea right and we do the same thing for every character char adhere to once - in one catch the way to other once - in one catch the way to other once - in one catch the way to other operations is if with a couch now equal to C down less which means you already have all the characters in this window but the law you know the law as the law captor may be our valid window or may not be our very window so we should move the law forward and they'll let it stay at the index theatre I belong chooser string G so but a well with every time we do the forcing we should make sure the index are variable so we should do law that's their high end map as the chart at law less than zero which means they are they have no use right we move we make the eschar yet no - - oh no make the eschar yet no - - oh no make the eschar yet no - - oh no is plus because we connect here and now use they're useless make a low class and then after this loop we make sure that law is now answer sir use a ball place usable and the high is also the usable place so let's compare hmm if minimum net is larger than high minus low has one which means this is much less there b---minus means this is much less there b---minus means this is much less there b---minus will be high minus low plus 1 and the minimum start will be low and the minimum end will be the high plus one why do I need 2 plus 1 because phangan want to use sub strings or sub string is exclusive the end index so I use minus 1 if you do not minus 1 you can add the 1 as the in the end ok and now already we already get a minimal are available of valid the window ended in the high so we should move the push your changes are charged at law plus in the move forward and the culture should - - forward and the culture should - - forward and the culture should - - because in this case we lose that valuable character we should find try to find it in the next steps okay now finally or should I check if the minimal start equal to negative 1 if yes we haven't found any variable so we just return empty three if not we will return as the substring minimum start as the minimum end okay I think it's right it's a cheese check and it should make sure when we compare all move law forward we should make sure the index a right so law less than highest right and yeah a larger than is a max value yeah he's right now we change the couch yes it's called equal to 10 Mel's so I think it's right let's see yeah okay so thank you for watching
Minimum Window Substring
minimum-window-substring
Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`. The testcases will be generated such that the answer is **unique**. **Example 1:** **Input:** s = "ADOBECODEBANC ", t = "ABC " **Output:** "BANC " **Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t. **Example 2:** **Input:** s = "a ", t = "a " **Output:** "a " **Explanation:** The entire string s is the minimum window. **Example 3:** **Input:** s = "a ", t = "aa " **Output:** " " **Explanation:** Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string. **Constraints:** * `m == s.length` * `n == t.length` * `1 <= m, n <= 105` * `s` and `t` consist of uppercase and lowercase English letters. **Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
Hash Table,String,Sliding Window
Hard
30,209,239,567,632,727
1,221
okay let's go ahead and all right welcome friends to this video we are going to solve a leak code problem in python today's problem is called a split a string in balance strings all right let's take a look and read through the problem and then go through some examples make sense out of what they're asking and then we can code the solution all right so it says bound strings are those that have an equal quantity of l and r characters given a balanced string s split the maximum amount of balanced strings return the maximum amount split bounce strings so let's take a look at this string here for example so we have r l all right and what we have is an output of four so s can be split into four balance strings so the first one is rl and then we have rrl is one and then we have rl again and we have rl again so essentially what they're asking is how many times does the r occur and how many times does l occur on that can equal each side of the string so hopefully this makes sense let's try another one here we have r l r so we have three in this case so we first have r l and then we have llr is an example and then we have lr so that balances three times let's look at the next one this one is once so yeah we can look at this pattern we have four l's and we have four r's that was uh yeah one there one uh yeah one pattern of l is one pattern r's equal one match all right let's take a look at the next one this one can be split into two so we have rl rnl that's a match and then we have rr no we don't have a match there we have oh yeah we have three r's and then we have um yeah this would work so we have these three r's we have two l's here's a fourth r and then so essentially what they're saying is these two r's these three r's plus this r is a fourth r these two l's and these two l's will make our balance string so this string here is balanced because you have equal r's as you do l's so that one would give us 2. all right so how do we code this all right so let's uh let's say we're going to take a couple we're going to create a couple variables first we're going to create match or counters first one is a match how many times does it match and then we're going to create a character counter so basically character is going to count the number r's and it's going to count the number of l's and then whenever we have a balance we're going to have a match counter all right so first let's loop inside of our string so 4 we'll call it a letter in s or s is the string that they gave us and then we're going to do some ifs we're going to check to see first we're going to look for ours then we look for l's and count those so we'll say if letter is equal to r then we'll do character plus equal to one and then we can say if letter is equal to uh l then we'll subtract it so we know that we're balanced here so character minus equal to one and then if it ends those two match and we say that character is now zero then match will add ones and then i'll go through this real quick and then out of the for loop will return match all right so let's take a look at this so essentially we're looping through our string for each letter and we if we find an r we'll add it to the character count then if we find an l we'll subtract is the character count and then at the end after we've done both of those if it as zero we'll go ahead and say that is a match and then after we've done through every letter through our loop we'll return how many times it matches all right let's go ahead and run that see how we've done and we've run we're successful for all our test cases all right hopefully that helps and thanks for watching this video and i hope to see you in the next elite code challenge solo
Split a String in Balanced Strings
element-appearing-more-than-25-in-sorted-array
**Balanced** strings are those that have an equal quantity of `'L'` and `'R'` characters. Given a **balanced** string `s`, split it into some number of substrings such that: * Each substring is balanced. Return _the **maximum** number of balanced strings you can obtain._ **Example 1:** **Input:** s = "RLRRLLRLRL " **Output:** 4 **Explanation:** s can be split into "RL ", "RRLL ", "RL ", "RL ", each substring contains same number of 'L' and 'R'. **Example 2:** **Input:** s = "RLRRRLLRLL " **Output:** 2 **Explanation:** s can be split into "RL ", "RRRLLRLL ", each substring contains same number of 'L' and 'R'. Note that s cannot be split into "RL ", "RR ", "RL ", "LR ", "LL ", because the 2nd and 5th substrings are not balanced. **Example 3:** **Input:** s = "LLLLRRRR " **Output:** 1 **Explanation:** s can be split into "LLLLRRRR ". **Constraints:** * `2 <= s.length <= 1000` * `s[i]` is either `'L'` or `'R'`. * `s` is a **balanced** string.
Divide the array in four parts [1 - 25%] [25 - 50 %] [50 - 75 %] [75% - 100%] The answer should be in one of the ends of the intervals. In order to check which is element is the answer we can count the frequency with binarySearch.
Array
Easy
null
1,022
uh hi everyone uh recently i come across this problem 1022 sum of root to leaf binary numbers so uh actually in this problem they have given us a binary tree that contains one and zeros only and we have to actually find the sum of all the paths in this binary tree so for example uh i'll just you know show you the paths here first uh so if you take from a root to leave one path like this is one of the path so one zero is one path so that's what they have mentioned here the other path is a one zero one this is another part 1 0 1 is another path then one more path is this 1 0 and the last one is one and one so if you uh like we have to first find out all these individual paths and then we have to sum them up and we have to return the sum that it's coming actually so if you look at this like one zero for example uh it will uh when you calculate the decimal value for that binary number it is four because you know like uh 1 into 2 raised to 2 so it is like a 4 and if you look at this 1 0 1 then the value is 5 and 1 0 the value decimal value is 6 and for 1 the decimal value is a 1 so we have to actually find all these paths and we have to calculate the decimal value for all the paths and then sum them up and return the actual decimal total value so that's what the problem is so um i actually solved it like uh using recursion and you know what i'm doing is like as you can see here so um i have implemented a traverse method and i am just passing a root of the tree and then i'm passing a empty error list here and one of the like a list i created to hold all the individual parts from root to the leaf so for example in this case this list actually will contain like four parts uh that one zero and one so um uh so actually in the traverse method i am just you know like starting from a root and um i am just you know first adding the root like the root value like one into the list and then i am going down on the left side and i will add zero into the list and then again zero into the list and once it reaches like here one once it reaches a leaf node then it will capture all the uh all this list that will contain like one zero um and then it will add into our this output uh list of strings which will capture all the individual paths from root to the leaf node so uh for example then uh first for first this for first leaf node 0 it will capture like 1 0 for the second leaf node it will capture one zero one for the uh like a third one like one zero and like one so this output list it will uh once we find a leaf node it will capture the current list and then you know we are using a new error list because we don't want to like overwrite the list that is coming because of the heap thing and then once we are done like once we add into output we have to like remove the last element from the list so you know like it can backtrack basically so uh this one this line actually is kind of for backtracking so for example one zero then it will remove the zero and it will go back to this zero and then it will again try to find another path like one and like one which is one zero one so um so that's pretty much it actually this solution works i'll post the code of the solution on github i'll just show you so we passed the test cases thanks for watching
Sum of Root To Leaf Binary Numbers
unique-paths-iii
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit. * For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_. The test cases are generated so that the answer fits in a **32-bits** integer. **Example 1:** **Input:** root = \[1,0,1,0,1,0,1\] **Output:** 22 **Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 **Example 2:** **Input:** root = \[0\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `Node.val` is `0` or `1`.
null
Array,Backtracking,Bit Manipulation,Matrix
Hard
37,63,212
77
So hello gas today is fast August and today we are going to solve lead which is number 77 question is combination so if you understand this question then it is said here that we have one two wait one N is one K and we have to return. If the possible combination of care number will work then it is from one to four so it means if you have to do from one to N then you have to enter from one then from there you have to do from 1 to four 1234 right so here the value of N is given as four. You have given the value of the cake, you are right, so we have to take it, you are the combination, we have to divide in the combination, then this is the answer, if it is 1213142324341, then we have to take only one and there is only one number, then it must have worked out that the meaning of this question is this. The question is what will happen to everyone, what is the approach to solve this question, so here if we say that we take mother from bacteria, we decide that if forest is given, you and brother-in-law = 2. And if you have given the value of k, then if you have given the value of four, then what is the range, one, three, four, then the best among all, you can solve, what to do, if n one n can solve, what to do, if n one is like in null, let's take it, yes first. One option will be that yes, we are taking one, yes, after that we just have to know, what will happen in the last, but what is there, why is it not divided further from here, because if we see it, then we will return from there that yes, this. We will include in the answer, we will include in one, we cannot add more because the value of cake is tu or tu, so we cannot make more than two combinations, so here the size becomes 12, so we return it. By the way, how will two come here, what will happen here, if we do it, then MP will be taken out easily, that is not an issue, but yes, what is the matter here, if we look here, then here we include 1, yes, the complete answer is one. Removed the complete combination One Two One Three One Four Like above we see what is here 1 2 1 3 1 4 Right done, here also we are going to do the same thing what are we going to do here that you include or do not include So this is simple, this project is going to be equal to if no means there is no size of the answer in which what we are going to do and we will take one answer and included it inside, after that we will do the function tomorrow and from I plus one. If we do it tomorrow and till tomorrow then we don't know after that no, do n't go after one yes because like here we have input one and if you include one from three four then only 2 3 4 is passing in 2 3 4. Later 1 input is done but you are passing three four, 2 3 4, we are seeing after that whether you are including it or not, that thing is A, so you have input one and after inputting, you have done the function. Yes, look ahead till I plus one, do I have to include or not, I and the other two numbers, we have to include two numbers in the combination. If I confuse one, then I will include one and one else. You are not going to include two, I have included two, I have to include two, I have included one first, I have included it, so how much was the child, improve the Assam tax people, you are two, I had to include one, so I have included only one. Can I include I plus one till the end? Answer: I Answer: I Answer: I can include I and K mines. Okay, how did this one happen, which one, how did this left one happen, if I don't include I and K. So what will I do? I have popped the eye in a second, so that second should include that and we will return in the last. To Menon sir, I am hoping that you all would have understood his approach, try it. So what will be the price, do you try to write the code once yourself to solve it, if not then someone will listen tomorrow, watch the video further, I am going to write the code there and also explain it. So I am hoping that you have tried it yourself once, if the code is not working, then someone listen, we will explain it here along with the court, we can do the difference, no, but yes, if we want to bat, then we will approach in the battery. Here it is going to be solved in the same way as we solved it. Generally, first we have the same as in the question, here the function is given, vector and vector 2d factor is given, here the parameters will be like this, meaning the parameter is the same, wait for us. Return connect tu d factor is to return the function name is combine and m given is given so let us create a function in which we will return this one once what do we do let's create a factor in which we will say sorry so this will go first So where do I want to take one more time, so I do one, I can do all this that if we do not return the message, we can just stop, okay, then we will do the same thing that yes, if the size of these answers and we will return here. That we have to send I Plus One, Hey, here the internet is back, we will pop it with the mine's answer of the person who is included. Does the answer name pop back? I released and sorry I released that no. Why don't you send K-1, you have to send only K, no. Why don't you send K-1, you have to send only K, no. Why don't you send K-1, you have to send only K, because we are checking the answer at the end, not whether the size of the answer is equal to you or not, if we send K minus one, then the size of the answer is also changing. If it is because of that, sorry but yes, if it is accepted here, then we submit and the answer is also accepted Here, in one of the answers today [Praise] In this in which the answer was made first from there to the beginning from the beginning to you It will be right, you will start doing it tomorrow, so if we include 2 here, the answer will be there again, life will come and here 3, when it is going to happen tomorrow, it will not come So hopefully I feel that here After explaining this much you must have understood that if you have any doubt then you can comment and for now this is all for today, till then see you in the next period.
Combinations
combinations
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`. You may return the answer in **any order**. **Example 1:** **Input:** n = 4, k = 2 **Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\] **Explanation:** There are 4 choose 2 = 6 total combinations. Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination. **Example 2:** **Input:** n = 1, k = 1 **Output:** \[\[1\]\] **Explanation:** There is 1 choose 1 = 1 total combination. **Constraints:** * `1 <= n <= 20` * `1 <= k <= n`
null
Backtracking
Medium
39,46
848
all right guys welcome to our channel food with sunny and in this video i will be talking about the medium type problem called shifting letters its index is 848 of the lead code okay so this problem is really very simple one and it involves simple operations on array or you can say the suffix sum or you can say the operations on the strings okay so without wasting our time let's discuss this problem we have been given a string s of lowercase english letters and an integer array shifts having the same length as of the given string and let's call the shift operation of a letter is exactly equal to the next letter in the alphabet wrapping around so that the z becomes a you can easily understand that if we are going to shift a particular character let's call it as a by an x amount we are going to shift it to the clockwise direction that is from a to b c and it goes up to z and if the value let's say x is going to be greater than the difference from a to z or the current character to the last one then it will cyclically shift to the next character that is then it comes again back to the a if you're not going to understand this let's look over this one suppose the character is a and we want to shift this character by two amount then it becomes uh b and then it again becomes c okay and what about when we have a particular character a and we want to shift it back to 26 like we are going to shift it by amount equal to 26 so it will change this to like 20 again it will change back to the a because after the 25th operation you can see a changes back to the z and in the next operation it changes back to the a so overall if you want to shift a character let's say ch to a new character by an x amount let's see then what we are going to do is first find out the ascii value of this character so ascii value of this character would be like okay it would be like the if you take on a single quoted comma it should be like this one and let's find out the let's say this ch character is c and for this c you are going to find out the what is the difference of this character c with respect to the base character is a okay and let's say you are going to find out the difference in ascii values like c minus a and it should come out to be i think two yes okay so it means that with respect to the base character this character c is two amounts ahead of it and if you want c to shift by x amount then what you are going to do you are going to write down two plus x and after shifting it by next amount you need to take by modulus 26 because there are 26 letters and it will come back to the again to the same position where it should be okay and let's say x is like let's call it as again 1 then you can see i need to shift c by amount equal to one so it should become two plus one mod 26 where it should become as three so it means that the new character will be three ahead of the current character base character which is a so it should be like a to b it should be c and it should be d so it means that d is our answer okay we need to take modulus 26 because x may be large okay so okay now shift of i like there is a shift adding and we need to do some operations on certain character like if we have been given shift of i exactly equal to x we want to shift the first i plus my letters of x exactly x times okay and we have to return the final string after all such shift to s are applied okay so let's try to understand this problem with the help of examples then we'll together build up the best solution for this problem so let's move further okay so let's take a simple example let's call the uh string as abc and shift l is given as a0 a1 and a2 are the values that is being given to us okay according to the problem statement what it says that if we have been given the a 0 it means that a i in general we are going to write it as a i if for a given value of a and this is the shift array actually a ai we are going to increment or you are going to shift all the characters all the first i plus 1 characters note that i is 0 over here so i plus 1 is 1 so we are going to shift first i plus 1 characters by an amount exactly equal to a0 now you can see that i is 0 over here so it means the first 1 characters that is only a okay so i'm going to write down some stops like this one let's make a three sized array and this is for the first character and this is going to be shifted by a0 amount right now okay now let's talk about the another character a1 sorry another value a1 so in general if a is given to us we are going to shift all the first i plus 1 characters by an amount exactly equal to a1 okay now you can see i is one over here so first i plus one characters it means first two characters i need these two characters okay and that is a and b so it means that this like the first one is already shifted by a zero now it is going to be again shifted by a1 and this is now going to be shifted by only a1 okay now let's talk about the another last value that is a2 now if ai is given to us first i plus 1 characters is going to be shifted and you can see that i is 2 over here so i plus 1 is 3 so it means the first 3 characters is going to be shifted by an amount exactly equal to the e2 you can see that these are already shifted by a 0 plus a1 now another value is going to be added which is a2 and here also it will be added as a2 and the final one it should be added as a2 finally now there is a pattern that you can see over here and you can see the very first position i have the value of the shifting as a0 plus a1 plus a2 and the second position has the value as a1 plus a2 and the final position has the value as a2 you can notice that it is actually the suffix sum of this shift array if you find out the suffix sum of the shift array you are going to get this value at every position so it means that if you have been given some like you are already finding it out the shifts of pick sum of the shift adding then you can easily perform the shift operation for every character and find out the answer at every position of this final answer string that is the last string is going to be shifted by a2 and the second last will be shifted up by this a1 plus a2 and so on you can do that note that we are going to do from the back side of this array so let's try to analyze the code now i've already submitted the code let's look over that you can see that there is a like one two like around ten or 9 lines of the code you can see i've taken now a 0 which will hold the suffix sum i will start it from the back side of this array and first i will find out the current suffix sum of this ith position which is now plus shift of i mod 26 i need to take modulus with 26 because i need to deal with the only the first 26 character that is small a to small z there is no need to store the characters for the larger ones that's why i have taken with modular 26 now i need to find out the new answer at this current position which should be find out the shift operation total shift operation will be like s of i minus e will be the current position of the current character with respect to the base character which is a plus the shift operation note that now will be holding the total number of shifts that will be happening to the current character and if we are done with that take modulus with 26 because so there is a cyclic rotation okay and if you do like if you do perform the cyclic operation 26 times uh forward then you are going to get the same character that's why we are taking the modulus over here and if you are if you have one if you have been finding out this value then we are going to increment or you are going to find out the actual value which will be stored in our answer it should be like a position of a plus this value it will redirect you to the same answers that we want for the current position and finally return the s which should be our answer so if you have any doubts do let me know in the comment section of the video and i will ask the viewers to like this video share this video and do subscribe to youtube channel for latest updates thank you for watching this video
Shifting Letters
shifting-letters
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length. Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`). * For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`. Now for each `shifts[i] = x`, we want to shift the first `i + 1` letters of `s`, `x` times. Return _the final string after all such shifts to s are applied_. **Example 1:** **Input:** s = "abc ", shifts = \[3,5,9\] **Output:** "rpl " **Explanation:** We start with "abc ". After shifting the first 1 letters of s by 3, we have "dbc ". After shifting the first 2 letters of s by 5, we have "igc ". After shifting the first 3 letters of s by 9, we have "rpl ", the answer. **Example 2:** **Input:** s = "aaa ", shifts = \[1,2,3\] **Output:** "gfd " **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters. * `shifts.length == s.length` * `0 <= shifts[i] <= 109`
null
null
Medium
null
1,456
Hello everyone welcome to my channel is quite a classic problem printed note medium at which it is cute easy if you understand it then ok before that let me tell you the date of done on Instagram also this is my handle you can follow me also ok so question ka The name is Maximum Number of Vowels in a Substring of Length OK, this is Microsoft Question, it is quite easy to understand, look at this, you must have given a string, okay, here you have given a string and it has given you the length, that is, the substring of this length. So I have to find, OK, there should be a substring of this length, so two is saying that the substring of two lengths, there will be many substrings of two lengths, one will be this, then this will be. Secondly, I am still getting only two, so let's see how many maximum values ​​I got, I still got only two, so how many maximum values ​​I got, I still got only two, so how many maximum values ​​I got, I still got only two, so my maximum is only two out of two, okay, here also I will get only two, here also only two. If we get then we have to return only the maximum number of vowels. If you saw that the substring of length is clear till now, then the question is quite easy to understand, so I will understand by taking a big butter example like mother takes, this is our example, this time the window size is three. It is okay, so let's see what will be the answer, how much wavel is zero, there is one wavel in the window and my maxi is also the same, so I will not update, okay then I came here, if there are two on this, it is max only. My date will be two now look here when I come here if I got three then max will also be updated then I am getting good answer I got two here but will not update here also I got two ovary but my max is also three so update We will not do 3 here also, if we find one, we will not update. After this, if we are not able to find a window of size three, then we will leave it. Okay, so what will be the answer, it will be three, okay, so how will we solve this? One, it is a very strong force. The method that you must have seen now is that I will first extract each substring which is of three sizes and then count how many vowels are there, okay but that is not an efficient solution, so this makes the playlist a sliding window and this sliding is a very classical problem. This is the most basic problem of sliding window. Okay, so the solution of sliding window is the same as always, that we take two painters, which starts from zero in the beginning, okay and will keep increasing gradually as we move forward. As soon as we get a window, what will be its length between I and J, similarly we will keep updating our maximum accounts, let's see what I am saying, you will understand from dry re, okay so look here now. Right? If it is at zero, then first let's check whether the character on the Jeet index is a vowel. So, I am keeping a variable named account, which I am repeating again in the current window. What will the account variable do? How many vowels are there in the current window? If you told me that it says in the current window, then I have banded it. Okay, so before moving ahead, check what K and I are. The length of the window that you are making is three. If not, then you will have to move ahead. We still haven't got the three size window. What does it mean that there is no win character? Have we not yet got the window of three sizes? So we will have to move ahead now. Okay, so again there is a flood here. Okay, so what did we check earlier that win? Is the character a vowel or not? If it is not a vowel then the count is still not one. Okay, so now notice that we have got a window whose size is three and in the question it is also said that what you have to do is that all the substances of three sizes have vowels in them. If we have to calculate the maximum number of accounts, then let us see that three sizes have been found, what is the value of the count. If there is one, then the max was also zero. In the beginning, how many vowels were found in this window, then it was banded with cat because one is more than zero. Okay, so now it is obvious that if you move J here, the size of the window will become bigger, it will become K, so I don't want the date, I want it to be of three sizes, so what should I do before moving K. I will enlarge the eye further. Okay, if it will move forward, then a window of three sizes will go to the right. So, when I will enlarge the eye further, then one thing will have to be seen before that. If you have enlarged the eye further, then who is going to go through the window? Earlier the window was this, now if you change the window to this, then this banda is gone from the window, if it was a vowel, then we will have to reduce the count of vowels, it means we will have to check again which character we removed, was it a vowel, yes it was a vowel, then the counter. There will be no impact, I have reduced the account back to zero, so now my IA has gone. Look in the answer, my balance in the account is also zero, that means we are going correct. What did we do after this, let's move ahead, okay. So, if we move forward like this, then first of all we will check whether the Jeet character is a vowel or yes, so what did I do, I increased the account, the count went back to one, okay, after that, what did we check that I and K are found? What is the size of the window? Three is right and we wanted only three sizes, so let's check how much V is currently. How much is Vivel in my window and Maxwell is also Vani, so let it be, we will not update. Okay, now let's move ahead, obviously what is the window size? So let's increase the i. First, let's see if this banda was not a wavel, then there will be no impact on the account. If I made the account bigger, then the count is gone. Look, the value of my account is also two. Okay and after that let's see what is the size of the window that I and G are creating is equal to three okay so we will update so see max is also one and the value of account is tu so now by the way we have one more okay I Have you got the value? Have you got it? We have also updated the max. Okay, then our sense is minus i plus one, the size of the window is three, so we will move i. Okay, before moving i, we will check the rectangle. The character is a vowel or not, then there will be no impact on the count. Okay, so I came here with a and it mix sense. Also pay attention to the current window, there is a vowel and here our account is also two, which means they are going correct. Okay, after this I came. K will increase further, it is okay, what is the big stubbornness on the character, if it is a vowel, then who will have to create it? We have made the account plus and the sense is that the size of our window has become three, so what will we do again? We will update the value of the account to max way 2. So we got another big value, three right, so we updated it. Okay, so if we increase I, then from our window this is I. Because I has gone here, we will have to min it also. This is also our answer, isn't it? The window one was my best answer ok so if you see the story point is going to be very simple we need two variables to create the window ok what will we do cup counting vowel if dj meaning win character if vowel is then keep counting account increasing It will be known that I have i+1a window size is that I have i+1a window size is that I have i+1a window size is equal to k i.e. if this condition is equal to k i.e. if this condition is equal to k i.e. if this condition is true then what we have to do is notice that we have got a window size, let's do a very good update max also and We will have to shift, we will have to do i plus because if we have got the window size then we will shift it but one important thing that we have to pay attention to is whether the character was a vowel, if it was a vowel then the count will have to be reduced because that window. Must have been written, if seen, this question will be formed from these three story points, okay, we will write now and our question will be solved, so now let's solve it in liquid and these story points are exactly the length, we will take two variables as ours. Answer: Wavell will keep counting the count of one current window, ours. Answer: Wavell will keep counting the count of one current window, till then we have to increase it. We have to write IF which is our current character, so we were counting plus, right, we were counting win characters. After that, what did we see? If k minus i plus one if k is becoming equal to k then okay then what we do is update it but before that we will check, after that we will increase i plus then what will happen is my window will shift to the right side and yes. So every time it has been big ok last time what will we do simple which is the value of max way it will return which 3 sorry quotes this vowel care and if k is a vowel i.e. then k = whatever parameter I am taking here. All brothers will pass the reference, it is okay to return, so let's remove it, are you passing or not? Next video thank you.
Maximum Number of Vowels in a Substring of Given Length
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
Given a string `s` and an integer `k`, return _the maximum number of vowel letters in any substring of_ `s` _with length_ `k`. **Vowel letters** in English are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. **Example 1:** **Input:** s = "abciiidef ", k = 3 **Output:** 3 **Explanation:** The substring "iii " contains 3 vowel letters. **Example 2:** **Input:** s = "aeiou ", k = 2 **Output:** 2 **Explanation:** Any substring of length 2 contains 2 vowels. **Example 3:** **Input:** s = "leetcode ", k = 3 **Output:** 2 **Explanation:** "lee ", "eet " and "ode " contain 2 vowels. **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters. * `1 <= k <= s.length`
Use Floyd-Warshall's algorithm to compute any-point to any-point distances. (Or can also do Dijkstra from every node due to the weights are non-negative). For each city calculate the number of reachable cities within the threshold, then search for the optimal city.
Dynamic Programming,Graph,Shortest Path
Medium
2171
368
Welcome back to our new video and today we are going to see the largest divisible subset, this is the problem of the lead code, today is the date, what is the date, this is not the question, first we will see our test case. There is one two three array and the answer is also in some array type like there is one two ch aa one two ch so my idea of ​​first seeing the test case was one two ch so my idea of ​​first seeing the test case was one two ch so my idea of ​​first seeing the test case was that one can find out what is one's input and what is the output. So, we will focus on whatever is important in the question. Okay, so now in this, read the problem first or read the test case first. I think, according to me, this is my opinion. I am telling you some general new idea that first is the test case. I think you should read this because in some competition exams, the questions are so long that you can't even guess which one is input and output, so you will read the problem first. Okay, you have seen the test case, so you. Have been given a set of distinct positive integers so all integers are distinct written the largest subset answer true that every pair answer i and j of element in this subset satisfy this condition ok answer module zero means it is divisible it is also divisible and Okay, so basically you have been given an array like this, so you have to divide it into groups in a way, and all the elements in a group should be divisible among themselves, okay, so this is your answer. Apna constraint is this, numbers length is up to Haz, so Apna order of a square approach will also work here and I think I am not shar n cube will work but yes n screw will work here number is 10 raise na till ok so numbers You will not be able to perform anything, all the pain is in it. Okay, so now let's look at it, what do you want to say here, it will be fun, won't it? Let's take one input from here. Let's pick up 48. Let's pick something different. 8 12 Okay, I picked this up. Now let's first see how it will behave on the smaller test cases. Okay, Let's pick up. This is only one, okay, this is my input, so what will be my answer in this case, tell me, the length can be zero or not, okay, so this is the smallest, so in this case, this one will automatically become this self. In that case, if it is divisible by both, then your answer is ntu. If it is not divisible, then your answer is one or two. If it is divisible by two, then in that case either The answer is two or th is not th because u and th are not divisible, so let's see for ourselves how this will work on the smaller test case. If you don't have any more idea than this, okay then like you one by one. Adding let's say I have a group Let's say I have a group from th and 6 are all divisible from th to th and six Is divisible yes so all these are divisible and this can be a group Okay now Can I add to this group ? Can I not? That will ? Can I not? That will ? Can I not? That will not be divisible by th. Na th is so is six is ​​also not be divisible by th. Na th is so is six is ​​also not be divisible by th. Na th is so is six is ​​also 8 can I can a also can't 12 can yes 12 can why one Will divide th will also divide 6 will also divide 12 so I can add 12 to this so I can add 12 newly to this okay so now tell me one thing like this is my group okay if there is someone in this The new element is the new element from the lettuce. It is divisible by its maximum. Here the maximum is six. If it is divisible by the maximum then will it be divisible by the entire group or not? Tell me after thinking about it. Obviously yes, why because? If these things are divided by six, then if I write six in letters like this, then I will write only 3 * 2 because it is divisible. will write only 3 * 2 because it is divisible. will write only 3 * 2 because it is divisible. Now if the new element is divisible by six, then it will be divisible by three. If the multiple is six then whatever will be my maximum, from here I have an observation from here and what is the maximum element of the group's maximum element should divide the element. Okay, if we divide that then I will say that This is also a part of our group, now there is a twist here, what is the twist, I am doing it to the maximum, neither here late, this time it is mine, I have made a group of 8 and 12 now. Now tell me whether I can add the number to 2 or not. Now from here you said that the maximum is 12, what does it divide 12 and not because it is less than 12 but this If it is possible to add to this group, then you cannot tell by just looking at the maximum, and you cannot tell why. Let's take another example, no, and 18. Okay, now here you have to add my co to late, so here if I ca n't do this by just looking at 18 because it will be divided by zero, so if it is less than the new element, it is less than that, then I will have to see in the whole group whether it divides or not and if it is greater then You have seen that the maximum is divided and we will see, now what is the issue here that two cases have been created, one is that brother is more or is equal to two and the other is less than it is fine but in this case I will have to see the whole group. Group Need to Know I should know the entire group and in this I only need to know the maximum because from that I will find out whether this person can be added to the group or not. Now what do I have to do, I want this to be obviously efficient, ok. Yes, it is efficient, it will take time for me to traverse the group, it is possible that I can convert it into this can also be yes, how is it possible that the elements in the group are always small which If the new element is separated from the new element, then it is possible and how is this possible? It is possible that if I shorten it to 4, 8, 12 and 18, then assume that this group will be formed first. So now whoever new will come will always be bigger than this, so now I don't care about it, now I will focus only on this, whatever my maximum will be, from that I will find out whether it will be added or not, so now I will focus on it. Let's see, let me erase it a little, okay, now let's start from one, so one itself is one. Apna, perhaps you haven't seen it. Okay, if you have seen that if the element is one, then Apna group size will be the same. Now. But coming to this group of one, can it come in the group or not? Tell me, obviously it can come, no friend, the maximum one which is there can be added, right, so here it becomes two and the three can come in two, can it be two? One cannot come into the group, one can come into the one and three can come into one's own group, so here it becomes two, that means this is one and the right, now the four can come into three, isn't it two? Yes in one person, now he can come in two person, then I know that the two person himself is sitting in the group of one person, now he is saying that he has seen that if the maximum that he gives to himself is the same. But if we have to do an operation then two and four can be added, so what will happen here, still it will be a part of this group, then what is its length, three has become ours till now coming to eight, 8 should be a part of 4. What can happen is that T can be its part. If four divides 48 then it will do 100% divides 48 then it will do 100% divides 48 then it will do 100% why this if you multiply it by two 2 * 2 is equal to two then it is 4 now 8 2 * 2 is equal to two then it is 4 now 8 2 * 2 is equal to two then it is 4 now 8 divide 4 or 8 2 * Divide 2, it will divide 4 or 8 2 * Divide 2, it will divide 4 or 8 2 * Divide 2, it will divide t, it is simple mathematics, so here I have divided it into four, now we get 12, can 12 go from A to A group? Obviously, it cannot go to four, yes and four is this. The part of the group is two and four, so here a group of 12 will also be formed, whose length will be four. Now these groups are being formed, it does not mean that they are being formed in such a count only, do not start visualizing it like this. Now things are fine, now the 18 one will not go in the 12 one, it will not go in the A, it will not even go in the four, three, yes, if it will go in the three, then this th and 18, this will make 1, this will make 18, so this is how much of it is If it becomes three then this is ours, till now this is the last one, as if we will pick our maximum, out of these only the maximum is what we want, what is the maximum group size that we want, so either I pick this one or this one, then it is mine. The answer can be either t 4 8 or this or two further and 12 but now I just know what the size of the group is now I don't know what are the elements in the group Okay, now it is important to know the elements, otherwise what is the point of not knowing the elements? What is the use of taking out two group sages? You need the ingredients which are in the answer, so what will you do for that, I will tell you my tips for that. We will take an array which we will name, I will name it right here itself, what has happened to it is ok, I have given it a name, I am the previous element, ok, so in this I will store the element of which part it is, like it was of the fourth one, right? Here I will say that this is the one in front of four, it is like this, one is in front of whom, one is not in front of anyone, two is the one in front of one, and three is its three, so here also one aa And this one was from two, so here two came and this one was from here, so it will come here one second, I have to store the index here, I have to do something, don't make a mistake, okay, mistake here. I am talking about the index here, I will store the index here, this is this. This one is on this index page, not on this one, this is also on this page, this one is on this page, so this one is also ours, and this one, is ours, the next one from here, 01 2, so this is this one is mine, this is the previous one. Index of element. Now let's see how I extract the information from here. Now I know whether the maximum is this or this. Now you can return anything in the answer. If two beans are of the same length, then it is okay. The maximum size of both is four. Four, return any one, I will pick it late, 12, so I picked 12, he later said, brother, go to the index of three, you will get the next one here, what is the index of three, now it is four, now the one of four. He said, go to one index, what is your two? The one with two will say, brother, go to zero index, what is that one? Now this minus one will say, brother, stop, that's it, I am the first person, so this is my answer. Done and guys, this is the problem I have described, it's kind of longest increasing sequence, so I thought I should have informed first that those who know this, they did not even need to watch this video, it was direct. Solve it with Longest Increasing Subsequence and if you do n't know then it is ok to solve this problem after this question. You must solve it in the lead code. So let's see. Now let's move on to our code. Is there anything left, is it our logic? It is complete, now I will look at the code and tell you my time and space complex. Okay, let's look at the code. Now let's get into the code. First of all, I have shortened the saw by one second. Why did I do that? I told that in the group, I always use the maximum. I am going to add the element itself, okay, after that I have an array, group size, here I told you, this is the group size, this is the name, it is very important, it means do not keep such names. Give that er adb rr is the name, it should be something significant so that the user can know what he is doing, here I am storing the group size, this is storing the previous element, this is my maximum index means this. Which is the maximum index, this one here can be either this one or this one will be the only one, so now let's start with group C. First of all, there is no group, there will be only one element, so we will start with group size one. This is what it is and we will start from one, after that the previous element minus and this also, we have seen that this is the starting point, this is its minus and, it is okay and this is minus and this is not the only thing, remember, I have one more example. Let me take it and tell you, otherwise you will get confused like it is not Jari, it is to and thi, it is and th, then this will also be minus w because it also has no origin, this is also the first. If yes, then both of them will be minus and, right? Now let us come to traverse, we will traverse the elements which are behind, we will see whether we can add it or not, then our condition is that if it is divisible by names, I is divisible by. Nams j Nam j will always be small Nam size which is newly added which is going to be added that one and if group size i which is current group size that na plus group size plus j if this is the group that will be added then if group size increases. Only then will I assign a new group to that group, otherwise I will not assign a group, okay, I have assigned this, plus and along with it, I have also stored my previous element that brother, yes, I have created a group from here. This will happen here, now as soon as the group size has increased, if the maximum index has increased, then I will also update the maximum index that my new group size has come, this index is fine, now let's go to our maximum index. I am backtracking, okay, I am backtracking, here I added and there on the previous element, I told you, I will backtrack you, from here, I will come to four, from three, then from three, I will look at this, then from one, like this. I will back track like this, okay, so I back tracked like this and then after that I will return the result, so this is my Java code, it is okay, I have also written the code in CPS, I have used Chat GPT because I don't think that I am an expert in C+Plus, still I am an expert in C+Plus, still I am an expert in C+Plus, still I tried to run it, this run was done successfully, so first I shortened it, after that I made a vector of my own, group size and previous element. I filled it with 'Mive' and filled the group size with 'one'. The filled it with 'Mive' and filled the group size with 'one'. The filled it with 'Mive' and filled the group size with 'one'. The maximum index is zero. This friend is more like it to me. It looks good. The GPT guy could have done it in Java also, ok but I think the logic is the same. Here also the logic is almost the same, there is nothing much different and let's see the short key in Python also, we have calculated the length of the group size in Python, we can do this by filling either 1 or n or one by one of n size. Will give previous element maximum index and then I in range a for j in range and after that okay so this is also almost similar so now we will discuss it time and space complex of n is obviously two arrays used here. I have also given my result and string but it is in the order of n. Okay, this is the order of n. I have complicated my space, so the order of n log n is the same. After that, I have traversed are. We have traversed the array twice which is order of a square, after that we can go till order or n so this is our time in complex video till then keep learning keep watching and keep solving questions thank you bye finish bye Tata gone good bye
Largest Divisible Subset
largest-divisible-subset
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies: * `answer[i] % answer[j] == 0`, or * `answer[j] % answer[i] == 0` If there are multiple solutions, return any of them. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[1,2\] **Explanation:** \[1,3\] is also accepted. **Example 2:** **Input:** nums = \[1,2,4,8\] **Output:** \[1,2,4,8\] **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 2 * 109` * All the integers in `nums` are **unique**.
null
Array,Math,Dynamic Programming,Sorting
Medium
null
632
hello friends so today in this video we will be going through another problem from lead code which is a hard problem the problem name is smallest range covering elements from k list so i'll go through the problem statement first and then we're going to discuss the approach and the good part the problem statement states that you have key list of sorted integers as you can see and in these are in non-decreasing order like these are in non-decreasing order like these are in non-decreasing order like they're sorted in like ascending order then find the smallest range that include at least one number from each of these k list which means that you have to find out the smallest range such that like any number from this range should exist in every nouns okay so what i mean by this is as you can see the range is 20 to 24 now 24 is in this range and it also lies in this list so 20 is in this range and it lies in this so android 22 is also in this range and it slides in this list so it's like finding out the smallest range such that every number in this range not every number but like every list has like should have one number which is in this range okay so you should find out the smallest range such that every list should at least have one number which should be in this range now how you can go about solving out this problem so it means that like you have to find out so what i first thought about this problem is like you have some sorted numbers there might be some overlapping some sort of like this these are the list and i have to find out some common smallest range which is in every number okay so it means that you have some sorted list which might be overlapping like this on a number line these are the sorted list and i have to find out the smallest range which is somewhat common in all the num like sorted list so if the list are like this and one is list is like this then i have to find that okay the list should consist of numbers of this range because then it consists of this numbers also this number also and some number of this list also so you have to somehow find out the intersection of all the list now finding out that section is a little bit different but not difficult but still but you have to find out somewhat intersection but what you can easily do in this problem is uh the one thing which come to my mind is let's assume that uh like these all the list if i somehow merge them into a single list like these lists are different okay these layers are different but i have to somehow find a common list now okay but if i somehow managed to bring out all these lists into one single list then it would be more beneficial for me but if i mix down to the single list then i will keep track of the like i will not keep track of what element is of which list so but i can attach every element with some id something id means that this is this of the first id like zeroth list this is the first list this is the second list so what you can do here is if i make a like if i make a single list of all of these elements okay so that they are sorted because the range which i have to found out it should be like an increasing order it should have sorted list okay assorted range so if i somehow make elements let's assume that one is of the second group okay two like there's a next number two which is of the first list there is uh like four which is of the first list there is a let's room six which is of the third list okay then there is one like sorry so one there is again six which is from the first list and so on okay which means that i have some sort of numbers which are sorted out and again i have some ids now it means that now my problem boils down to finding out us a subsection or like a substring or like section of this whole array such that every number which is the id should exist in it i hope you get the point which means that see i have to somehow make a range i can make out this range also now such that if this is a range i should ensure that in this range every element should like every id should be present at least once because every id is present at least one means that it means that in this range which i have taken every number from every list just present like at least one number from every list present because every list is depicted by one id and if i take out one like one section which means that okay taking out this section means that i have taken out elements from each id and that's the logic for this problem you just have to first make a single array marking out the num like the elements and the id sort it out after sorting it out you have to use a two pointer technique okay two one technique to find out the smallest list the smallest range list or like a subsection which consists of all the elements like all the ids element and that's the whole problem i'll take under the code part now to make it more clear you can pause the video at this point if you want to see the code and yeah so what i have done here is i have to first insert all the nums value with its id so this is the id okay so i'm iterating over every list and for every list i'm iterating by every number and i'm pushing out the number and the list id in this array then i'm sorting out the whole number such that every number is sorted out with the list ids but the sorting is done on the basis of the numbers itself then i have to find out the minimum length array or like a range so the minimum range i am defined by a very large number because i have to find out the minimum length okay then this is like a map which is which i've used in the problem i'll tell you how which i've used this is the total and this is jj and i is used for 2.8 is used for 2.8 is used for 2.8 so i have mem set this value so this is the map value which is the difference so i have name set it with zero now what i'm doing in this problem is like i have to store out what are the different like different ids in this problem i have to ensure that every id is present how many different ids are there the different id is the total number of lists which are there so total number of list which is the size of the nums and that much ids are there so i have to also make the ensure that i have to keep track of how many ids i've seen till now using this to two pointer so i have to make a map for storing on different ids and after first mem said to zero that no id is there then this is the two pointer start i from zero till end then whatever id i've seen till now id store on i dot second i will increment that id okay then what i'll do as you can see if the particular id is 1 after incrementing which means that i have seen this element for the first time if i have seen this particular element for the first time the total different ids i have seen will increase increment but increment by one which means that let's assume that there are different ids there is some two there is some one there is again one so if my eye is moving from left to right i have seen one time one and again see one time one these both of these ideas are same so i should not increment two type it means that both of these ideas are same so it boils down to a single like i should take if i'm taking both the elements it's also fine but i have to find the total number of different ids should be equal to total number of different ids in the total i like problem itself so i have to also increase the total means that i have seen a new id how can i understand that this is a new id i have to see that whatever id have added till now whether the count become one the count become once means that okay i have added this id for the first time which means that this is a new id so i will ignore total and whenever my total becomes equal to different total number of different ids are there if it becomes total number different which means that okay now i have all the ids in my list or the range i have so i have to minimize this range like so what i'll do what is the range value so as you can see the range value will be this so if i take out a range from first till six one till six i take out the range then as you can see if i take out one to six range means that every number in this range will be somewhere in every list so as you can see one will be in the first second list two will be in the first list four be in this in the first list six will be in the third list and so on so it means that if i take out a range from one till six every number like every list has some number which is in this list because i've taken this list out okay so that's what i've done so i have to minimize this range now so what is the length of this range i will see that the length of this range is this minus this plus one because six minus one plus one actually six the total length of this range is obviously six now so if this length is smaller than what i'll do i will update my minimum because this is the smallest range i've seen till now and i have to also store out this range somewhere so that's why i make a answer i think so yeah answer vector to throw out this range that i'm also sorting out this range now if i have covered all the total elements which are different now i have to also move my back pointer so i have to make a while loop and i will use this back pointer and i will keep on updating my back pointer will move so let's see my eye is at this point which means that i have seen all the elements till now like two three and one now is there some way that i can move my back pointer and also minimize the total the range value can i somehow uh like minimize the range one because assume that my first side is two the second i id is two third right is two four that is one and fifth idea is three now if i have only three id possible then obviously my range is this but i can also bring down my range to this also because this range also consists of all the elements from one two three but if this is also on top of all the elements from 1 2 3 but this is smaller so it's beneficial to bring down my left pointer which is j to this point when i have to bring this down i have to only bring this down when i have all the elements in my range so that's what i'm doing i'll do a while loop such that i'll do a value till my total elements total different elements is equal to total different element which are existing if they exist what i'll do i will check that whether the element i am on the jth element so if the jth element is the frequency of that element is greater than one which means that okay there are some more elements can i delete out this element and still my range has all the elements present yes so delete this out because i want to somehow delete some elements from the left part such that my total number of different elements should remain the same that's what i'm doing if they are same delete this element out and increment my j so now my j go to this point if my j is at this point can i delete down this element and still my range has all the different elements yes so delete out this element also now by g because i'm at this point cannot delete this element and still my range has all the different elements no because if i delete down this two my range will not have one two three this two is deleted so it's not possible now so you my j will come down to this point now so this is my final range which is the smallest range but still i can go further but this is the smallest range i can go so i will break out when i cannot go further and then this is this new range is like my js at this point in my is this point so i will now again check that whether this range has sinken down or not if this is this range is smaller than the minimum i have seen above if yes i will update again update my minimum value and in this process it's like just like a two pointer window approach to find out what is the smallest range the range length is not depicted by the length of the window remember that the range length is not depicted by the length of the window but it's depicted by the value of that elements at that window because we are finding out the range of those using those elements not the window length but still we are using two pointers to get the smallest range as possible and it's just like a window technique to find out the smallest range such that the length is smallest and it consists of all the different ids present and in the end i have this answer which is storing out the starting and the ending range values so you can see the code at this point okay if you still have any doubts you can mention a coin box as the next one until then keep coding and bye
Smallest Range Covering Elements from K Lists
smallest-range-covering-elements-from-k-lists
You have `k` lists of sorted integers in **non-decreasing order**. Find the **smallest** range that includes at least one number from each of the `k` lists. We define the range `[a, b]` is smaller than range `[c, d]` if `b - a < d - c` **or** `a < c` if `b - a == d - c`. **Example 1:** **Input:** nums = \[\[4,10,15,24,26\],\[0,9,12,20\],\[5,18,22,30\]\] **Output:** \[20,24\] **Explanation:** List 1: \[4, 10, 15, 24,26\], 24 is in range \[20,24\]. List 2: \[0, 9, 12, 20\], 20 is in range \[20,24\]. List 3: \[5, 18, 22, 30\], 22 is in range \[20,24\]. **Example 2:** **Input:** nums = \[\[1,2,3\],\[1,2,3\],\[1,2,3\]\] **Output:** \[1,1\] **Constraints:** * `nums.length == k` * `1 <= k <= 3500` * `1 <= nums[i].length <= 50` * `-105 <= nums[i][j] <= 105` * `nums[i]` is sorted in **non-decreasing** order.
null
Array,Hash Table,Greedy,Sliding Window,Sorting,Heap (Priority Queue)
Hard
76
662
hey everyone today we are going to service a little calculation maximum width of binary tree so you are given a root of binary tree return the maximum width of the given tree so the maximum width of 3 is a maximum width among all levels the width of one level is defined as the length between the end nodes of the leftmost and the rightmost non-neural nodes where the neural nodes non-neural nodes where the neural nodes non-neural nodes where the neural nodes between the end nodes that would be present in the complete binary tree extending down to the level are also counted into the ranks calculation it is guaranteed that the answer will be a range of 32 bit unsigned integer so let's see the example so you are given this binary 3 and the output is 4 because so this level is a maximum width of 93 and uh so as the description said we have to count some new node here yeah so that's why output is one two three four in this case before I start my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all the details of all questions in the video and you can get a call from GitHub for free so please subscribe my channel hit the like button or leave a comment thank you for your support okay so let me explain with this example two sort of discussion I want to Traverse the binary tree with a breast fast touch to get the maximum width of binary tree and but one important thing is that we have to calculate a Max width over each level so how can we calculate the width so to calculate the width every time I put the index number so loot node is zero and the left turn this one and the right third is two and three four and five so nude also counted and the six and then we calculate the lift right most index minus our leftmost index plus one so in this case six minus three plus one and four so one two three four so that's why we get the four as a Max weights of binary tree but how can we calculate the index number so next index number so it's simple so every time when we go down the next level so one parent node has two node at most so that's why uh two multiply current index Truss one or so this is a for our left child and for right side two multiply index number plus two so if we use this formula we can calculate the next index number so let's check so now we are root node so in the left step should be two multiply 0 plus 1 and 1. looks good and uh two so four right side two multiply 0 plus 2 and 2 right and so let's calculate from in the index one so for rest child two multiply one and get two plus one and the total C right and uh for right side two multiply one plus two and four right and then from index two to multiply two plus one and five right and uh for right side and two multiply two plus two and six yeah looks good so this formula looks works uh so yeah we use this formula um and I keep the answer every time yeah so that is a basic idea to solve this question so with that being said let's get into the code okay so let's write a call first of all if not root in the case just return zero and then after that first of all initialize Mark sweets with one and two so I use our DQ and a fast value should be like a root and index number should be zero and start grouping so start traversing so Y and Q and first of all um okay so get the rebel size equal length of Q and then after that pick the leftmost node in the rightmost node and so we have a two data so node and the index number and then here we don't use a node so that's why underscore in the left index will call Q and zero and this is our right index equal q and the last note so -1 equal q and the last note so -1 equal q and the last note so -1 and that calculates the current width equal right index minus left index plus one so that's because this is a index number so we need a plus one for to convert a real number and then calculate the max width and the marks and the max width passes current reads and then next try to append the child's children if we have so for underscore in lens and the level size and first of all pop the data index equal to pop left and if node.rect so if we have a ref child that node.rect so if we have a ref child that node.rect so if we have a ref child that does our band QQQ dot append and uh left node and the index number should be 2 multiply index plus one because this is RF node and then if node.write and then if node.write and then if node.write so append Q and this is a node.right and this is a node.right and this is a node.right and index number should be two multiply index Plus 2. yeah that's it and after that return the max reads yeah so let me submit it yeah looks good and the time complexity of this solution should be order of n so where N is a number of nodes in the tree so this is because we visit each node in the three exactly once during the rest first search traversal and the space complexity of this algorithm is order of w and where W is a maximum width of a binary tree so this is because the maximum number of nodes that can be stored in the queue at any given time is equal to a maximum width of the three so in the worst case the entire last level of the tree could be in the Q or at once so result in the space complexity of order of w yeah so that's all I have for you today if you write it please subscribe the channel hit the like button I will leave a comment I'll see you in the next question
Maximum Width of Binary Tree
maximum-width-of-binary-tree
Given the `root` of a binary tree, return _the **maximum width** of the given tree_. The **maximum width** of a tree is the maximum **width** among all levels. The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation. It is **guaranteed** that the answer will in the range of a **32-bit** signed integer. **Example 1:** **Input:** root = \[1,3,2,5,3,null,9\] **Output:** 4 **Explanation:** The maximum width exists in the third level with length 4 (5,3,null,9). **Example 2:** **Input:** root = \[1,3,2,5,null,null,9,6,null,7\] **Output:** 7 **Explanation:** The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7). **Example 3:** **Input:** root = \[1,3,2,5\] **Output:** 2 **Explanation:** The maximum width exists in the second level with length 2 (3,2). **Constraints:** * The number of nodes in the tree is in the range `[1, 3000]`. * `-100 <= Node.val <= 100`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
328
hi everybody welcome back to another algorithm problem hi uh future michael here so i'm currently editing this video and i realized that it's been about six months since i posted my last video and a lot has been going on in the last six months tldr moved across the country switched jobs and i haven't really had time to edit videos these days uh i have a bunch of videos that i filmed like four or five months ago even this video was filmed like four or five months ago and i haven't really had time to edit them anyway a bunch has been happening in the last six months i'm really sorry i haven't really got around to uh post videos but i will try to do that in the next couple of weeks also let me know if you want to see something like a live update video uh frankly i don't think you guys care but if you do let me know down below in the comments and back to the video today we're going to solve leak code 328 odd even linked list this question feels like an easy problem and frankly it could be an easy problem depending on the way you want to solve it also depending on the input and complexity constraints so the question says given the head of a singly linked list group all the notes with odd indices together followed by the notes with evidences and return the reordered list so the first node is considered odd the second node is even and so on so this question gives you linked lists with odd and even indices and you should group all the odd indices together and even indices together and connect the two groups so the odd indices come before the even indices well this problem is similar to one of the problems we have on this channel which is to partition the links list i'll put the link below in the description and on the screen if you want to check it out as well while that question wants you to partition a links list around a certain pivot value this question wants you to partition the links list between odd and even indices so we're going to cover two solutions the easy one and the harder one and i'll write the code for the hard one because the easy one is pretty trivial so let's get into it so here's an example of the links list that we have an input of one two three four five right here and then we have an output of one three five two four so the notes in red are odd notes in the root notes in green or even notes these are even and these are odd one three and five and then we should group all the odd notes together and as you can see in the output we just group them one three five and then we just group the even notes together two and four and we have to make sure that the order in which the notes appear like two comes before four so two should also come before four in the output and then also for the odd notes one comes before three comes before five and then the output one should come before three should come before five so that's pretty much what the question wants us to do group odd and even indices of a links list in the order in which they appear the first node is considered odd the second note is considered even and so on and what we want is to partition these notes so the odd notes are pointing to each other in the correct order in which they appear and the even notes are doing the same and join these two partitions together like so the first solution is the sub-optimal the first solution is the sub-optimal the first solution is the sub-optimal one and that is to iterate through the links list and add even indices to like separate arraylist and odd indices to separate arraylist and reconstruct those two links lists and join them together at the end uh we'll have a counter that tells us which node is even and which node is odd depending on the index and then we would just reconstruct the two links list cons consisting of odd nodes and even nodes and then join those at the end so let's see how that would work so we have our links list with values one two three four five and then for our first solution we're going to iterate through the list and then add the even nodes to like an array list in the odd nodes to an arraylist and we're going to have a counter variable that tells us which index we're currently iterating at if it's an even index or like an odd index and this is going to be like cookie cutter links list iteration with a while loop that says while head is not equal to null and then in the while loop we can say head is equal to head dot next and then we can also increment like a counter variable like counter is equal to counter plus one and for the first time that we're going into the loop we're going to initialize the counter to one so now our counter is one then we're iterating through this list first of all we're going to be at the first node which is one and then we check is one an even index or an odd index it turns out one is an odd index so we add one to like an odd array list or an array whichever one works for you as long as you're keeping track of them so i'm just going to say odd and then we add 1 to it that's the value at index 1 and not the actual one it just turns out that this corresponds exactly with the and this is like the value at each index corresponds exactly with the indexes value but that's not what's going to happen in every case so what we want to do is not add the index itself to the arraylist but add the value at the index the value is 1 that's what we're going to add so then we move on to the next iteration increment the counter so now our counter becomes two this is going to be really messy two and then we check is to an even index or an odd index turns out 2 is an even index so we add 2 to the even array list so that's 2. and then we move on to the next iteration increment the counter so now counter becomes three and then we check is three an even index or an odd index three is an odd index so we add the value at index three to the odd array list so three comes here and then we move on to the next iteration incrementing the counter as we go so counter now becomes four and then we check is for an even index or an odd index turns out four is an even index so we add the value at index four is four so we add four the even array list and then we move on to the next iteration incrementing the counter as we go the counter now becomes five and then we check is 5 and even index and odd index turns out 5 is an odd index so we add 5 to the odd array list so now what you're going to find out is we're not done yet we're also going to go to the next iteration because our iterative algorithm like a while loop doesn't know when to stop unless we come across like a null node and then we move into the next iteration incrementing the counter as we go so now counter becomes six so the very last node will be pointing to like a null node so five would be pointing to null and then we're going to go to the next iteration incrementing the counter as we go and then we come here and then we check are we at a null node is the pointer currently pointing to a null node which it is so if that's the case then we just break out of the loop so breaking out of the loop uh after we do that we're going to find out that we're going to have two lists one list consisting of odd values in the other list consisting of even values or rather values at odd indices and values at even indices so we're going to reconstruct two separate links list with these values and then join those links list together so the first one would be connecting one three and five and then we reconstruct another links list with the values at even indices so that would be two and four so one connects to three connects to five and then two connects to four so we're gonna have two lists two um links list now all we have to do is to connect the tail of the odd list to the head of the even list so at the end we're going to have the values 1 3 5 2 4 which is the final answer this is a valid solution but it's super expensive on space and the constraints say the links list could have up to 10 000 elements so we want to find some solution that doesn't consume extra memory and can be done in place and the next solution does just that the second solution is more optimal and doesn't use additional memory so how does it work we're going to iterate through two lists at a time and we're going to update the dot next pointers as we go so one list would contain values of even indices and the other list would contain values of odd indices the two main differences with the first solution are one that we're not going to keep track of a counter variable that tells us which index is even or odd because the decision about whether an index is even or odd is binary if it's not even it's got to be odd and nothing else and because we know that the first node is odd then the next node must be even and the next is odd and the next is even and so on so we don't really need to keep track of the counter variable the second difference is that we're not going to store the values of even and odd indices in an arraylist or some other data structure so let's go through an example to see how the solution works we're going to initialize two lists let's call them odd and even this is odd and this is even right off the bat we know that the first node is odd and the second node is even first node's odd second node is even so the head of the odd list would be the first node as you can see and the head of the even list would be the second node so even list starts with the first even index and the odd list starts with the first odd index and now we're going to iterate through these two lists odd list and even list and we're going to do four operations and the order in which we do those operations is really important first we're going to set odd next to be even next so i'm talking about while we're iterating through those two lists in a while loop in the while loop we're going to do four operations first operation we're going to set odd.next operation we're going to set odd.next operation we're going to set odd.next to be even next and next we're going to update odd to the new odd.next that we update odd to the new odd.next that we update odd to the new odd.next that we just updated in the previous step then we're going to set even.next to then we're going to set even.next to then we're going to set even.next to odd.next odd.next odd.next and finally we're going to update even to the new even next that we just updated in the previous step i know that sounds confusing but i promise you it's going to make sense in a second so let's dive into an actual example going step by step of how this process works so let's say we're iterating through these two lists iterating through the odd list and the even list and this is the head of the odd list this is the head of the even list first we're going to check if odd.next first we're going to check if odd.next first we're going to check if odd.next is not equal to null and even that next is not equal to null so let me do that this would be pointing to null and this would also be pointing to null at the end so audit next is not equal to null for now even.next is also not equal to null now even.next is also not equal to null now even.next is also not equal to null for now so we can continue doing the four operations that i just mentioned first one is we're going to set odd.next to even.next which means that odd.next to even.next which means that odd.next to even.next which means that we're going to move this pointer and point it here so audit next points to even dot next so when we do that we've essentially blocked the connection between one and two one now points to three so let's erase the connection between one and two now we have to update which odd value we're going to next logically the next odd value that we should go to is three so we're going to set odd to the new odd next that we just updated i think it's better if i just like put something on top of them so we could keep track of which one's odd and which one's even so i'm going to do o for odd and e for even so now the current odd pointer points to one current even pointer points to two we're going to move the current odd pointer to 0.23 now which is the new pointer to 0.23 now which is the new pointer to 0.23 now which is the new object next that we just set so let's do that odd now 0.23 odd now 0.23 odd now 0.23 and next we're going to set even next to be odd next so even.next to be odd next so even.next to be odd next so even.next which is this one right here we're going to move that pointer to be odd.next the to move that pointer to be odd.next the to move that pointer to be odd.next the new audit next that we just set so let's do that even.next points to so let's do that even.next points to so let's do that even.next points to odd.next odd.next odd.next this means that we've essentially erased the connection between two and three so there's no connection here let's erase it next we set even to the new even that next that we just updated logically the next even is four so we move the even pointer now goes on to four now we're ready to go to the next iteration of odd and even so we do the same four operations again first operation set odd dot next to even next so update next which is three pointing to four now even the next is five so let's do that hot.next goes to even hot.next goes to even hot.next goes to even dot next meaning we've erased the connection between three and four and then we can set odd to the new odd next that we just updated so odd which is three now goes to five and then we do the same thing for even that next now becomes odd.next the even that next now becomes odd.next the even that next now becomes odd.next the new output next that we just updated notice that our next points to null which is fine it's totally fine for now so we're going to point even the next to null so even the next points to null and then we can move even to the new even the next that we just set even moves on to even that next and now we can erase the connection between four and five so this has been updated and also five and null has been updated so this connection is no longer there so now what you can see is that we're ready to go into the next iteration but the constraints to go into the next iteration is if either like odd next is equal to null or even the next is equal to null and in this case they're equal to null so now we're going to break which means we're going to break out of the while loop and we're done constructing two separate lists two independent lists of odd values and even values let's see what we just did here so as you can see one points to three point two five and then two points to four so now all we have to do is to connect the last value in the odd list the last element in the odd list to the first element in the even list so now we just connect 5 and 2. it's going to be messy if i do it here so i'm just going to move everything up a bit and then write it at the bottom so we've got one pointing two three pointing to five and then we've got two pointing to four and then four pointing to null and now we just have to connect five and two this is the bridge that we're going to make here that connects to your list and this is the final answer so if you were in an interview setting it's highly unlikely that you would think of the second solution but that's okay if you have a working solution you could discuss more optimal solutions with your interviewer as long as you have an idea that your solution can be optimized and you could talk about like potential optimizations with your interviewer even though those potential optimizations may not be fully fleshed out it would be like a conversation starter and you could talk about more you know computer sciency things in the interview and that's really important to have that like back and forth conversation with your interviewer and that gives them a sense of how deep your knowledge of computer science is so don't beat yourself up if you don't come up with like a super optimal solution what you should try to do is come up with a working solution like a first solution and then try to optimize it as you go you may even go for another solution that's right in the center of these two solutions that we just discussed or you can use the two pointer runner technique and have two runners a fast runner and a slow runner going through the same list so while iterating through the linked list you're going to have fast runner and slow runner going to the same list the fast runner moves two steps at a time and the slow runner moves one step at a time so the slow runner would point to odd notes and the fast runner since it moves two steps at a time it would point to even nodes then you can create a new note at every instance of the fast and slow runners maintaining the two lists as you go and join those two lists at the end so this strategy is explained in detail in the partition links list question that we have on this channel i'll put a link in the description or on the screen and i highly recommend you watch it to learn uh more about this type of solution the runner technique is super important in solving links this question so you should definitely watch that video so let's talk about the time and space complexity of um this solution so for time complexity we're going through every single node in the linked list so time complexity is going to be o of n so t is of n and then for space complexity we are not storing extra space so space complexity is going to be o of one so yeah that's how you solve this question guys let's dive into the code lady so the first thing we're going to do is have an edge case that checks for well if the head is equal to null if this is the case then we just return now so with that out of the way let's initialize the two lists the odd and even list so let's say list now pod would be pointing to the first node in the list which is the head and then we have another list node called even which would be pointing to the second node in the list which is next now you see why it's important to have this check here because if head is null head next would give you a null pointer exception and you don't want that so now we're going to have like the third list and this is important so we can create that bridge at the end that connects the even and odd list so let's have another list node let's call it even head and that will just point to even so now let's iterate through the two lists that we have here so let's say while um even is not equal to null and even that next is not equal to null let's do stuff so if you're wondering why i did even is not equal to null or even that next is not equal to null or even can even be audited next because object next is just even the next element after odd is even so you can do odd that next is not equal to null that even that next is not equal to null or you can do even is not equal to null and even that next is not equal to null whichever one works for you i think this one is a little bit more readable so i'm going to keep it and in this while loop we're going to do stuff and what are the stuff we're going to do four operations first operation is set on.next first operation is set on.next first operation is set on.next to be evened up next then we're going to set odd to be odd.next that's the new set odd to be odd.next that's the new set odd to be odd.next that's the new output nets that we just updated here so set odd to this odd next that we just updated and then we do the same thing for even i'm just gonna say do the same thing for even so what are we gonna do we're gonna set even the next to be odd to the next and then we set even to be equal to even that next the new even that next that we just updated here and at the end of the wild wave after breaking out of this while loop all we have to do now is just set on to the next to be equal to even head and then even head points to the first even and this is the bridge that we're going to create between the odd list and the even list now the only thing we have to do is to return let's run this and see what happens awesome it's accepted let's submit this and it's successful so that's how you solve this question guys if you like this type of content please consider subscribing to the channel comment down below if you have something to say also smash the like button for the youtube about everything share this video around the community and i'll see you next one bye for you
Odd Even Linked List
odd-even-linked-list
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,3,5,2,4\] **Example 2:** **Input:** head = \[2,1,3,5,6,4,7\] **Output:** \[2,3,6,7,1,5,4\] **Constraints:** * The number of nodes in the linked list is in the range `[0, 104]`. * `-106 <= Node.val <= 106`
null
Linked List
Medium
725
1,094
hey guys welcome back to my channel and I'm back again with another really interesting coding interview question video this time guys we are going to solve question number 1094 carpooling before I start with the video guys just want to request you that if you have not yet subscribed to my channel then please do subscribe and hit the Bell icon for future notifications more such programming and coding related videos and now let's get started with the problem statement you guys uh we have got a car and we are given the capacity of the car which is the number of empty seats and this vehicle only drives in One Direction okay so it cannot drive backwards it is only driving forwards and we are given a sort of an array of array okay a list of list as you can see and this is called as strips okay and you can say that in this list every single uh single object is uh is comprising of three things okay so every single small sub array is comprising of three uh numbers the first number in this sub array represents the number of passengers in this trip the second number represents from where from which position this trip is starting from so for example in this case the trip starts from number one position and the last thing represents where this strip ends so it starts at position number one and it ends at position number five so basically it is uh making it is traveling five stops starting from stop one to stop five okay now there is another trip which is mentioned here and in this trip the number of passengers which are traveling are three it starts from stop number three and ends at stop number seven okay so what happens in this car is that according to these trips when according to the starting and the ending position of the trip the driver takes the car from one place to another from one trip to another take takes the passengers you know and then drop them to their location what happens is that the car is having a certain capacity certain number of seats which is given to us by this capacity okay we have to return true if it's possible for the driver to pick up and drop off all the passengers in all the given trips given in mind that we have got a certain capacity so for example if there is a case that the number of passengers which are waiting for boarding the car is more than the number of passengers the car can actually accommodate it means that we cannot do that trip so for example let's say at a given point in time so this card is having two passengers right it starts from stop number one and it ends at stop number five so when this car will be on stop number three it will start another trip but in this second trip you can see that three passengers are waiting for the car to board the car is already having two passengers in it from the previous trip and if it boards all these three passengers then the capacity will be overboarded and the capacity is only four we cannot board five passengers so that's why it's not possible for this car to take all the trips successfully hence the output is false if it's possible so for example in this case you can see that the first rib starts with the stop one NZ top five and in this case two passengers are also traveling and the same second truth is here three passengers are starting from stop number three ending at stop number seven so obviously at one point in time we would need five passengers to sit in the car and in this case the capacity is five so that's why it's possible and hence the output is true so this is how this problem statement is that the constraints are also really important to look at in this problem statement basically it says that the trip length that means the number of trips is only 1000 can only be maximum 1000 and obviously every uh trip small sub array is having three elements the number of passengers can go from 1 to 100 from and two locations can go from zero to one thousand so that's why I said that the number of trips could only be 1000 and the capacity can actually vary from 1 to 10 to the power five okay so these are the constraints now that we are clear with the problem statement let's jump to the solution approach so for this problem statement guys basically we have got two solution approaches one is going to be the solution approach which is the more logical approach and first we are going to discuss that and second we will discuss the other approach which can actually is a sort of a hack but it can actually work in this problem statement so the first approach which we are going to use is an approach taking Min Heap as a data structure so think of it like this our mean Heap is going to accommodate all the trips and on the uh top of the trip is going to be drag trip which is having the minimum ending value that means which is ending the soonest so this mean here is going to have all the trips sorted of trips so that the trip ending earliest is on top okay so we will create a main Heap like this but before even that the first thing is that we are going to sort all the trips according to their starting position so actually it should be like this only that we cannot assume that all these strips are actually given to us in a sorted fashion uh but obviously the driver is going to start from the drift which is at the earliest of first so it's going to start from stop number one and then go to stop number two and then to three so we can assume that driver is going to go in this direction but we cannot assume that the trips given to us in this area automatically sorted by the from value of the trip so that's why we have to sort the trips first according to their positions so the first thing is that we sort the trips then we create a mini heap of trips chips mean Heat so that the trip which is ending earliest is on the top of that MIDI now what we are going to do is really simple anyone can guess it that we are just going to go through all the trips just reverse the trips find out if any trip is ending that means you will just pull it out from our mini heap so in this mini we'll just pull it out the trip we'll see if that trip is ending or not so at every single stop all the trips which are ending you will simply deduct their passengers from our currently present passengers and the newly added trip its passenger will be added to the currently present passengers finally we will check if the capacity is greater than the given capacity or not so I'm just gonna write it down for you guys so for each trip we will deduct the ending trips at that stop location and we will add the new trips passengers too the current passengers so at every single uh at every single trip we will find out if there are any passengers to be deducted and for that trip we will simply add its passengers to the current passengers if the current passengers becomes greater than the capacity we return true sorry return false and once the loop is over we will simply return true it basically means that the driver can complete the ship okay so now that we are clear with this problem statement and we are clear with the solution implementing this is really easy guys let's jump to the implementation part so the first thing is we are going to sort our array so I'm just going to use a Java arrays.sort functionality this is a Java arrays.sort functionality this is a Java arrays.sort functionality this is going to pass the trips into it and then because it's an array of array so you have to add a custom comparator so I'm going to add comparator and in this there is a function called as comparing comparator dot comparing basically I'm going to use a Java Lambda in which for every trip which means this value I am going to compare the from value for it so this basically means that all the trips which are starting uh first will come first and the strips which are starting later will come next okay so it will start the trips in there from value from the ascending order once we have sorted it next thing is that we are going to create a mini heap and in Java we use priority queue for priority Q and this Q is going to be holding integer arrays so it's all going to be holding this entire trip array so that's why the generic type is integer array and then I'm just going to write it as Min Heap equals to new priority queue and now again we are going to add a comparator object but in this case we are going to use comparator dot comparing sorry comparing but in this case guys in the Min Heap we want the tray which is ending the earliest on the top so in Min he we are going to use comparator dot comparing trip Lambda trip 2 because uh trip 1 is your from okay so this trip one index is your from and Trip 2 is your ending position and we want the trip which is ending the First on top of the Heap so that becomes your mini now it's really simple guys we are just going to start traversing all the trips so into the trips so every trip in the uh integer chip every trip in the trips array so that every single trip we are going to check if uh there is any value left in our heat in our mean Heap which is ending at this position so while Min Heap he is a not empty and if this Min Heap so whichever is on the top of the Min heap if it's ending is lesser than or equal to the current trip ending Uh current trips starting so if let's say the current strip current trip in this case is starting at position number three and the previous trip is let's suppose in this case it's ending at position five but if it's ending at position 2 then in this case we will simply pull it out from the Heap and we will deduct its passengers so current passengers oh I'm so sorry I didn't create this current passengers object before so this object is just to uh keep track of our current passengers in our car right now I am going to initialize it to zero let's come back to this while loop now so until the Min Heap is not empty and the first value of the Min heave is having an ending before then the current trip so that means we can simply minus its passengers then current passengers will be deducted by minhip and we can just pull it out because we can just take it out from the Min Heap and uh dot pole and 0 index is basically the zeroth index of our trip which is the number of passengers so now we have deducted the passengers whose trip has already ended by the I ended before the country now this trip is uh these are the trips which you have to deduct but the current trip has started so we will add its passengers to our current passengers so current passenger becomes equals to current passenger Plus trip and the number of Messengers are trip zero so that becomes your current percentage now if current passengers are greater than the capacity so it basically means that our car cannot accommodate these number of people we will simply return false and we will not go any further and once this thing is done we will simply add the new trip foreign so as to continue further if nothing returns from this for Loop you will simply return true it basically means that everything is fine and all the trips can be done successfully let's run this code guys let's see if this works you can see that it is working for one example case and hopefully it will work for others as well and there you go we're talking about the time complexity guys so this particular solution is having a Time complexity of order of n login which is pretty obvious because we are first of all sorting it out and second we are using a mini heap so every single operation in Min heave is taking log n and because we are using a for Loop it will definitely be n log n login and the space complexity is order of n why because we are using a Min Heap and it's possible that it can be holding n elements at a time okay so that becomes a logical solution but I told you in the introduction guys that this particular problem has got two types of solution one is The Logical one which can actually get you through in your interviews and one is sort of a hack which definitely works so I'm going to discuss that solution as well so let me just delete everything and go to the description back again so if I scroll a bit down guys you can see the constraints now the constraints here it clearly says that the total number of trips do not exceed one thousand and that basically means that the total number of trips uh I'm sorry the total number of from and two locations do not exceed one thousand I'm sorry not touch its length but the from in two locations do not exceed 1000 which basically means that the number of stops we have are only one thousand now if we go through all these tops and we can just check the number of passengers boarding it in every trip and number of passengers leaving it in every trip we can basically find out the total capacity at every single stop and if at any stop the capacities more than the one which we can accommodate or uh the number of passengers are more than the one which we can accommodate we will simply return Force so this is a sort of a hack guys and now let's try to implement this hack as well so it's pretty simple to implement I'm just going to create a stops array stops equals to new integer and the memory is going to be 1001 because we know that the number of stocks cannot exceed 1000. now for every single trip in my tricks array I am going to populate this top sorry so for every single stop which is on the from location of my trip so the from location is trip one so at every single form location uh you will simply add the number of passengers in that trip so plus equals to trip zero so every single from location so what or so for example in this uh in this case the from location was one so at location number one at stop number one you simply add these two passengers and F stop number one if any trip was uh you know unloading any trip was uh completing so for example in this case at stop number five we will simply deduct these passengers from the stops so at stop number five so how we'll get the stop number five which is the trip index two that is our ending location this is simply deduct the same passengers from it trip zero okay doesn't matter it goes negative you simply add the percentage and we will simply deduct the procedures now I am going to Loop through all the stops stop installed and we are just going to check that the total number of passengers in that stock is it more than the capacity or not so if the value of the stock is greater than capacity it means that on that stop the number of passengers which were there is more than the capacity we can accommodate so we will simply return false because this will not work if we don't return false from anywhere we will simply return so let's run this code guy let's see if this works and uh okay sorry this is not stop it is stops so my array name is tops and I wrote it here without this so that's why there is an issue now that I have fixed it I'm going to run it again and gives me a wrong answer if I think it's not uh stops greater than capacity it basically it should be greater than I think it's uh it's not stopped greater than capacity we just simply have to check if capacity minus top is lesser than zero so if it gets negative basically if um if the if it's if it gets negative if we simply return false and uh oh okay so I'm sorry guys that is my bad so every so for all these jobs at every single stop we are just going to um change the capacity value like this so capacity becomes equals to capacity so at every single stop the positive value means that the total number of passengers are you know sitting in the car so if the capacity is 4 and number of percent is sitting at 2 it means the capacity has reduced so capacity becomes 2 right 4 minus 2 is 2. so at every single stop if the number of passengers are positive capacity will be reduced if the number of passengers are negative the capacity will be uh you know increased so every single stop I'm just going to deduct the number of passengers from capacities the capacity becomes equals to capacity minus top so remember if this value is negative this is going to increase the capacity if this value is positive this is going to decrease the capacity but after doing this if capacity becomes lesser than 0 it means it becomes negative then we will return false otherwise we will return true so I'm sorry guys uh I got a bit confused in uh earlier but actually it's like this at every single stop we will recalculate our capacity and see if it's getting negative or not so let's run this code guys let's see if this works and there you go now it's accepted and uh there you go it will get accepted for all our cases as well and yes now if I talk about the time complexity so this is pretty much you know order of n because uh we only ran this follow and this follow which is only for n elements 1000 elements so that's why the complexity is this and space complexity is also order of n because we are using an extra array so this is definitely better in time than after your solution but will it work in every single case if I increase the number of trips from 1000 to 1 million we don't know if you increase the number of stops from 1001 million we don't know it will uh will it work that well or not because we don't know if we don't know the this constraint if we don't know this n value then we won't be able to implement the solution right so this will only work if you know the constraints so that's why it's not the best solution it's sort of a hack which works okay but I hope guys all the solutions are clear to you and all the approaches you did like it if you did guys then do not forget to like this video and share this video with your friend uh if you have any questions comments suggestions feedback for me please write down in the comment section below I would be happy to address it happy to hear it and 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 and coding related videos I'll see you guys in the next video Until then take care and bye
Car Pooling
matrix-cells-in-distance-order
There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them up and drop them off are `fromi` and `toi` respectively. The locations are given as the number of kilometers due east from the car's initial location. Return `true` _if it is possible to pick up and drop off all passengers for all the given trips, or_ `false` _otherwise_. **Example 1:** **Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 4 **Output:** false **Example 2:** **Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 5 **Output:** true **Constraints:** * `1 <= trips.length <= 1000` * `trips[i].length == 3` * `1 <= numPassengersi <= 100` * `0 <= fromi < toi <= 1000` * `1 <= capacity <= 105`
null
Array,Math,Geometry,Sorting,Matrix
Easy
2304
3
in this video we'll go over lead code question number three longest substring without repeating characters given a string we have to return the length of the longest substring without any repeating characters for example if the string is hello then the longest substring is hel so we'd return three there is no other way to get a longer substring without having repeated characters now one way to do this would be to calculate the length of every possible substring so first we'd find all substrings starting with the letter H including the full word itself then we'd find all substrings starting with E and we'd continue this until every substring has been found this runs in O of n Square time we're not done yet though because we now have to check every substring for repeated characters we can do this by iterating through each substring and keeping track of the characters in a set for example to test the string hello we'd look at h e l then when we come across the second L we see that we already have an L so hello is eliminated now each one of these checks runs in of end time and we'd have to do that for every single substring which took o of N squared time to generate so in total The Brute Force algorithm ends up running in of n Cube time so instead of doing that we'll use an optimized o of n algorithm by using two pointers to maintain a sliding window and eliminate unnecessary computations here's the idea let's use a slightly longer string and say a b c d c e f g is our string we'll use two pointers a left and a right pointer to denote where the substring starts and ends the substring starts off as just the first character a so they both point to a and the length of the substring is one character from here we'll move up the right pointer one character at a time and try to expand our substring so our substring is a b so we're still okay so let's extend it to ABC then a b c d and now we're at four characters but now when we try to extend it to a b c d c the letter c is repeated so what do we do well the first Insight is that we don't need to look at any more substrings starting with the first character a because all other longer substrings are still going to have that letter C repeated so we can skip all those computations and just move the left pointer up and start looking at substrings starting with the second character but notice that we haven't solved our problem yet the letter c is still repeated so should we still look at substrings that start with the letter B well this substring is clearly invalid so any longer substrings will also be invalid shorter substrings might be okay but there's no point in looking at those because they're always going to be shorter than the last valid substring we just saw in this example you can see that we already shortened the substring one character by moving up the left pointer and by moving the right pointer one character back we've now shortened it by two characters which results in a substring of length three this is already shorter than the last valid substring that we looked at which was four characters long so the conclusion is we can also skip all substrings starting with the second letter B because they're all going to be either invalid or too short so we can move up the left pointer again the same logic also applies to the third character this substring is still invalid any longer substrings will also be invalid and any shorter substrings will be too short and so finally we move up the left pointer to be one character past the C character and now we can resume our search we then keep on moving the right pointer to expand the substring as long as no characters are repeated and finally we return the result a length of five so our algorithm will be keep moving the right pointer to extend the substring until we reach a repeated character at that point move the left pointer up until the repeated character is gone then we keep on repeating these steps until the right pointer reaches the end of the string we only have to Loop through the string once so this algorithm runs in O of n time the only question we haven't addressed yet is how do we know where to update the left pointer when a repeated character is found well instead of looking at each character and moving it up one by one if we keep track of the index of each character using a hash table then we can look up those indices and constant time so now let's look at the code and see how we can piece all of that together first let's create a dictionary called scene because it'll keep track of the indices of all the characters that we've seen before as we Traverse the string the key will be the character and the value will be its last known index then we'll set our left pointer L to point at the first character at index zero and we'll also initialize a variable called length to zero length will contain the length of the longest substring that we've encountered next we'll Loop through the entire string using the variable R which will be the right pointer R will also start at index 0 so at this point both the left and right pointer are pointing to the same character we're going to be adding a character at the right index so I'll save that character in a variable called Char so that's a now we'll test for two things if we've seen that character before and its last known position is greater than or equal to the left index then that means that character is repeated somewhere in the substring so we need to move the left index up you'll see an example of this later but for now this is the first time we've seen the letter A so we'll jump to the else block and calculate the length of the substring by doing R minus L plus one we have to add one because we're including both the left and right pointers as part of the substring so right now this would be zero minus zero plus one so our substring is one character long it's just a letter A then we'll take the maximum of that number and the length variable to make sure that the length variable always contains the maximum length encountered so far so 1 is greater than zero so we'll update length to be one then at the end of every Loop we'll record the position of the character we just added so we'll add a key of A which corresponds to a value of zero its index then we'll go on to the next letter B this is the first time we've seen the letter B so we can add it to our substring and now the length is 1 minus zero plus one which is two then we'll record the index of B which is one the next letter is C and it's the same thing we can just add it to the substring update the length to be three and record the index of C which is 2. now for the next iteration the character is a now we have seen this character before and its last known index 0 is greater than or equal to the left Pointer's index which is also zero this means that the character a is repeated in the substring so we'll have to move the left pointer up we'll do this by finding the last known index of a then moving the left pointer one spot past this index the last known index of a is zero so we'll update L to be one now that the first a is out of the substring we can move on we'll update the index of a to now be 3 and we'll continue the next iteration is similar Char is C which we have seen before and its last known index is 2 which is greater than the left index which is one so we'll update the left pointer to be two plus one which is three so now C is no longer repeated and will update its index to be four now the next iteration is kind of special Char is B which we have seen before but its last known index one is less than the current left index three this means that even though we've seen it before it's outside of the substring so we can just add it onto our substring and calculate the new length which is still three and update B's index to be five next is D which we've never seen before so we can finally extend the length to be four characters and record the position of D which is 6. for the last iteration we come across D again which is obviously repeated so we'll move the left pointer to index six plus one so seven that was the last iteration so we can just return length and we're done and remember since there's only one Loop that goes through the string once and since hash table lookups run in constant time this algorithm ends up running in O of end time
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
1,870
hey everybody this is larry just me going with q2 and you can see that i struggle out of this one uh minimum speed to arrive on time so this one conceptually is not that hard but for me i had issues with uh precision i think to be honest if they're going to do something like all these weird hours stuff with two digits after the decimal they should have um uh they should have just given you a string so that you can pause it better um because if they give you enough it's gonna always be a little bit off uh or like it's not you know you don't get to choose um to position uh so that this one's a little bit awkward for that reason um but yeah but the way that i would that i did do it uh very quick i didn't okay time it's just by binary search um the idea is that you know ignoring the precision problems which i'm not going to go over that much because it's precision forms can go you know beyond the scope of whatever so you have to really uh er yeah position forms are hard uh it's beyond my ability to teach i think because it's just one thing is that i avoid as much as i can which is why i think that the input should not be a flow but going back a second on binary search um the idea is that okay you have some speed function right um so the thing is that obviously um so there are two uh you know things that make it monotonic so that you could do a binary search which is that okay given a certain speed um if speed works then speed plus one works um and et cetera right speed plus two works and so forth right um so that's par or all you need to do and just based on this that's all you need right because that means that you know you kind of part of the true force thing you get force oops you have force voice force right and you know and these are discrete speed and now you're trying to find the minimum speed for which this is true so you're trying to find the first true if you will uh so basically just you're looking for this thing um and then your function is just you know implement what they tell you right um to calculate whether this speed is good you just do 4x you know for each distance you do the time you round up because um because the tr the bus or train whatever it is um the train leaves only at the hour so if you have if you go over the hour you know you just keep going right um and then that's pretty much it uh yeah so you round up and then at the end you do some math on you know whether the last part of the trip um on the last part of the trip whether that is you know that fits you into the fraction part of it um there's some precision issue here as i mentioned i'm not going to get into but you know but this is pretty much how you know um because basically this is just our uh we check with our the fraction part of our is bigger than x minus speed uh which because x is the distance um and of course that means that you multiply speed on both sides to get this thing um again precision errors aside that's basically it um so on the binary search you go okay so the way that i always think about it instead of memorizing patterns is i go okay there are only two scenarios right um so that you know given these dysfunction it could either give you a force value or a true value if this is a force value then what happens that means that uh that means that everything to because we're looking for a true um that means that this value is eliminated and everything to the left of this value is eliminated meaning that the left will have to be on the next value so that's basically how i write you know if this is not good then left is mid plus one and then the only other possibility is that and um i guess i forgot to mention this is that i use uh this inclusive range because the reason is that um if left is equal to right and it is inclusive that means that your answer is on the left or the right because they're the same number uh but in any case the other case is that if this is true then you know that everything to the right um is no good because this is all you know your maximum answer is already you know this is already an answer that you can return so everything to the right of it we don't have to look up so that means that we can eliminate everything to the right meaning that we set the right to admit um so that's pretty much it this is binary search uh it's a very tricky problem uh yeah so um there is a very tricky problem because i spent like eight minutes uh and the wrong answer or on just a position uh and even before that i had some weird off by once or something um but you know uh hope you did well uh and you could watch me sub it live in the contest next c so um not just too much waiting which we must travel what an awkward problem i don't even know that's enough position this is good why is this not the third hour is a very awkwardly phrased problem and no one has gotten it yet for that reason even though it's a cute too this is good and we can try a smaller one i have to test it and this is like really awkward but so especially why is it so awkward um and now this is our i like that there's a way awkward oops touching up here that's not even right oh no hmm so speed one i might force why divide force because so foreign why is it force because at the speed one wow this is not going well but let's speed one so this should be four for time so that's two hour is two speed is one and x is equal to two what why is x three oh man i am dumb um speech should not be zero that's fair is that good enough okay i don't know if this is right though but what an awkward problem please if it's too slow i'm gonna be sad okay wrong answer still sad why do i give 2.01 so my speeders i hate you but okay so at 2.01 hmm does not make sense why am i off by one i mean i know why i'm 151 but maybe there's a dumber way of doing it to be honest and i'm just being stupid and that's why this position nervous um i'm really struggling on this one this is mostly white but it's such a weird silly problem oh that's only force but why oh because it's one over a million or one over 10 million twice i think is it a big phone i know one over 100 is in there how do i handle this is this round up so then hour is the number that they give you this is so awkward to give you most input 2.01 2. i mean yeah exactly right so this is so silly that they don't even it's the easy way to do this hmm a lot of people got in it though i um what am i doing wrong i know what i'm doing wrong but how do i do it in a way that isn't that oops i mean does that work nope that is just so bad don't know how it's helped us maybe the position was us because this is minusing one over a million at a time but one over a million is two whatever one of these if they give the finger in the string then i could handle this much better but i don't know how to solve this maybe so why can't i just multiply this it's really awkward and i got the concept like pretty quickly it's just i don't know how to implement the thing in a good time like how do you resolve the worst case i'm playing multiple times okay fine it does seems like the worst answer is like what that mean but how do i fix this is that good enough i don't even know anymore probably still wrong to be honest just such a hack but now i don't know how to do it huh okay that's such a silly hack so i don't uh this is me again before the contest uh i just forgot to talk about the um the complexity um this good function is gonna be linear time so this is of n time this function is going to be o of log u where u is the size of the universe uh which i just i took 10 to the 12 but i think 10 to the nine is probably good as well because that's just ours um as a result the entire tire uh the entire complexity is just going to be o of n log u and in terms of space we don't use any extra space so that's pretty much it uh and you know n is 10 to the fifth and this is going to be roughly you know 20 or 30 or something like that um so yeah this is gonna be fast enough and that's basically it uh and now you can watch me stop it live during the contest next hey uh yeah thanks for watching hit the like button hit the subscribe button join me in discord let me know how you did on this contest i did okay but uh yeah and also on this problem what do you feel about my solution um yeah you know stay good stay healthy to good mental health and i will see you later bye
Minimum Speed to Arrive on Time
minimum-speed-to-arrive-on-time
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. Each train can only depart at an integer hour, so you may need to wait in between each train ride. * For example, if the `1st` train ride takes `1.5` hours, you must wait for an additional `0.5` hours before you can depart on the `2nd` train ride at the 2 hour mark. Return _the **minimum positive integer** speed **(in kilometers per hour)** that all the trains must travel at for you to reach the office on time, or_ `-1` _if it is impossible to be on time_. Tests are generated such that the answer will not exceed `107` and `hour` will have **at most two digits after the decimal point**. **Example 1:** **Input:** dist = \[1,3,2\], hour = 6 **Output:** 1 **Explanation:** At speed 1: - The first train ride takes 1/1 = 1 hour. - Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours. - Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours. - You will arrive at exactly the 6 hour mark. **Example 2:** **Input:** dist = \[1,3,2\], hour = 2.7 **Output:** 3 **Explanation:** At speed 3: - The first train ride takes 1/3 = 0.33333 hours. - Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour. - Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours. - You will arrive at the 2.66667 hour mark. **Example 3:** **Input:** dist = \[1,3,2\], hour = 1.9 **Output:** -1 **Explanation:** It is impossible because the earliest the third train can depart is at the 2 hour mark. **Constraints:** * `n == dist.length` * `1 <= n <= 105` * `1 <= dist[i] <= 105` * `1 <= hour <= 109` * There will be at most two digits after the decimal point in `hour`.
null
null
Medium
null
329
Hello hello guys appeared in girl shot today is not another google interview question to solve your friend has been recently interviewed by google and this question has been lost to him long standing bath in the recent sea inverter companies question appears for this question appears in google prayer Times Facebook at Times f5 times Amazon five times and Microsoft two times in recent months OK should this problem be VHP's trick hai so how this problem arises like given interior metrics and what we need to front find the length of the longest increasing bath OK So from which you can another mode to the four directions left side tap and don't you may not mode a tap and Mukesh Yadav country or have parents not allowed okay so example number one can see like the longest increasing the live with 6 this is the meaning Of This Is The Longest And Smaller Should Have To Find The Right Path And Subscribe Now To The Side Sexual Subscribe Like And 324 506 Aaj Movie Jaana Hai Subscribe Should Here Go For This Problem So They Can Solve Like Poets From Each Sale OK we can move to the self and neighbors who never and monitor that school what is the maximum from which of the national bus ok so airtel there are possibilities for the next flight one point to solve like must subscribe our channel like and any number of chal Sake Thank You RCCC Notes That You Timely Yudh Tabs Very Valid For Se Teens How They Can Optimize Pitch Actually Job Vacancy In This Problem Well So 101 Of Any Further Stated In To Calculate The Results To Calculate The Results To Calculate The Results So They Can Live With Its Allied 9 And Give Me To The Know Like This Page Number 90 From This Dish To Front Veer Work And 1981 More Value 810 Result Might Be Used In Schools Not Given In Matric Sham Problems Caused By Others On A Possible Student Result Ok Latkan Rarely Used Instead Of Going And Calculating For It Again And Again To Here Vacancy Like And But All Property Ok So Special Example Work And Where They Can Apply Dynamic Programming Memorization 100MB Solve This Problem Using Position Solid State Museum Printer Code Is So Let's Calculator Size metrics and by using who socks Santa like you can see a time complexity and reduced from 4 to the power of amount to only daughter of and cross is so let's calculator sizes are equal two a matrix dot length that fantasy culturor who skin Which deep length a hunt create and arya the interior memory card se kas hai iss tree se nichala disti g this essay teacher and Kashi in hand with unmodified actions will create and edit directions ki kaise jeevan ka maun ko fold latitudes show their Majiro a Minus one work 80 90 ka mal-1 90 ka mal-1 90 ka mal-1 that me work - 1304 production Quikr Namo that me work - 1304 production Quikr Namo that me work - 1304 production Quikr Namo Hello friends that under it's given like we can start from any where they can form a chain reaction mode show will need to calculate the results from each of the cells okay So 102 That They Tried To Quote From Each Other To Pickup Wear Look To Move From Any Sale On That Neck And High Plus Silent Text From Jira Challenge To Z Plus App A Tax Credit Available And So That Pension Equal To A I Maths Notes On A Solution se ai ka maje da the matrix hai a strong and well written result ki not simply mandir songs all 216 aur pant ko kaise rok ki print column the saint matrix hai ko switch ek ladki ek a ki aisi hai base result calculated in world me maurya Similarly this dish result 10th sample taking internet don't need to calculate again sampler written a tot loot column undefeated 9th class 10th calculated by going into all the four directions on 200 point note d the intellect equal to stop plus app ki BJP jhal hai Waist is zero vacancy is the saint and a girl to column of two plus its i gamma-1 person fit column of two plus its i gamma-1 person fit column of two plus its i gamma-1 person fit not the outside of this great that spain is a that taking the wicket of reserve bank 1046 is great if equal to a matrix dot length and On do it immediately 90 1104 Give advice Open the song A Matrix 087 Length and Vaikuntha Increasing Path Soviet to take and like a small window in and for smaller and like in it Caller like and path should need to take a great Indian festival word matrix That N Year ago it is ordered the matrix proven and vein treatment as answer plus because they are collecting results by going to darshan rehab to z till urgent sale * * answer because you rehab to z till urgent sale * * answer because you rehab to z till urgent sale * * answer because you need to find the longest increasing bath and current sale is gold and unit In Path So They Need To Have Been Created To Forget To Share And You Will Feel Very Memorial Gift Royal To Column's Choice To Answer That Unwritten Andar So Let's Pray To Run This Jhal Hai So Why This Answer 's Main What The Are Now Device less 80 's Main What The Are Now Device less 80 's Main What The Are Now Device less 80 ki aapke hain akshar de sorry ni0 comedy one can wait kar do ki purush voltage ki naked photo the matrix jhal ki no let up tight ho raha hai net the city but in fact refine latest tyunther input jhal mein rak or person format Chakli Fine Paste Summit Main Soya Fund Channel Ke Sajal Hai That Reply Ki The Matriculation Tunnel Is And Return To Matrix Length Calculate U0 Simply 100 Ki Citric Acid Handed Over This Video And Voice Mail Version Concept For More Videos Laddu Subscribe my channel thank you for watching
Longest Increasing Path in a Matrix
longest-increasing-path-in-a-matrix
Given an `m x n` integers `matrix`, return _the length of the longest increasing path in_ `matrix`. From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the boundary** (i.e., wrap-around is not allowed). **Example 1:** **Input:** matrix = \[\[9,9,4\],\[6,6,8\],\[2,1,1\]\] **Output:** 4 **Explanation:** The longest increasing path is `[1, 2, 6, 9]`. **Example 2:** **Input:** matrix = \[\[3,4,5\],\[3,2,6\],\[2,2,1\]\] **Output:** 4 **Explanation:** The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed. **Example 3:** **Input:** matrix = \[\[1\]\] **Output:** 1 **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 200` * `0 <= matrix[i][j] <= 231 - 1`
null
Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Topological Sort,Memoization
Hard
null
1,793
what's up everyone myself Aditi and today I'm back with lead codes another daily challenge problem so today in this question we are asked to find maximum score of a good subar okay let's see the overview of the question you are given an array of integers nums which is zero index you are also given an integer K and they say that the score of a subar starting from I up to J is defined as minimum of elements or numbers starting from index I up to index J multiplied by J minus I + 1 okay they say that a good J minus I + 1 okay they say that a good J minus I + 1 okay they say that a good subarray is a subarray where I is less than equal to K and J is greater than equal to K so basically in the end we are required to return the maximum possible score of a good subarray okay so uh basically the problem overview says we are given an array of numbers and a special position that is K within that array and we want to find a specific subarray that maximizes certain score okay so basically the goal is to find a subarray which is centered at K that maximizes a certain score so um what should be the approach to solve this problem let us understand with the help of this example given okay so basically the example is uh first of all we are given an array of integers integer array nums which includes the elements 1 4 3 7 4 5 and you are given an integer k equal to 3 fine so in this question you can clearly see that K is three and what's the approach to solve this problem so in this uh particular problem what are we uh planning to do we are as you can clearly see since we are given an array um and we need to find a special subarray that gives us the highest score so it has to be uh the approach involves that the subarray is centered around a special position K okay so I decided to use an approach called expanding from Center and it just involves starting from K okay and expanding both left and right to found the boundaries of the subarray so initially what I am doing I am just initializing my left and my right as the K itself and then I'll expand my subarray in order to find the highest score okay so uh the reason I chose this approach it is because it allows us to consider all possible subar centered at K efficiently okay by expanding both ways we can capture the maximum range that contributes to that score fine so what I have done in this uh particular example and I'll be doing the same to solve the question as well so I'll first initialize some variables one is left another is right and I'm just assigning them the values of K itself okay and uh um so basically let me show you the pseudo code here I'm initializing left and right variable equal to K and then I'm initializing my minimum height is equal to nums of K okay so basically uh as I can as I have clearly mentioned here that the good score is u in the question you can particularly see uh that in place of this numai they have given minimum of number starting from uh index I up to J okay so when I have already initialized the values of left and right that is I and J okay when I have already initialized the values of I and J as k then it's so obvious that I will be you know at the K index and that will be the minimum of it because it's so obvious when your left and right pointers are exactly pointing to the same number then the minimum of both of those will obviously the same number okay and then that's the formula so what's my pseudo code I'm initializing both left and right to K and then I'm initializing my minimum height equal to nums of K okay the minimum of all the numbers when both are pointing to k then it will be equal to nums of K okay and then what will be the maximum score here implies the good score only so it will be equal to minimum height so just to um showcase why it is equal to minimum height I have already solved here you can clearly see the formula to calculate the max score or the good score was minimum of numbers from index I up to J multiplied by J minus I + 1 okay so nums multiplied by J minus I + 1 okay so nums multiplied by J minus I + 1 okay so nums of K will be there fine and then when you can clearly say left is equal to right is equal to K that is J is right and I is left okay they are both equal to K so I have written K minus k + 1 to K so I have written K minus k + 1 to K so I have written K minus k + 1 basically K cancels another K and then you are left with another one okay so basically nums K into one will only give you nums of K so this is some kind of initialization of pseudo code that I'll be using so basically this is the whole approach to solve the particular problem so um fine so this approach has a Time complexity of O big O of n okay the um just a second okay so basically the uh time complexity is bigger of N and why it is biger of n because it involves traversing the array once only where n is the length Okay and the space complexity is bigger of one if we are using a constant amount of extra space okay I've also considered scenarios where K is at the boundaries okay K can K okay so yeah K can be here as well K can be at zero K can be at five okay so I have already considered those cases when K is at boundaries so we'll have to handle expanding left or right accordingly okay our potential challenge could be uh handling cases where elements around K are very large or very small which could affect the score calculation okay so uh to summarize we start at K expand both left and right each step we update minimum height okay we will update the minimum height because it's so obvious when K is at three so it will be nums of K but when we are expanding when we are moving towards left when we are moving towards right so we will have to keep updating the minimum height according to the numbers present so we'll update the minimum height and we'll keep track of the maximum score so far okay so yeah let's start our implementation first of all let's initialize the length of the array as n which is nums do length now let's initialize our two pointers or variables you can say left and right which is equal to K and write also at a okay now let's initialize our minimum height which will be equal to minimum of all of these numbers so when left and right both are equal to K our minimum height will be nothing but nums of K only okay because there will be no two different values to be compared okay now let's initialize our Max score which will be equal to U Min height only why because Min maximum score has the formula that is um minimum of number of I into minimum of nums I up to nums of J which is multiplied by jus I + 1 okay so when is multiplied by jus I + 1 okay so when is multiplied by jus I + 1 okay so when you can clearly see that minimum of all of these numbers is nums of K only and then when we have to multiply this part so when J equal to k i is also equal to K so they'll cancel out each other that is left and right left is I right is J okay so they'll cancel out and then you'll be left with only one and then when you'll multiply nums of K into one you will simply get nums of K only that will be equal to minimum of height only okay so maximum score initially will be Min height fine so let's start our Loop okay we are basically expanding it from our Center position which is at K okay so let's check why left is not at index zero okay while it is greater than zero or right is not at the last index okay so let's check here if left is greater than zero and right is equal to n minus1 okay or nums of left minus one is greater than nums of right + one what is greater than nums of right + one what is greater than nums of right + one what does that mean that simply means when you are expanding what does that mean you are you have both the pointers initialized at K okay so since you clearly know I has to be less than equal to K so it can only move towards the left and right can be greater than equal to K that is J can be greater than equal to K that simply means it can only move towards the right and not left okay so uh when it's clearly given that when you move your left pointer one towards the left and you see that the value which is okay at K minus one index is greater than this what does that mean that simply means you will decrement your left pointer why because you cannot um take the greater value okay because you want the minimum of it so you'll keep moving the left pointer okay now so let's just yeah let's move our left pointer towards the left else if it is not greater than the value which is at right plus one index then we will move the right index towards the right okay then what are we going to do after expanding from Center let's update our height and score okay so here Min height will become after we have multiple values to compare it will become Mach do Min of our Min height comma we will take minimum here of nums of left okay we are going to check it both ways we'll first check it towards the left then we'll check it the right value that is towards the right side okay after index so yeah we'll check it and we'll just take the minimum of minimum height and the value which is minimum out of these two okay so we'll get this so basically we are keeping track of our minimum height and we are also initializing our score okay this is nothing but the current score you can say it will be equal to Simply Min height into right minus left + one okay as given in the formula left + one okay as given in the formula left + one okay as given in the formula that is given in the question which is Jus I + 1 it will be simply right minus Jus I + 1 it will be simply right minus Jus I + 1 it will be simply right minus left + 1 okay and then in the end what left + 1 okay and then in the end what left + 1 okay and then in the end what are you going to return you are just going to return Max score before that what will be Max score will be equal to Simply math. Max of we are going to take the maximum of what Max score and our current score okay that is four if the score or the current score is maximum or it is greater than the max scod that we initialized in the beginning then we'll just update it and then in the end we will return our Max score okay so let's run the code okay so there is okay it has to be equal okay so the mistake is here in the Y Loop the right pointer should be less than the length Okay it should not be at the last index okay so the code is accepted let's submit it thank you for watching guys please stay tuned
Maximum Score of a Good Subarray
minimum-moves-to-make-array-complementary
You are given an array of integers `nums` **(0-indexed)** and an integer `k`. The **score** of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A **good** subarray is a subarray where `i <= k <= j`. Return _the maximum possible **score** of a **good** subarray._ **Example 1:** **Input:** nums = \[1,4,3,7,4,5\], k = 3 **Output:** 15 **Explanation:** The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) \* (5-1+1) = 3 \* 5 = 15. **Example 2:** **Input:** nums = \[5,5,4,5,4,1,1,1\], k = 0 **Output:** 20 **Explanation:** The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) \* (4-0+1) = 4 \* 5 = 20. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 104` * `0 <= k < nums.length`
Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications.
Array,Hash Table,Prefix Sum
Medium
null
39
hi everyone it's Orkin welcome to my channel uh today we are gonna solve Elite code 39 problem a combination sum so first let's read the description so um we are given an input array of integers and we need to find the all combination that in some give us the target for example in this case we have the input array 2367 and the combinations that is gives us the target is two to three and uh server itself so there are two it's important requirements first requirement is that our combination should be unique so if let's say that we are generated another combination two three two that is not qualified as a um as a result because we already have 223 that would be a duplicate another one is that we can use the number unlimited number of times any number so for example two we can use twice and at the same time we can use the three twice at the two three four and the unlimited number of times um yeah that's the requirements so let's see how we are going to solve this problem okay uh let's take the example that we were given uh the array of uh two um 367 as an example and let's uh work on that one so basically we have this array and we have the target which is equals to the seven so we need to generate all possible combinations um so um or so we can tell that the generating all possible combinations it's a backtracking problem so we can qualify it as a backtracking problem and the uh so for the backtracking we need to first thing that we need to do is to specify the base cases so base case in this case would be that the our uh sum either should be equal to seven in that case we backtrack or it should be more than seven okay so uh that is our uh the base case so let's generate our three how we are gonna generate our three so first is let's say take two so we can use the any element uh we will use our element until we either uh hit our base case or we are exceeding our base case uh so for example two we can use once then we can use it's less than it's not equal to seven and it's less than uh seven so we can use it one more time Q2 we can use it one more time that is two uh and we can use it uh one more time again so that would be two uh two and two okay so what happens in this case is that we hit our first base case which is our uh our sum is more than seven so in this case we can no need to go further we are backtracking from this solution okay we exhausted that the all possible combinations for two now let's go to the what's the next element so for 222 we consider it also a combination with the two and let's consider combination with the three so basically two and three so in this case we are again backtracking from our solution Okay so another one is another one would be uh to uh another one would be another one uh is uh two six again we are backtracking from here and we are backtracking also from here because it's more than our base case more than seven okay so that the last one is that we need to um uh for you to two and the Seven in this case it's also more than uh it's also more than our uh base case so we are backtracking here okay so we exhausted uh all possible uh scenarios for the two so we consider it two three and the six and seven so we can't backtrack from this branch of our tree so what we need to do we need to consider the next one so the next one is for Q2 is two three right so two 3. so in this case is it qualified as our is it equals to our base case or more than our base case it's actually exactly equals to our base case so we are adding this one to our solution so the what's the next thing is that we need to generate four to two uh two six and which is more than our base case so we are backtracking from here and another one would be like a force 227 we will again backtrack from the from that Branch I guess you get the idea so the same way exactly the same way we are going to generate for the three we are gonna generate for the six and we are gonna generate for the seven if you will generate you can actually practice yourself just to see that the how exactly the tree because the most important thing in backtracking problems is that you know how exactly you're gonna generate the tree so once you know that once you have the once you can visualize that rest of that is just fall in place so um so you can practice how you are going to generate to three and seven and you will see that there is no Solutions and we will backtrack from every Branch for the seven we have only uh so for example for the seven so the first combination that we take when the seven itself actually this is our another solution all right uh let's put the tree that we generated into the code um first thing that we are gonna do we are gonna um we are going to create a method and uh we're gonna create a backtracking method for generating our tree let's call it just the backtracking BT and it's going to taken as an argument our uh candidates first also it's gonna take our Target that we are receiving and also we need to create a result to return and it's a list of the list of integers so let's put here integer and let's just call it simply result and also we need one temporary array also integers so basically what we are going to use that for is as we go over our tree we are going to add each element to the uh to our temporary array a temporary arraylist and then if that is the qualified at the moment that if the combination is equals to Target then we are going to add that temporary release to the result so let's just call it temp and also we need to keep track the beginning of the three that we are generating so from which position we are generating in the next backtracking iteration so let's call it just let's say start okay all right so uh first things first let's put the first for Loop here so I in this case is going to equal to our starting position so it's going to tell from where we should start uh the next one is that so we should put the condition for that it should be equals to A candidates less than kept its length and um we're just gonna increment that so um as we go over and generate our tree we are going to add that to our candidates so uh to our templates first and we are adding that here so just so we are going to add candidates I uh another thing is I wear a click backtrack so basically uh again we are gonna pass our candidates we are going to pass our here what we're gonna do instead of adding the sums combination sum and the comparing with the target we are going to subtract from the Target and to see that if the target is equals to zero if the target equals to zero it means that combination is uh that combination is the combination that we need for example in case of the two three we are going to first subtract the two uh we're gonna have five then we are gonna subtract another two we're gonna have three and then we subtract three we're gonna have zero so it qualifies we are adding that combination to our result but if it exceeds so it means that if it's less than zero so it means that we have exceeded our Target and we need to backtrack so we are going to do that in a bit reverse order that's easier to code so that's why we put here Target minus um uh so Target minus candidates I so the next one is um we are going to put here result uh that we are going to pass through and we will put the temp and the position that we are keep tracking also what another thing that we need to do we need to remove from our temporary result uh our latest element that we have added let's say we are backtracking and we need to keep we need to clean our temporary array otherwise it will have the all the elements that we have added as we go and the generate our tree so for that reason we are removing as we are backtracking we are removing from our um temporary array we are moving that temp uh size minus one but basically the latest element that we have added um yeah that's it for our for Loop that's how exactly we are going to generate our tree uh so we are gonna use for example let's say that the two we are going to use two three six seven right so we are going to use two here we are gonna uh zero element we are going to use until we hit the until we hit our base case and the base case for that would be like a two so when we are using two four times and at the time we're gonna backtrack so that's why we are passing here our uh our starting position I position okay now let's put our base cases the first base case that we have agreed is when the target is less than zero if the target is less than zero we are going to just basically return uh okay another thing is if the target is exactly equals to zero so it means that this is our uh this is the combination that we need in that case we are going to add to our result temp uh we are going to add temp to our result but another thing is we cannot add the temp itself because if we add a temp itself so basically that will be Point uh so the in this array in the result we have uh the all results we will have they will point to the same arraylist in the memory to avoid that what we need to do we need to um uh at the copy after I released at the moment so uh other and the that way we can escape that problem so that's why we are creating here new arraylist and uh so and the taking the copy of the that our temporary list at the moment Okay so uh so here we are just going to Simply create arraylist and uh so let's call it result uh new arraylist and we are gonna backtrack here called our backtracking method we are going to pass here candidates uh Target result in your realist and with zero index because we are going to start from the zero at the end we are going to just return our result okay that's it uh let's see that have we missed anything or all is correct so let me see um temp integer yeah it should be integer okay yeah it works well so that's the solution as I said uh so uh we are generating the tree and then we just put the tree that we generated into the code and this is the two base cases that we have seen in our explanation part that's it for today I hope you liked my content if you liked it please hit the like button and subscribe my channel and if you have any question please leave the leave it down in the comments thank you so much for your time see you next time bye
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
1,320
hey what's up guys this is sean here so today uh let's take a look at this uh problem number one thousand three hundred and twenty minimum distance to type a word using two fingers okay so you're given like a keyboard layout as shown about like this right there are like 26 buttons on top of it right they're sorted like i have i mean alphabetically right and then like the letter a's is in zero it's located at zero so on and so forth the last one is a z here okay and your and then you're given like a word right what is that your input and they ask you to return the minimum total distance to type each string using only two fingers okay so the distance between the coordinates the distance between two coordinates is calculated as this basically the absolute x difference plus absolute of the y difference okay and then the initial position of your two fingers are considered free so what does it mean means that okay so that means that the uh so the first letters right it's always free because you before typing okay before typing the first letters you're there's no distance like uh calculated so which means uh you for the first word it's free okay yeah and then also your two fingers do not have to start at the first letters on word or the first two letters okay so this is just like a further explan a clarification right basically you can use your fingers to type in a few letters and then you can use the other one to type the others okay cool so and then it gives you a few examples here right but let's go back to the to this diagram here right so to this graph a keyboard here so i mean so this problem you know i think it shouldn't be that hard to come up with like a dynamic programming problem right because you know it's clearly that you know at each state we have a few options right we can either move our left finger or we can move to our right finger or we can move our right finger so at each state we have those two options right so that's why i mean it's a perfect candidate for us to use dynamic programming to uh to calculate this problem you know again okay so now with dynamic programming so the first thing the most important thing is that we have to define the definition of our state okay so i think for this problem i think it's pretty straightforward right basically we have like dp here right and then we have dp watts so the first state is like the uh the first data i'm going to have a k here so the k means that we are at the case ladder here okay because we are typing the word from left to right so i mean it's obviously the first dimension of dp is the it's the current letters right basically how many letters we have typed so far okay and then the second one is it's obviously our left finger it's a high and then we have a j is our right finger so i believe this definite this dp definition shouldn't be that hard to come up with right even though it's like three dimensional dp but since it's pretty clear clearly telling you that you have two fingers so which means that i at each state you know any of the two fingers can add any of this board here which means the iron and j the range is in the 26 right and the k of course is the length of this word here so once we have once we define this like uh deep dp definition right and then the next thing is always how can we uh maybe come up with the state transition function right basically you know with the current state means we have process we have processed case letters and then our current left finger is i at ice location and our right finger is at j's location okay so what does that mean right so basically no since we have processed the current case letters right so we know that what's the case letter right so we know the word k here we know though we know the uh the word k right so we so with the word k here uh we know so either i or j is at this word it's at this ladder right because you know that's the definition of our state right so either the left finger is currently pressed it's currently at this ladder case ladder here where the right finger is at this finger where the right finger is at this case ladder so with that we can easily calculate the all the scenarios that can get to the current state by from the dp k minus one state okay so what's the uh then what's going to be the current the previously state of this right so for example let's say the current letter is k here sorry the current the case letter is q here right so how many are how many different uh scenarios we can move we can come to this uh to this state here right basically you know the total combination is you know the left finger can add any position out of this 26 right that's gonna be the first 20 26 possibilities and of also the right finger can also be at any of the 26 possibilities so in total at each state we have 26 times 26 different ways at k minus 1 state that can get to the current state right basically we and we just need to uh consider all of those scenarios and we'll get the minimum value out of them so that we can get the minimum value the minimum distance for this current dp state here and because we have two fingers right again that's why to get to the current state uh i and j here right uh we can use the dp so i uh ii right and j and jj plus the distance from ii to i or from the uh or from the jj to j that's the distance okay it de depending on if we are considering j is pressing at the current word where the i is currently pressing at the current word right basically if the eye is currently pressing at the current word then the distance here will become the distance of i and i right otherwise if you're considering j is pressing uh j is pressing at the current word here then the distance will be what will be the distance of the jj and j okay yeah so that's basically the state transition function here right and then we'll get the minimum out of these things here okay so i'll explain a little bit more while i'm doing the coding here so i think first thing first right let's do an unlock uh word here right so that's the first dimension and to define like a three-dimensional to define like a three-dimensional to define like a three-dimensional arrays in pythons uh and also since we're going to get the minimum values so at the beginning i'm going to i'll be starting at the maximum value for each of the elements here so we have 26 right and then four in range 26 okay so that's the first uh that's the last two state right and then out of this we also have a third uh dimension which is the uh in this case it's going to be the range of n okay so that's how we define like the three dimensional dp right in python so and at the beginning everything is its maximum so since it's maximum we have to get the uh we have to set the base case otherwise in the end we'll always get the maximum value right so then what's going to be the base you know what actually let me try to finish the uh the main logic first so we have a in range one two n okay so this is because we are at the step number uh we are at the second word here yeah so we are we're at the second letter here so now the uh we need to get the current letter right because so the next step is the you know with the current letters since remember we're defining like the index of each letter here right and we have to get the uh the current index so that we can uh map this word into the one not into one of the index in this dp array here so we have index right so the index is going to be what it's going to be the word of word k right uh miners of ordinate or what do you know of the word the letter a okay so that's how we get the current index the index is from zero to 20 to 25. okay so now we have the current position basically so this index is either it's going to be the dp k i and j right so basically this index will be either like the at this the left finger or the right finger okay so now we just need to have loop through everything right look through all the possible scenarios that can get to the current state right so the first thing is the uh first thing is let's uh let's just assume like uh move left finger right move left finger to the index right so that's that so basically the dp k so if you're moving the left finger to the current index so which means the current state is the current left index left finger is at this index right and this thing is at j here right so that's that so we're going to have a minimum of dp of k index right and then j dot what dot dp of k minus 1 of the uh of i right so i n and j plus a distance right i mean you get the distance basically you know so the j that doesn't change right because the right finger stays the same but the left finger got changed basically changed from the current from i to the index and we need to get the distance for this index and i here but how so and then let's define like hyper functions right get distance right so it takes like a two index it got an index one and index two so as you guys can see here we are defining the index from 0 to 25 and to be able to calculate the distance we have to convert them into like x1 xy coordinates right so xy and x2 right equals to what the div mod basically you know i1.6 right i1.6 right i1.6 right i think you guys know this one right basically you know the x is the division after uh division by six and i know sorry and the y one is the uh it's a modular uh divided it's a modular of six that's how we get zero one zero two zero three one zero one so on and so forth right same thing for x2 and y2 we also could do a div mod of i2.6 mod of i2.6 mod of i2.6 right so now we can return the absolute value of the x difference right x 2 plus absolute difference of y 1 and y 2. that's how we calculate the distance so now here we have uh since remember so we move the left finger to the current to the to this index to the current index that's why we're gonna pass in the uh the high and the index right so that's that and of course so we can put most mostly uh paste copy and paste these things so now we need the next one is to move the right finger to the current index to move the right index finger so we have a we have the j at index the j uh stops at the current index right so i'm going to copy these things here then it's going to be i here so again here right so it's still also i like i and j but at this time we're gonna have like a j right because we're moving j in this case so that you know the distance for this one for this k for this photo base from j to the index okay so and in the end right in the end we just need to get all the values right at the last step basically i in range 26 and then for j in range 26 answer equals the minimum answer dot dp the last index of i and j right so these things means that you know at the last step our left and right finger can end up at any location at any of the position on this keyboard here so that we just need to consider all the other possible scenarios out of at the last step to get our final answer right and in the end we simply return the answer basically that's the main logic right to uh for our for this problem now let's go back to here right so we're starting from one right because we are because since we have this k minus one but we haven't initialized the zero case which means as the first step right so it already told us right at the first letters right it basically is it's free so keep typing the first letter is free for us so which means that uh for i in range 26 okay uh basically you know we have a we have dp0 right we have dp0 and then so the first letter is what is the uh first index equals to a word zero so basically i just copy these things here right word zero so it means that at zero right basically you know we can have either left finger or the right finger press the first letter right it means that okay so for example if we use the left finger to press the first letter right it means that how about the right finger so this thing should be equal to zero right but we have three dimensions right that's why we have like this i here right it means that if we use the left pointer left finger to pull to press the first letter so the right finger can be at any locations okay right because it doesn't really matter actually that's why we initialize everything for this case to be zero and same thing for the right same thing to press the first letter with the right finger right so we just in this case the left finger can be at any locations right so that's how we initialize this uh the first step so this will guarantee that uh our following state transition can get the uh the correct answer cool i think that's it let me try to run the code it is not iterable minimum dpk plus oh sorry i think that distance maybe this one here okay yeah so the test case accepted let me try to submit this one yeah so it passed i don't it's pretty slow anyway maybe there's a better solution better approach for this one because as you guys can see here so the uh the word length is 300 right and it's pretty straightforward it's a straightforward that we have what's the time complexity for this we have like this is a just like minor so we have an n here right so we have n times this right 26 times 26 yeah so that's the time complexity right and the space complexity is also the same space complexity is the same thing here time is this space also this yeah pretty straightforward right so yeah i think just to recap this problem right so this one is i think it's one of those classic dp problem and with three states you know every time when you guys see uh like this kind of like typing things if you're doing the if you're doing it with one fingers and then it won't be uh it won't be like a dp problem right because with one fingers you only have one scenario to type in the whole world so the reason this one becomes a pdp problem is that you know it has it at each state you have two options you can either use the uh the left finger or the right finger to do this right i mean actually this problem if you're using like the uh if you're using like a top down i think it's it'll be more straightforward yeah i think top down is it's better than the then the uh then bottom up i think because you know because for the bottom up as you guys can see here we are like actually we're looking through all the possible scenarios right other possible scenarios uh from the previously state but i think if you're using a top down we won't necessarily be looping through autos 26 by 26 at each of the scenario because if we start at this word here right i mean yeah actually you know what let's try to do a top down real quick here okay just give me one second so uh let me quickly implement the top down i think top down is it's better for this uh problem you know okay so to implement the top down right so i'm gonna come out these things here right so we're gonna need everything else okay except for this right so we're going to have like a dp here right so we're going to have same k high and j right so and then we're going to have a memorizations right close to this and then the uh in the end we simply return the what the dp basically you know we start from the first letters and the uh so this part right so how about our fingers right at the either first at the first ladders the finger doesn't really matter it can either start from uh from any of the other location it's just that at the first letters the movement is free so how can we uh how can we check that right so i think one of one ways to we can just pass in like some special values here right like for example minus one which means the uh it's a it's and it says the telling us the okay so it's the first moment so whenever it's the first movement it should be free so which means that we can just simply modify this uh get distance do we have distance we have a okay we just have a uh the distance here right i mean basically if the a it's a equal to the minus one or the b is equal to the uh the minus one and then we simply return uh we return zero so that's the only thing we need to change here okay so that i mean here i think we have a template right so if the k i and j are in the memorizations right and we return the memorizations okay so then here just to answer return the answer okay so here we have answer here and then define the answer as the beginning of the system max right so that's the template basically you know and the uh now is the uh what's the main logic right so we have a current index right the current index is like the word of the uh similarized the uh the bottom up right k minus ordinate of a right and now we only have two options since we're go we're moving forward right so this is basically following the same the description of this problem basically we are typing the words so by typing the current words we only have two options right basically we have dp uh so the next state so what's going to be the next states the next day that we are moving the case by one this for sure and second one is that assuming we're typing the current word right with the left finger that means it means that the left finger will be on the index okay and the right finger is still j right so and then we add the get distance of the what the current this index plot comparing with the previously left finger uh index right so that's how we get the distance and then the second one is basically typing the current word with the right finger so which means the right finger will be current index and the last finger is still the i so same thing here right so now we have a current index with j okay so that's that i mean and the last thing is that we just need to uh return the base case which is the k equals to n right so in this case whenever we have tapping everything we simply return zero basically there's no more movements needed okay yeah i think that's it right i mean run the code so this will accept it submit all right so you guys can see so this one is much faster than the bottom up one so the reason being is that it is like this right as you guys can see here so for the top down sorry for the bottom up scenario solutions here for each of the state we need to basically uh brutal force all the possible previously existed states because with the current state the number basically the numbers can be moved from any of those 26 times 26 combinations right so that's why we have to loop through everything here but and instead for the bottom for the top down scenario solution here we are only we only have like two options here so basically with the current state we only have two options we either go with our left fingers we'll go with our right fingers i mean even though the time complexity is the same but with the top down we have we will process less much less state cool yeah i think that's it for this problem you know at least for this problem top down is better than the bottom up uh hopefully you guys can uh can tell the difference between the top down and bottom up and why the bot the top down is better than the bottom up for this problem okay thank you so much for watching the video guys stay tuned see you guys soon bye
Minimum Distance to Type a Word Using Two Fingers
remove-all-adjacent-duplicates-in-string-ii
You have a keyboard layout as shown above in the **X-Y** plane, where each English uppercase letter is located at some coordinate. * For example, the letter `'A'` is located at coordinate `(0, 0)`, the letter `'B'` is located at coordinate `(0, 1)`, the letter `'P'` is located at coordinate `(2, 3)` and the letter `'Z'` is located at coordinate `(4, 1)`. Given the string `word`, return _the minimum total **distance** to type such string using only two fingers_. The **distance** between coordinates `(x1, y1)` and `(x2, y2)` is `|x1 - x2| + |y1 - y2|`. **Note** that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters. **Example 1:** **Input:** word = "CAKE " **Output:** 3 **Explanation:** Using two fingers, one optimal way to type "CAKE " is: Finger 1 on letter 'C' -> cost = 0 Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 Finger 2 on letter 'K' -> cost = 0 Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 Total distance = 3 **Example 2:** **Input:** word = "HAPPY " **Output:** 6 **Explanation:** Using two fingers, one optimal way to type "HAPPY " is: Finger 1 on letter 'H' -> cost = 0 Finger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2 Finger 2 on letter 'P' -> cost = 0 Finger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0 Finger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4 Total distance = 6 **Constraints:** * `2 <= word.length <= 300` * `word` consists of uppercase English letters.
Use a stack to store the characters, when there are k same characters, delete them. To make it more efficient, use a pair to store the value and the count of each character.
String,Stack
Medium
1128,2307
515
hello everyone next unsolved question we have in our bfs playlist is find largest value in h3ro let's go to the question so given the root of binary to return an array of the largest value in each row of the tree zero industry okay so a pretty straightforward question if you know like we can do it as it is a tree binary tree mainly so we can do bfs or dfs so if we go with bfs we will do level order traversal kind of thing okay so like one then we go for three and two then we will find the maximum our question is to find the maximum in each row so that in each level for first four three two the answer is three two it is trivial so answer will be one for five three and nine the answer will be nine so we can go for bfs also when we try dfs it will need an extra parameter like some level or i will add level to it like we will call a define we will define a function dfs okay and we will take the root initially we will take keep the level as zero and then we will go for another dfs to do dot left okay and root dot write not but like this sorry we'll go for root dot left and we will also add level plus one and for each level plus one we are going to store uh the maximum and minimum in an area like for each level of not level this array of that level is equal to like max of current this comma the whatever we will get from this okay we're gonna do this like it's no big deal let's try it with simple bfs uh if we will have time we will can do dfs too but let's do it simply but okay let's do it with bfs obvious so uh let's take a q is equal to root so here we are gonna do bfs so while q let's create a current level instead of writing this we can say current level or current level is q now q is our current level because we are starting from here so this is like next level we have to fill our next level so how we are going to fill the next level we will check we will keep uh keep taking the next table while q is uh non-empty okay uh non-empty okay uh non-empty okay so while q is non-empty if okay while q is not non-empty if okay while q is not non-empty if okay while q is not non-empty pop the node q dot from starting as it is queue starting if node.left is there queue starting if node.left is there queue starting if node.left is there no dot left then next level append next level dot append node.left okay we have to do same with let's do same with node.right no dot right okay yeah the next level dot no append no dot right now at this point you will got empty now q is empty so what we will do we will append q we will append not we will update queue like now the queue will become our next level okay and yeah this will continue on until this file queue is properly vanished okay like we traversed the whole area now our the situation is we have to find the maximum of it now so we have we already have a level so our result max the result max will be initially it will be root dotted let's check whether the number of nodes can be zero so we have to check first if not root return zero i mean return mdr okay else result dot max is equal to root dot where okay and here update the max of it q is equal to next level so for i in queue okay instead of this press max dot append max off max of node dot valve in next level no did next time yeah this will work no dot so rather we can we should keep it in the list yeah max of node.well of node.well of node.well for node index level and return res max let's see whether our code will is running or not max okay yeah so if next level then only try to do this one more condition we should put because at the end of the leaf max argument will throw an error that the list you are putting in is already empty okay so this was our bfs solution uh we have time to complete the dfs tool it's only seven minutes so let's go for dfs now okay not return 0 it will be the same so let's go for df our dfs solution tfs but for dfs i will always take a helper it will i'll pull for a helper function so initially we have root and level for root is zero okay and what we will do max number of nodes are let's check now what are the max number of nodes it is 10 to the power 4 okay so level can be 10 by 4. so let's create all the levels level array because for each level i will store the max zero we have to store the max or min um largest here largest and node well can be negative also so instead of zero we are going to put float of minus infinity over top minus infinity okay this is our level area now what we will do yeah if root if not root then return okay and if it's not the case then update level adding level array of level equals max of root dot well comma my computer is working so i don't know why okay root dot well comma level of error yeah we are gonna update our level adding like here i have i should comment it out like it contains max of each level okay so yeah now what we can do is root of minus infinity no into total number of possibilities are 10 to the power 4 okay let's take 10 to output so max of root dot well level array level now we are going to call it on root dot left and root dot write also by increasing level from here so it is dfs you can see we are at first going till the uh till the depth of left array left tree then for right tree it's going like this that's why you can see you can observe that it's dfs so okay we are going like this yeah it will work now let's simply call our helper rate uh there's one more thing that our level array should be of maximum height so it will be update we have to up we have to return the level array up to index where we find float of infinity so it's like return level array starting index to where we find first l dot index of load of plot of minus infinity this i should say yeah okay let's try this it's working also let's see um yeah it's working so yeah it's done thank you guys keep watching it subscribe also my youtube channel okay bye
Find Largest Value in Each Tree Row
find-largest-value-in-each-tree-row
Given the `root` of a binary tree, return _an array of the largest value in each row_ of the tree **(0-indexed)**. **Example 1:** **Input:** root = \[1,3,2,5,3,null,9\] **Output:** \[1,3,9\] **Example 2:** **Input:** root = \[1,2,3\] **Output:** \[1,3\] **Constraints:** * The number of nodes in the tree will be in the range `[0, 104]`. * `-231 <= Node.val <= 231 - 1`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
135
hey everybody this is larry this is june 27 of the june decode daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom loading candy uh usually i saw these live so it's a little bit slow um just fast forward and sometimes i even talk about uh like a daily update of some sort for example earlier in the contest earlier in a day in the contest finished third yay try to celebrate victory so that's why i'm just wait maybe it sounds like bragging but if you've been watching the stream or following um i've had a really bad slump where i just couldn't solve problems for some reason during a contest so it's good to kind of have a good contest on under my belt and then the sec the night one night in new york anyway finish 108 had a lot of silly mistake and we're just slow in general but yeah you know i feel like i did okay today so yeah it's a decent day anyway so let's get back to today's farm candy in case you're wondering by the way um if not well you're still here hopefully so anyway okay there's n children standing in line each trio is a sign of rating so we rate childs great huh children childs so we're awaiting children given kenneth each child must have one candy higher rating must get candy than the neighbors okay return the minimal minimum number of candies you need to have distribute the candies to the children okay so i think this just becomes a sort of a simulation problem that you can think about as a maybe a breakfast search or something like that um but the kind of the first observation is probably just greedy right because thinking backwards like the problem tells you that the highest rated child has more candy than is left and is right but in reverse that means that to minimize the number of candies that means that um the lowest rated child will have one candy because that's the minimum and then from then on you could kind of spread it out to kind of see um you can kind of just see how um yeah the order to process it i guess that's about it um is there anything else to say about this one i don't know yeah i think that's maybe the way i would think about it um because from then so basically the idea is that you give the lowest or you give one candy to or the fewest so you sort them in order you get the fewest to the lowest rating and then you remove that lowest person and then you kind of do it again so you kind of keep doing it so um in that in varian and you can't just do the gr the lowest that you can't do and i think that should be good enough uh there's gonna be a sorting there so it's n log n but you know usually n log n is gonna be fast enough unless you're doing some crazy thing within the constants and in this case we just use it for sorting so we do not so yeah um let's see so index let's just say we have assorted ratings we want to enumerate from here so then here we have for index rating in here what are we doing that means oh actually whoops i messed this up we want to sort this thing by waiting first and then index well it doesn't really matter if it's aft huh actually that's interesting maybe i didn't i for some reason i thought that the ratings would be unique now i'm trying to think about a second where what happens if um what happens if two people have the same rating right and i'm just trying to think about this sorting and whether the order matters and i guess it does not only because children with a higher weight and get more candies than their neighbors but that does not mean children with the same rating has to have the same candy as his neighbor that's not one of the requirements even though it feels like intuitively that should be the case for fairness or something but that's not even the case right two people have the same rating doesn't mean anything because for example you can have a child that's like one five one and then you have maybe like one two three four five four three two one um this five is going to have way less candy than this five because they're forced to have you know like the solution supposed to be one two one maybe one um let's see yeah two three four five four three two one something like that right it's the answer but that is you know the fives don't matter but we'll process them together or not together but in that order so okay so let's say now we start by the rating and we keep track of the index we just go left for right for purposes but then now so for index versus for rating index in this thing what happens now let's also have an answer array which is uh let's do negative one times n where n is the number of ratings okay so then now we just go okay so if rating of the index okay so current i'm just trying to think about how to phrase it correctly right because we know how to say it in english before you sing it to a computer that's the hard part talking to computers they're cuckoo uh okay so yeah so let's say we give them default of one candy if the current rating is greater than the neighbor and of course this assumes that index minus one is greater than less than zero and this is then current is equal to max of current and an answer of index minus one right and of course th this number will never be negative one because we're processing this in order um also this is ratings not waiting i guess we never really use this but i mean you could copy and paste it doesn't really matter but yeah but if basically now you're a child you look to your left if you're you have a higher rate anam then you should have uh that number of candy plus one right to have make sure that you have more than them and then same thing for looking to the right and that's pretty much it and then we just set it to current and then the edit very end return answer i feel like this should be it so i oops and also how earlier case let's give it some love running love oh jen i miss a parents probably there's so many prevents for waiting index and sorted in i guess technically this is this inside of that oh i need to do a prevent over this thing which is maybe fair maybe this is what i need actually so that it's a tuple properly okay and technically i guess we don't even use the rating so we can just i don't know but we have to sort it by that so okay but here we don't use it so let's just do this uh oh i know that this isn't the right answer because i look at it and it's quite wrong but it's not wrong it's just that you know we run the total so that's actually my bad oops and you could do it either way you could either add it while you set this thing or you can do a sum of here i think that should be good enough oops so yeah so the key part about this problem and i hope i get this right because otherwise that phrasing is very awkward uh it's kind of noticing the in variant and also it's accepted just in case you wanna uh is knowing noticing the invariant in that you always wanna keep giving the fewest amount of candy to the lowest ranked right so then you kind of process them in that order and as long as you keep processing them in order um you know then you can do things to it which is what i did so what is the complexity of this right well this is going to be n log n because of all the sorting uh and technically of n space well because of here but also though you know if you're observing you notice that we don't actually need this because we can just add it for this particular problem because we only need to get the total but there's also a linear space in kind of creating temporary arrays to be sorted so there's still going to be constant oh sorry uh there's going to be a linear space no matter what at least the way that i did it um yeah uh am i gucci i think yeah so n log n time because of the sorting you can't really avoid it uh i mean you can always say random stuff like linear sorting but whatever that's assuming that we're regular people with our simple comparison based sorts then you know it's going to be n log n and linear time or sorry linear space because of this thing but also just this thing because as i said this one you can remove for this particular problem but here is still going to be constant oh sorry keep saying this linear space um yeah and this is greedy sorting that's what i have for this one um happy sunday everybody uh there's only a couple of days left in june so you made it this far give yourself you know a pat in the back you know uh treat yourself a little bit to something um but make sure you finish the last couple though that's all i have hope you all have a good sunday have a good rest of the week and yeah stay good stay cool to good mental health and i will see you later bye
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
1,319
hey everybody this is Larry this is uh was it day 23 of the legal day challenge hit the like button hit the Subscribe button drop me on Discord let me know what you think about today's poem so uh and also for people celebrating uh hopefully I'm saying it right uh um uh yeah hopefully I'm saying that correctly if not my apologies I Googled it a few times so I don't know uh I'm trying my best anyway all right so today's problem is 1319 number of operations to make never connected okay so there's some and computers they're numbered and there's some connections that are existing you're given initial computer network connections you extract okay you turn the minimum you can extract certain cables between two direct and place them in any pair of disconnected computer instead okay oh I see hmm thank you so my I'm trying to think because I think my initial intuition is just you don't even have to keep track of it you just kind of count the number of edges or something like this and then kind of just count the number of islands right and I feel like you can always just you know do it um but I'm to try and double think whether that is sufficient uh like as a proof almost but I think that yeah if you have extra edges and every time you remove it you're going to connect an item anyway right so I think it's just a number of islands minus one and then see if you have at least n minus one edges if you have n minus one edges it should be okay because then no matter what it's just a number of islands that you have to readjust I think that should be okay let me we'll see if it is but uh I believe so let's do it um yeah so years you go to a number of edges so just connections and then now we want to um do a adjacency list right and it's for you being connections uh typing is hot and basically now we just count the number of connected components which is the number of islands right um yeah and you could do this in two ways you could do a definite search or breakfast search I'm gonna do a breakfast search because n is 10 to the fifth and Infused overhead should be smaller so yeah so basically maybe just like um you know go for search so you have a maybe it's visited it's your first times n right and then this is the current uh start say and then you could have a qv0 collections that deck right also killed out a pen start and then Kern is gonna kill that pop left and then um right uh if not visited we then visited we assumed it true and then Q dot append V right and of course you can change it to a Dev first search by popping instead of Pop left in case you're curious and then yeah and then basically now it is just accounts you go zero oops for uh oh I have to do that thing I said earlier we just have e is less than if you press so if e is less than n minus one then we return negative one because we don't have enough edges otherwise you know by pigeonhole principle is how I'm doing it if you want the proof is because then now by a sort of a forcing function there will be islands that have extra edges and then you can just kind of redistribute them in a number of islands and each one of because every time you move a connection it will remove a double or from a double by double I mean like a duplicate uh unnecessary uh connection to one that connects a new Island right so that's basically the idea um okay I think that should be oh uh it's kind of minus one because you only need minus one for the number of islands Mr Natural Edge case let's give it a submit and it looks good cool it's a complexity here this is gonna be linear time linear space um linear time comes from breakfast search and you know we look at each node once by the virtue of how everything's structured around within it so you can kind of prove that in a good way uh and then that's the note process that's the re part of the linear uh the E part of the linear is that each Edge gets looked at once from you or maybe twice from each Direction so that's still linear right and we also create linear space to due to the adjacency list and also the usage of Q and also visited I suppose um so yeah so this is linear in all of e this is all of a reef for vertices and yeah this is also where this is um yeah that's all I have for this one let me know what you think and yeah stay good stay healthy took a mental health I'll see you later take care bye
Number of Operations to Make Network Connected
unique-number-of-occurrences
There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network `connections`. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return _the minimum number of times you need to do this in order to make all the computers connected_. If it is not possible, return `-1`. **Example 1:** **Input:** n = 4, connections = \[\[0,1\],\[0,2\],\[1,2\]\] **Output:** 1 **Explanation:** Remove cable between computer 1 and 2 and place between computers 1 and 3. **Example 2:** **Input:** n = 6, connections = \[\[0,1\],\[0,2\],\[0,3\],\[1,2\],\[1,3\]\] **Output:** 2 **Example 3:** **Input:** n = 6, connections = \[\[0,1\],\[0,2\],\[0,3\],\[1,2\]\] **Output:** -1 **Explanation:** There are not enough cables. **Constraints:** * `1 <= n <= 105` * `1 <= connections.length <= min(n * (n - 1) / 2, 105)` * `connections[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * There are no repeated connections. * No two computers are connected by more than one cable.
Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value.
Array,Hash Table
Easy
null
658
Hi gas welcome and welcome back to my channel so today our problem is find the closest element so what have you given us in this problem statement here we have given a sorted era from the arena is ok and two integer k and x have been given. And what we have to find is that A is the closest integer to It would be less than the absolute difference of B - absolute difference of B - Okay, so first let us understand this problem through the example, then we will see how we can solve it. Okay, so look here, what has to be done here, if you want to follow it, then let us look at the first example and first understand it. 1 2 3 4 5 Okay, this has been given to you, what have you given, then K-4 has been given, what have you given, then K-4 has been given, what have you given, then K-4 has been given, that is, we need four elements, we need closure elements of K, we have given another Do it, see whose is less, we will take that first, so here you will do your difference of X - A - 1 - here you will do your difference of X - A - 1 - - You will find the difference of 3, you will - You will find the difference of 3, you will - You will find the difference of 3, you will sign the difference of five minus three, see which one is less, here you will be tu, this will be van, this will be zero, this will be van, this will be tu, okay so here it will be less, this difference is less, then this is Okay, so now we have to choose the fourth element, do this, do that. Okay, so see which element is yours less. Here, there is one and here there is five, so you will do that to the one because you have been given that A &lt; B. It should be that you will given that A &lt; B. It should be that you will given that A &lt; B. It should be that you will select the element which is less in yours. Okay, so which of these two is less, van is less, then we will tweet this, then this is done, that is, you will run here and give 1 2 3 4, this answer will be your right now. What do we do, how will we solve it, we will see what we have given you in this problem, what is the rule of the problem, here we have given you fine classes, whenever you can think of a problem in a question, give it priority and hip to do it. To do it because whenever I have seen till now, if I have given all the most important questions, then it is sure that once you have given priority, you can try it, now you can try it there, to think in the direction. What is the priority of this because by doing this problem can be solved? I am not saying that it will happen 100% but 19 I am not saying that it will happen 100% but 19 I am not saying that it will happen 100% but 19 you will have 95% of the question as to you will have 95% of the question as to you will have 95% of the question as to when it has to be done with priority. Okay, why will we do that or what is the minimum difference? For closure, what should be the difference between element and So, in the case of equal, what will we do, we will make the elements which are less, ok, so what we are going to do here, firstly we will have to take care of our difference and secondly, we will have to take care of the elements also, we will have to take care of both. So the expectation of priority is that the element which we are going to insert will be in the form of a tree, one is our difference first because first is our difference party, okay when the difference is becoming equal to yours then in that condition you are seeing the element, so both of them If you insert then what have I done here, why did I take the max brightness here, what happens in it, the element which has the highest difference will be at the top, okay the one which has the highest difference will be at the top, okay after that if this difference can be If there is a combination of two elements, what will be its condition? The element which is highest will be on the top. Okay, why are we doing this so that we can remove it from there and the elements which remain with us, we will call the one with minimum as ours. Finally, what do we do with that? Insert it into one of our answer vectors and turn it into final. Okay, so we are doing that, so now we do follow. What will be the first one, what will be your difference? What is the difference of x - 1? What one, what will be your difference? What is the difference of x - 1? What one, what will be your difference? What is the difference of x - 1? What is your tu? Then what will be the element? What will be your van? Okay, after that what is the difference of your main tu? Van is and what will be the element is your tu. This is done. What is the fourth element? What is the difference and if there is four of the element then Look, the difference here is also van but the element is tu, so this 1/4 will be here, okay, is tu, so this 1/4 will be here, okay, is tu, so this 1/4 will be here, okay, this will be 14 here, now you see, now here you come near this element, you will see the difference of 5 - 3 is tu and This is five, will see the difference of 5 - 3 is tu and This is five, will see the difference of 5 - 3 is tu and This is five, okay when you come here, what is its size? It has become four. The cake is equal, so now we cannot insert more elements in it than the case, so can we remove its top element ? Can't do it, okay, what should ? Can't do it, okay, what should ? Can't do it, okay, what should we do for that, we will compare the difference of both, is this difference, is this more for you or is this less, what if it is less then look at what you need, we have to keep the minimum difference, okay last. The elements that are left in this party are the ones with minimum difference. It is okay. If it is the one with the difference, then the element with the least value will be the element with the least value. It will be okay because your A is yours. What is sorted, so the element which is already in this. It will be sure that it will be minimum, after that whatever elements you will come, if the difference is also equal, like in this case, what is the difference, your equal has been found, this is also your, then you are for this thing. Sir, you will be sure that what is already placed in it is sure that this element is less because it is sorted, right, you have started short it from here, you have started from the beginning, the sorted element must have been inserted first, so in this condition. What should we do? We will not insert it and we have got four elements. Okay, so what should we do? We will remove the second element and insert it because you will get 1423. We will get it on this basis, so what will we have to do with this also, we will have to sort it because I will sort the answer and explain it to you so that it becomes clear to you. See what you will do here. This will be your tu and the elements will be van, then what will be the difference here, it will be three, so you bring this here, bring this van, here, take three and here you will become okay, then what will happen to you here. The difference of 3 - 1 will be then what will happen to you here. The difference of 3 - 1 will be then what will happen to you here. The difference of 3 - 1 will be four, then what will be this, these elements three will be here, then what will be the difference of four minus one here, what will be yours, this will be four, then what will be your difference here, 5 - 1 - 1 will be six, then the difference of 6 here - 1 - 1 will be six, then the difference of 6 here - 1 - 1 will be six, then the difference of 6 here is six and elements 5, will you insert in it, what is retirement, what is it of four, okay, so the fourth and fifth will come in this direction here or not, I will have to decide first. We will see the difference. Hey, this difference is more. What is the fourth element, which is already the same for us? So what will we do? We will take out all of them, this will be our answer. We will take out the second element, this will be our answer. Okay, I hope you have understood. Let me also explain the code to you. Okay, see what we have to do in the court. Secondly, what about your element? Okay, now we will go through each element. Okay, what will we do? First of all, we will check the size of our priority. What if it is then look at what is the absolute difference of the elements which you are on, is its difference less than its top, what if it is less than the top, then what will we do, we will remove the elements from there, suppose look here that you would have that here. What elements do you get here, like this is five four here, okay and you get the difference, what is the difference, you get the element, what did you get, seven, something like this, suggest man, okay, so which one would you prefer, will you do this or will you do this? Because this will be too much closure, so we will remove it, pop it from here, and what will we do, then we will insert it, okay, this has to be done, so we have seen here, what is the priority, why is the first element at the top, what is it? Is the difference absolute Hey guys, what will be the size in this condition? It will be 3. Okay, so here you will put this condition that if the size of PK is greater than yours then it will be in the condition. If this condition is not fulfilled then this condition will come on this condition. What will happen to you when it is not fulfilled? Its difference will be greater. Look, if this condition is fulfilled then it has to be popped from here. Okay, if it is popped then your element will be reduced. If this has not happened, it means that this current element. If the difference is more, then in that condition, what will we do, we will continue, okay, we will continue, adar vice, what will we do, we will push the element, okay adervise, what will we do, we will push the element, then it is yours. Why have you prepared your priority? Okay, what elements have you got? Now what will you do until PK is your MP? What will you do by storing all the elements in the answer? PK is the second element of the top and PK is the second of the top. What will you do with the element, store it in this answer vector and keep popping people and picks, that is, what we do is, we will come out from here, insert it, then insert it here, come out, set it, pop it, come out from here, set it, turn it off here. We will take it out, we will set it, we will pop it in the van, okay, you will get it. If you liked the video, please like, share and subscribe. Thank you.
Find K Closest Elements
find-k-closest-elements
Given a **sorted** integer array `arr`, two integers `k` and `x`, return the `k` closest integers to `x` in the array. The result should also be sorted in ascending order. An integer `a` is closer to `x` than an integer `b` if: * `|a - x| < |b - x|`, or * `|a - x| == |b - x|` and `a < b` **Example 1:** **Input:** arr = \[1,2,3,4,5\], k = 4, x = 3 **Output:** \[1,2,3,4\] **Example 2:** **Input:** arr = \[1,2,3,4,5\], k = 4, x = -1 **Output:** \[1,2,3,4\] **Constraints:** * `1 <= k <= arr.length` * `1 <= arr.length <= 104` * `arr` is sorted in **ascending** order. * `-104 <= arr[i], x <= 104`
null
Array,Two Pointers,Binary Search,Sorting,Heap (Priority Queue)
Medium
374,375,719
1,921
friends uh welcome to follow up let's have a look at problem 1921 eliminate maximum number of moners this problem is yesterday's Daily challenge problem we are going to explain a solution based on the following strategy so we are going to count how many monsters we can eliminate from the interval this is a left close and right open interval so from the current running time to the nearest Mon a time and then we're going to do the submission so our plan will be the following first we are going to adjust the problem requirements and then we look at the logic and finally we share the code so this problem is tricky in the sense that we need to count the time besides the number of monsters we can eliminate so with that said let's look at the problem requirement so here we are playing a video game where we are defending our city from a group of n moners so we are given a zero index integ array called distance of size M where distance I is the initial distance in kilometers of the ice monster from the city and the Monsters walk towards the city at a given constant speed the speed of each monster is given in an integ AR called speed of the same sides where speed I is the speed of the ice monster in kilo uh kilometers per minutes so we have a weapon that once fully charged we can eliminate a single Monster in each minutes right however the weapon take one minutes to charge so the weapon is fully charged at the very start so we will lose when any monster reaches our c City if a monster reaches the city at the exact moment the weapon is fully charged it also counts as a loss and the game ends before we can use our weapon so we want to find the maximum number of monsters that we can eliminate before we lose or just the end if we can eliminate all the monsters before we reach uh they reach our city so actually this in is sort of dummy because that we just need to use just need to uh count how many monsters we can um we can eliminate right so for sure the number would be less than or equal to n because we have in total n moners so here are three examples so uh we're going to look at um the first one first so here the speed are the same right both a one so monster one will arrive at minute one and the monster um with uh distance three will arrive in minute three and four will remain at minute four right so we can first at Time Zero we eliminate the one who will arrive at minute one so then at minute two we eliminate the second monster and the minute three we can eliminate to the third monster so in total we returns three this is also the length of this um uh also the total number of moners so in example two I guess the uh the purpose of this example is to show at the same uh time there multiple monsters can arrive for example at minute one so two monsters with distance one can arrive but we can only elimin to one and then we lost the game so we return one in this example uh in the second example or in third example which basically tells us that we need to consider the speed as distance together for example in the first two monsters with distance two H three and two so there are speed of five and three So within that minute on both can arrive so we can only elimin one so that's why we return one for this one and then the monster with distance four arrive at minute two but at that time we have already lost the game so with that said let's also look at the constraints um first n is bonded below by one so in other words we have at least one master and then it's bonded above by 10^ 5 so 10 the power five is a above by 10^ 5 so 10 the power five is a above by 10^ 5 so 10 the power five is a decent large number so for such large number we cannot use the in square um time comp the algorithm right so the distance and speed has element have elements in between 1 and 10^ 5 so with elements in between 1 and 10^ 5 so with elements in between 1 and 10^ 5 so with that stage basically uh we can look at the logic so here I give uh the walk through for three examples so the first one is a general example so here I have a distance this like this and speed is one and four so this is also a test case so in this test case we're going to return three right so the reason is that overall we need to consider um the Aral times right for this example you know so because the for um there are three so this three monsters will arrive at minute three so in other words we have three at Min three we have three monsters arve and then for the last monster with distance four it because it has a speed four so it will arrive at minute one so at minute one there will be one monster arrive so for the first monster with a distance four it takes 4 minutes for it to arrive so it arrives at minute 4 or it will arrive at minute 4 so the logic will be the following so at the current time t equal zero right so uh this time so we can U kill or eliminate the um the only monster who will arrive at minute one right so we eliminate this one and then 10 becomes one right then and current time one so then we are going to consider time three so in time three there will be three monsters to come but because the difference of time is uh T is one and the AR of time is three so we could kill two of the three right so we uh the temp will becomes three so in this case so uh we will have mon kill monsters three right and uh another monster will arve and same time so the game ends in other words at time T we killed or eliminated three monsters and the game ends so this three is also the return for this example I guess this example is very representative so um this is the first one now if you look at um the first example so you have one three four so the arriv time is at time one there will be V moner and time three there will be V masterer and at time four there be V monster so at time zero so we can eliminate the monster to AR at time one so the result will incremented by this one and T becomes one then at time T equals 1 so we can eliminate the monster to arrive at next Aral time that is three right then result becomes two by increment this one and T becomes two then at time tal 2 so we can eliminate the monster to arrive at time four right so in this case the result is three and T becomes three and then all the monsters are eliminated so we return three for this example so this is the more targeted analysis so if you look at example three so here we have 324 and 532 so this example basically tells that we need to consider the setting operator when we compute the time to Aral and for example uh the distance is three and speed is five so time taking is 3 over five but we count 1 minute right for this in this context so the AR time will be the following so the first two monsters will arve at time one right and the third monster will arrive at time two therefore and tal Z so we can kill one out of the two monsters to arrive then the result will be one and two will be one but another monster will have arrived so we return the current result state that is uh one so with that said basically uh we know the logic will be following right so uh we can't uh we check a Ral time uh for from uh early to later right or from small to large in other words we need to sort this R HS and then uh we check T and uh count how many uh Monsters uh we can eliminate right so we're going to specify how we make this comparison right so with that said I hope that you have digust the problem requirement I guess it's always worthy to of doing such digest so that you can R code more uh clearly so with that said let's look at the coding part so if you have grasped the logic so writing the code is actually a breid so first I want to get the oral TS so I just call it times then basically for distance let's call it s and speed let's call it wi so as in physics right so distance and speed so here I'm using the zip function right to um make two po out of the two and then I want to compute the r time so that will be Mass so I'm going to use SE operation so s over way right so why we use the S uh the setting operator you can look at it example three for example so now we want to update this one so times T so we want to count how many monsters arrive at time T so that is times get so let's check if T is in the dictionary or not if not we set it to be zero then we can't increment by one and then we want to sort the orable TS so that's call it arbl we sort it U case right so this way we are going to uh sort the temp from small to large then we are so our current temp is t equal Z notice that at t equal Z we can kill one at least right so the result will be the number of monsters we can eliminate so now we just need to iterate over the AR HS let's call arrival in arrivals so now let's see uh how many Monsters uh will arrive at this time so times arrival so notice that current our time is T right so if for example just add time T = 3 you have three monsters to time T = 3 you have three monsters to time T = 3 you have three monsters to arrive so that's okay right because at tal Z you can kill one and tal 2 you can Q one and tal uh three you can Q one right actually the number of monsters let's say we have a 10 we have an N monsters so the number of monsters um number of uh Monsters uh we can eliminate is so you can do the counting right say tal 0 and T = 1 and tal 2 up right say tal 0 and T = 1 and tal 2 up right say tal 0 and T = 1 and tal 2 up to um 10 minus one right so you count this will be 10 minus one minus 0 + this will be 10 minus one minus 0 + this will be 10 minus one minus 0 + one that is time minus t anyway because T is zero so this is the monster we can kill if the monsters the end monsters is larger than this uh count then we will lose the game right so now with that digested let's look at the counting so can um kill or can eliminate so let's me write eliminate that is aable time minus t so actually this is computed by this t + actually this is computed by this t + actually this is computed by this t + 1 up to arable time minus one so it's Aral minus one minus t then you count this one itself that is Aral plus T not plus T minus t right so this is the moners we can eliminate right so um if in musters is logic and is less than the can eliminate and then we can increment the result by n monsters so we can kill all these monsters ahead of time then T becomes um increment also by this amount right because each minute we C we elimin one so otherwise so we just need to return result the current state plus the monsters we can um kill right that is we can kill this amount but the other monsters we arrive right we lose the game that's why we return so overall we just need to return three dot right so we don't care about directly return and in like here so as long as after this for Loop there's nothing returned so we just return the result stage that's result stage will be the number of uh monsters given or the length of the dist or speed so with that said I guess we're ready to do a test yeah it passes one example now let's look at generic case uh canq is not defined so here I think I use can eliminate so now let's check that yeah let's check again yeah it passes all the cases so that's basically about it for this problem so um let me give a quick summary I guess for this kind of problem because uh we need to count both the T and the arrivals arrival T and as the number of monsters arrived at that time so here we need to be clear that um we that we need to be clear that which that just the problem inserting Precision so um as for temp complexity it's very easy to uh to analyze so for example this part four and this is the O of n right and then uh in general we do the S is um M log M algorithm so here m is a number of different keys right but this m is bonded by the length of this T So this Loop is O of n let me use Big O so this is also so big O basically means up to a constant right so for this one this is also this for Loop is also linear so o of M so it's the number of um uh you different case right then you can get the complexity easily so with that said I guess that's it for this video um thank you
Eliminate Maximum Number of Monsters
eliminate-maximum-number-of-monsters
You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city. The monsters walk toward the city at a **constant** speed. The speed of each monster is given to you in an integer array `speed` of size `n`, where `speed[i]` is the speed of the `ith` monster in kilometers per minute. You have a weapon that, once fully charged, can eliminate a **single** monster. However, the weapon takes **one minute** to charge.The weapon is fully charged at the very start. You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a **loss**, and the game ends before you can use your weapon. Return _the **maximum** number of monsters that you can eliminate before you lose, or_ `n` _if you can eliminate all the monsters before they reach the city._ **Example 1:** **Input:** dist = \[1,3,4\], speed = \[1,1,1\] **Output:** 3 **Explanation:** In the beginning, the distances of the monsters are \[1,3,4\]. You eliminate the first monster. After a minute, the distances of the monsters are \[X,2,3\]. You eliminate the second monster. After a minute, the distances of the monsters are \[X,X,2\]. You eliminate the thrid monster. All 3 monsters can be eliminated. **Example 2:** **Input:** dist = \[1,1,2,3\], speed = \[1,1,1,1\] **Output:** 1 **Explanation:** In the beginning, the distances of the monsters are \[1,1,2,3\]. You eliminate the first monster. After a minute, the distances of the monsters are \[X,0,1,2\], so you lose. You can only eliminate 1 monster. **Example 3:** **Input:** dist = \[3,2,4\], speed = \[5,3,2\] **Output:** 1 **Explanation:** In the beginning, the distances of the monsters are \[3,2,4\]. You eliminate the first monster. After a minute, the distances of the monsters are \[X,0,2\], so you lose. You can only eliminate 1 monster. **Constraints:** * `n == dist.length == speed.length` * `1 <= n <= 105` * `1 <= dist[i], speed[i] <= 105`
null
null
Medium
null
32
hello everyone let's take a look at lethal 32 longest valley parenthesis it's a very good problem and it can be solved by multiple solutions for example we can solve it for dynamic programming or we can solve it by stack okay let's take a look at this problem so the problem is given string containing just the characters the open bracket and the closed bracket when you find the length of the longest valid parenthesis substring for example in the example one the longest is two in this example's longest is four in the last example is zero okay let's go straight to the solution first we can use dynamic programming dpi means longest valued parenthesis and the index i so the result is the maximum of all the dp elements okay let's um start with the framework so we have a dp vector and we maintain our results finally with retentive results and we need to for each every character and in each iteration we update the results so this is the basic framework let's say how can we calculate each dpi in this box okay so for each character we only care about the closing bracket right since if it's open bracket if the string ending open practice then it must be invalid okay now for each um closing bracket there are two cases like um for current i if it's an open bracket then we uh take a look at i minus one zero two case one is open bracket one is uh closing bracket so first we talk about open bracket what if it's an open bracket then we know it's a closing bracket so it's itself is a valid parenthesis then we take a look at i minus one so in this case i minus 1 we know the value is 2 so 2 can add the like 2 can add another 2 here since currently we create a new valid parenthesis which has length two so dpi is two plus dpi minus two okay what if dpi minus one gets a closing bracket let's say in this case when dp one is two and uh dp4 is two we need to calculate dp5 assuming is at f5 like how can we calculate it so to calculate dpi first we know that dpi minus is 2 and we have index which is i minus dpi minus 1 and -1 minus 1 and -1 minus 1 and -1 so this is our index if db index is open bracket then we know this is open bracket this is closing bracket so they create a valid parenthesis right so we have a valid parenthesis here and we need to take a look at dp index i minus 1 if the secant also contributes the length to our valid parentheses so in this case as long as index is not a negative number and s index is a open bracket then we note that this dpi is two plus where is 62 c2 is the closing okay and it's an open bracket plus dpi minus 1 was dpi minus 1 dpi minus 662 so these characters inside the new open closing bracket and the plus our dp index minus one so for the previously valid string you can like concatenate and combine the and generate a longer like substring right so this is dpi okay this is a dp solution let's take a look at another solution using stack the first we create the framework we have stack and we push negative one first and later you will see how this negative one works and we have a result we will maintain results in this hidden box and will result and return the result okay as usual we iterate every character in this input first index is serial and its open bracket then we push 0 to our stack next is closing bracket which match the top element in this stack so we pop the stack we up this result is on i minus stack dot top so which is one minus negative one so it's two here okay next we're at index two it's open bracket then we push it to stack next open bracket push it to stack next it's closing stack closing bracket which matches top element in stack so we pop the stack and we update this result which is also two next index at five is also closing bracket which also match the top element so we'll pop the stack and we update results so now result is five minus negative one which is six so which is our answer we get the correct answer let's see how to implement so we get the uh top element instead as long as it's a match so is a great closing bracket and the top element is open bracket then it's a match so we probably stack and update our results otherwise we just purchase the stack so compared to the dp solution and the stack solution seems a bit cleaner and a bit maybe better but there are also good solutions here since and the time complex he so take on okay that's the problem see you next time
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
957
hi everyone my name is Steve today we're going to go through a legal problem 957 prison cells after n days let's take a look at the problem first there are eight prison cells in a row so it's a definite number and each cell is either occupied or vacant how do we denote occupied or vacant it says so here it says we describe the current state of the prison in the following way if a cell value is 1 that means this cell is occupied otherwise if it's 0 this cell is vacant basically this is a binary array the value is either 0 or 1 let's take a look at the rules how the cells are supposed to change each day whether the cells whether the cell is occupied or vacant changes according to the following rules two rows one is if a cell that has adjacent neighbors that are both occupied or both vacant then the cell becomes occupied otherwise it becomes vacant note that because the prison is a row the first and the last cells in the row can't have two adjacent neighbors which means is guarantee than the first and the last cell in the row should always and end up in vacant which is zero let's take a look at the example the last day the first one in the last cell it's always as otherwise it's incorrect right so the problem is asking us given the initial state of the prison written the state of the prison after n days and n such changes described above as ticular had the first example on the first the cell is given like this 0 1 and this salmon which means after seven days it's asking us to output the correct status of the prison let's take look the correct output is this and how we got to this there are a total of seven snaps so we need to go through we only need to go through a couple of days today zero is the given state like this one exactly like this one and then day one is going to change following these two rules if the two neighbors aren't occupied and then this one becomes occupied all if the two neighbors are vacant then this cell becomes occupied as well otherwise it becomes vacant so let's take a look at day one the first cell is always going to be 0 it doesn't have two neighbors some regardless of the one sided neighbor so let's start from the second one is this it does have two neighbors and both neighbors are vacant meaning they have the same value so this one is still occupied then let's take a look at this one it does have two occupied neighbors so this one should become one and this one it has one is occupied and one is occupying the other is vacant so this one becomes zero vacant and then this one it also becomes vacant because one side is occupied the other side is vacant how about this one becomes vacant as well because it's an its unequal on both sides of this one how about this one becomes zero as well because this one is occupied and this one is not and the last one is in last sale so it doesn't have to your neighbor so it becomes zero so this is how it changed after day one continue to do this until N equals seven to the seventh day then that's the final result that we're going to output this is how this program is supposed to run and then let's take a look at add the notes for all the prerequisites for this problem which says there's a total of a definite number of cells there are a total of 8 cells in this row and each cell is binary is even 0 or 1 but then to pay attention to this and it can go to this bit which means if we use the brute force a most straightforward way we might end up in time limit exceeded exception because is it possible that we have redundant repetitive computation right is it possible let's take a look at one example suppose we are given this cell on day one this cell looks like this a total of 8 cells and on day 1 only the first and last is unoccupied and the rest from the first to the sixth all of these six in the middle cells they are all occupied let's just a suppose n is infinite safe and is 199 let's go through a couple of you of them first on day one how it's going to change like this cell is going to become 0 that is because its neighbors are not equal 1 is 0 the other is one right so is this one changed from one to zero because it's two neighbors are not evil okay this is day one day two it continues to change this one becomes zero for the same reason day three this one becomes one that is because both of its neighbors are equal now so this one becomes one and for the same reason this one becomes one but for these two they both become zero because its neighbors are not equal okay that's clear now let's take a look at day 4 is continued it's going to continue to shift and this time this one this cell becomes 1 that is because both of its neighbors equal and this one becomes 1 as well that's for the same reason now day 5 on day 5 this one becomes 2 1 that is because it's neighbors are equal and this one becomes 1 that is because its neighbors n equal and these two ones become zeros that's because both of their neighbors are not equal alright let's continue changing so far we don't see any repetition we don't see any patterns right all of these first 5 days all of them are still unique let's move on day 6 and this one becomes 0 this one doesn't change this 0 doesn't change this these 2 ones become zeros for the reasons that we described above now moving on still we haven't seen any repetitive patterns yet moving on day 7 least all of these from the first to the sixth all of these six ones in the middle have all become to one that is because all of their neighbors are the same value they are all vacant or 0 rooms right so notice is there any pattern have we run into any cycles is there yes there is this one is exactly the same as the initial given state sounds like we might be entering a cycle if you're not sure let's move up so for day eight we are getting this that is because we are following the same rule and this state becomes the initial state so of course the next day is going to be the day eight is going to be exactly the same as day one right moving on day nine is going to be exactly the same as they do day ten is going to be exactly the same as day three so you see the difference is seven right so we can continually move on until like how many days but it's a cycle it's a psycho it continues to repeat itself so we can move on all of these to day 14 is going to be exactly the same as day 7 as we can see so the time it takes to finish a cycle is seven which means for any n if this n is greater than seven then we only need to compute n modulo 7 I hope that makes sense because after we exceed the number of days equal to seven it's going to repeat itself then we can just cut a shot we don't need to all of these we don't need to go through all of those repetitive computation I hope that makes sense if n equals to 8 then we can do it only once right because the seventh days is going to be meaningless we don't need to calculate those seven days because it's a cycle there right the same goes for if n equals to 99 we can cut all of those repetitive computation out it's going to be exactly the same as N equals to 1 or n equals to 8 we'll just do the modular function this is going to help us a lot especially when n is extremely big the end could go as big as 10 to the magnitude of 9 that's a huge number of course it's going to save us a lot of repetitive computation along the way that's the idea those triphala it might not be the most optimal I'm sure they are more optimal ways to do this but this is one way to get this code accepted and I in my mind is pretty straightforward now let's put the algorithm into the actual code so how do we do that first we want to how can we detect if there is a cycle we want you have a hash set to do to store all of the states in differ days so in that case we can use we can initialize a hash set of type string I just call it set for simplicity new hash set again this set is used for us to store the different states for each day to see if there is a cycle then we need another variable called bullying or just call it a hand cycle first what default to be forced next we'll say how many days does it take before we can detect a mirror cycle so we'll just call it the days initialize to be 0 and then we just go through n we don't know if there's a cycle or not this n could be seven could be 14 there's the number of days it's going to take before we can detect a cycle could be 7 could be 14 right so we don't know so in the first in the beginning we're going to start from 0 and go all the way up to in start from 0 up to n at this point we can calculate the neck the states for the next day we're just quite next which is quite next for the concise if deserve Dakota or maybe you use another function let's just quite get next let me implement here private and get next in ourselves so this is the key here this is one of the key functions that were going to need we'll just call this next the next day length is going to be exactly the same as the killing one and how we're going to implement this is sales if I press plus if I equals to 0 or I equals to sales lands minus 1 then in this case next is guaranteed to be 0 because it has only one neighbors right otherwise was use next should be well check if the two neighbors on the current cell that we are iterating on which means minus one equals two cells I've just won one of these two neighbors are equal regardless whether they are occupied or vacant whether they are zero or why it doesn't matter as long as they are equal this current cell we're integrating on should become occupied all right otherwise it's going to be vacant which is zero and then in the end we're just going to return next this is the helper function that we need you're right just to make the code more concise next we can call it a string to put an easier way to change a simple integer array into a string which is like this arrays to strain in different languages there are multiple different ways but in jail and I think this is this really a pretty straightforward way saying here we check if the set this hash that contains that this state that we currently generated for the next day whether we have visit whether we have generated this state already let's see if it first if it doesn't have it then what can just a happily but this string into this hash set and then we'll also increment days by one which means the work and we it's going to take us one more day before we can reach before we can detect a cycle if there is one otherwise what we are going to do is that will put a psycho to be two and then we're going to break up because we detected a cycle there's no point moving forward it's going to cost us more time right so after that what we'll do is we'll change well we'll assign the newly calculated state for the next day to be the new date so that we can continue to get rid on getting out of this followed what we want to do is it's possible that this end is very small like smaller than seven or smaller than fourteen that this has psycho is still forced in that case we can just return sales that's it right but just in case if there is a cycle the end is very big and there's a psycho in there has psycho if that is the case well we're only going to run through and modular the number of days this and we are going to change it in place change this end to be a much smaller number all of these full cycles we don't need to run through anymore I hope that makes sense at this point we can have another folio you can have when you wire loop as well as long as it serves this purpose so here what we can just do sales and get next sales until we traversed through up to n this n is the number of days that we have to go the minimum number of days that we have to go through without running into cycles that's it for this algorithm I think this is going to work let's try to run the code first see if there's any syntax error there is one of ourselves not sale run again alright accept it let me hit submit alright accept it 36% not super optimal alright accept it 36% not super optimal alright accept it 36% not super optimal but at least this is something that varies that's very straightforward to help people understand this problem and how this works this problem is very similar to the one that we went through last time caught game of life it's just a there is some variation between this one and that one I hope this video helps people understand this problem if that's the case just do me a favor and quickly destroy the like button that's going to help a lot with the YouTube algorithm and I really appreciate it or so don't forget to hit the subscribe button as we continue to go through a lot of interesting interview or leave code problems and if you have any questions comments just leave me down in the comment section below I really appreciate your time see you guys in the next one
Prison Cells After N Days
minimum-add-to-make-parentheses-valid
There are `8` prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: * If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. * Otherwise, it becomes vacant. **Note** that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors. You are given an integer array `cells` where `cells[i] == 1` if the `ith` cell is occupied and `cells[i] == 0` if the `ith` cell is vacant, and you are given an integer `n`. Return the state of the prison after `n` days (i.e., `n` such changes described above). **Example 1:** **Input:** cells = \[0,1,0,1,1,0,0,1\], n = 7 **Output:** \[0,0,1,1,0,0,0,0\] **Explanation:** The following table summarizes the state of the prison on each day: Day 0: \[0, 1, 0, 1, 1, 0, 0, 1\] Day 1: \[0, 1, 1, 0, 0, 0, 0, 0\] Day 2: \[0, 0, 0, 0, 1, 1, 1, 0\] Day 3: \[0, 1, 1, 0, 0, 1, 0, 0\] Day 4: \[0, 0, 0, 0, 0, 1, 0, 0\] Day 5: \[0, 1, 1, 1, 0, 1, 0, 0\] Day 6: \[0, 0, 1, 0, 1, 1, 0, 0\] Day 7: \[0, 0, 1, 1, 0, 0, 0, 0\] **Example 2:** **Input:** cells = \[1,0,0,1,0,0,1,0\], n = 1000000000 **Output:** \[0,0,1,1,1,1,1,0\] **Constraints:** * `cells.length == 8` * `cells[i]` is either `0` or `1`. * `1 <= n <= 109`
null
String,Stack,Greedy
Medium
2095
95
hey everybody this is Larry this is day five of the Lego August daily challenge when it loads anyway uh hit the like button hit the Subscribe button join me on Discord let me know what you think about today's problem why is my internet slow is it my computer all this money all this technology and it's just having fun being slow what is running in my background all right in any case um I'm gonna keep this first quit some stuff uh today's problem is 95 unique binary search Trees Too give me the energy and return all a structured unique psts binary search trees uh it's kind of funny that they uh they only use This Acronym acronym once and they defined it so actually using This Acronym makes the problem statement longer but it's not an important detail but it is true uh they didn't even use it in the uh title anyway which has exactly and know some unique rise on one to end return the answer in any order um yeah I mean I think this is a pretty straightforward in a way um you know this is recursion I guess we've been doing recursion all week of it this is a very uh I mean if you've been on my channel enough times and apparently you know I this is one of my favorite sequences back in the day uh and apparently it is also one of leeco's favorite sequences of the day which is the Canada and sequence of course in this particular problem you have to do more than um you have to do more than just generate a number of uh trees you have to actually generate the trees but the reason why this is a very common uh number or sequence is because it is a very simple to Define sequence of uh divide and conquer recursively right the idea is that okay well look yeah so let's kind of do that basically the idea is that okay give an n uh let's just say construct right how do you want to say it uh basically we will start from uh let's say lower upper I don't know left right I usually go left right just because in my mind I a lower right is by the worst uh but yeah maybe slightly better this time and of course this is basically uh um return or trees um with the numbers between low and upper inclusively right there are actually a couple of ways you could have and you can actually think about this um you may not need to do it this way because you can also think of it as um just a number of lower or upper minus lower plus one number of nodes and maybe like the color kind of some math there um it doesn't really matter to be frank uh I mean like you know there are a couple of ways to do this is what I'm saying um I think right now I'm just uh like you know like any given day I might want to do something really different so I don't know but anyway if lower is you go to Upper then we only have one node right so then we can return it uh as you say we return a list of one node of uh y u is equal to lower right and that's it otherwise then we Brute Force the top node or the root of this new tree so then now for x and range of lower to Upper plus one inclusively uh or well I'm exclusively so that's how we get low and upper inclusively so now X is the current node right so uh and we also want to return an array right so uh yeah so then now we have two set of things right we have the left note which is construct lower to x minus one and then we have the right uh sub tree so that's you know X plus one upper and maybe we'll actually do something we'll I mean in theory you can also add an if statement here just to make sure that it's within bounds but maybe it's just a little bit easier if yeah wait hmm yeah if you do something like this return to the video but then maybe I'm like off by one somewhere because then now you do a Cartesian product against um an empty list is going to be sad times but maybe that's fine maybe that's just part of this way awkward though actually like do we want to return this would that like messes up oh well I guess let's stick with this uh and then we'll see how it uh comes back to haunt me later but okay so then now it's just basically for I don't know a variable name in love for um yeah again this is quotation product right so then now we basically entered that a pen oops uh what am I doing uh tree node where the value is equal to x uh left is equal to l y is equal to R and I think we should be good uh I mean there's only eight possibilities so we might as well just uh you know put them out and it looks good running time is good so we're good so let's get a submit uh yeah so there are a couple of things right um so what is the advantage of this versus the other uh what I said about during construction where you're just given construct given end nodes right well given end notes then you're able to actually do memorization because now you can reuse it and then just like do some numbers there um in theory anyway at least in terms of um creating the structure of it the thing is that you're doing very close to the bung anyway so and what I mean by that is that your output is going to be very close to your lower bound uh or the lower back or the output is the lower bound but you're doing your complexity is very close to your lower bound then it you know uh you don't gain that much there because you still have to copy it for this particular problem you have to copy the memory over to recreate anyway because for example if you because the idea there is that okay let's say the left has three nodes the right has four nodes but then now you have to renumber all the nodes on the right and as well as create additional memory for them right so you still have to kind of create new things anyway um these are things that I think about like immediately but I guess I didn't really talk about it until now right um yeah I mean I think that's really the biggest thing um you do get memorization and you do get like that structure and of course if you if all you have to do is return account then that would be way easier because then you don't have to deal with all this memory stuff but for this one it makes this slightly cleaner to write even though yeah I don't know uh the none part is a little bit awkward for sure because we set it to none in that way um and I don't know because I think it technically would maybe fail for if n is equal to zero which is not part of the input because then in theory we will just return an array with one element of with that element being none versus just an empty away but you know I don't know it is what it is maybe because special case it even if there was an N is equal to zero uh and I've been kind of a little bit sloppy I mean today was intentional but I have been a little bit sloppy doing contests lately so I don't know how I feel about it um yeah I think that's all I have with this one let me know what you think like uh this is recursion that is very big uh oh I mean it's not very basic obviously but it is one step remove from way basic this is just the right and Conquer uh yeah I guess so yeah so definitely you know it comes into play in a couple in a number of ways right so definitely be familiar uh and yeah let me know what you think stay good stay healthy to your mental health I'll see you all later and take care bye
Unique Binary Search Trees II
unique-binary-search-trees-ii
Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**. **Example 1:** **Input:** n = 3 **Output:** \[\[1,null,2,null,3\],\[1,null,3,2\],\[2,1,3\],\[3,1,null,null,2\],\[3,2,null,1\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 8`
null
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
Medium
96,241
283
chances are that you have already found a solution that works in an order of n time complexity and now you're struggling to find a solution that is space efficient as well i am talking about the problem move0s or lead code this is one of the classic problems where you realize that to enhance your problem solving skills and to become a better developer you need to think about space efficient solutions as well i will show you step by step how you can approach this problem and trust me you will be surprised yourselves how simple the solution is hello friends welcome back to my channel a place where we explore the life of technology and make programming fun and easy to learn first i will explain you the problem statement and we will see some sample test cases next we will look at the most straightforward approach that you can solve this problem and then we will try to optimize it we will find an efficient solution to the problem and then also do a dry run of the code so that you understand how all of this works this way it will stick in your mind forever so without further ado let's get started okay so let us first try to make sure that we are understanding the problem statement correctly you are given an array of integers and you have to move all the zeros to the end while maintaining the relative order of the other elements now what does that mean let us try to understand it with a sample test case so you are given an array of integers and you have to move all the zeros to the end so you can see that this array has two zeros right when you are moving these zeros to the end that means that i am moving both of these zeros over here but there is additional part to the problem you have to maintain the relative order of all the other elements the relative order means that in the final array these elements should appear in the same order that means 1 should come first then 3 and then 12. so for test case number 1 this would be your answer you can see that all the zeros have moved to the end and the relative order of the remaining elements remains the same similarly look at test case number two you have a smaller array with these three elements to write the answer for this first of all move both the zeros to the end and then you only have one element remaining right so you can just write it down over here so for this test case this will be your answer now if the problem statement is clear to you feel free to try it out on your own otherwise let us see how we can approach this problem so let's say i have the sample array in front of me and once again i need to segregate the zeros and all the other elements what is the first thing that comes to your mind what is the most straightforward way one thing that could come in your mind is that okay i will separate all the zeros in a different array and all the elements in a different array and then i can combine them right so how will you go about doing that you will start from the beginning you see a 0 and you will add it in your other array if you see a number that is not 0 you add it in a different array you see a 5 so if i add 5 over here then you see a zero again so you add it over here so this way what will happen is your relative order remains the same and you have all the zeros over here now you can just combine both these arrays and you will get your final output correct now this is a time efficient method that means that you are only taking up order of n time but this method is not space efficient you have to take extra space to store this array and then you have to take extra space to store this array hence this is not a space efficient solution we need to find a way that we can optimize the space that we are using what can we do about it you are really gonna be amazed how simple the solution is so let us say i have the sample array and you have to separate all the non-zero numbers and the zeros right non-zero numbers and the zeros right non-zero numbers and the zeros right so think about it you don't need to do anything about the zeros right you are only concerned about the relative order of the non-zero elements relative order of the non-zero elements relative order of the non-zero elements so the most simple way to approach this problem will be that you start iterating from the beginning and if you see a zero just ignore it but if you see any element that is not zero for example if you see element number 1 just start moving every non-zero element just start moving every non-zero element just start moving every non-zero element to the beginning so what i will do is i will move this 1 at my index 0. so now my array becomes this correct now move ahead you see a 5 so now move this 5 to the next place so this 5 will eventually come over here and this is the current state of my array now keep moving ahead you see a 0 so don't do anything next you see a 12. so move this 12 to the next position that is available this 12 will come over here and this array now changes don't worry about the remaining elements just keep advancing through your array next you see a zero so don't do anything next when you move ahead you see number nine and what you will do is you will move nine to the next available position in your array so your array now looks like this okay so now you have traversed the entire array right and what does this mean this means that all the remaining elements should just be replaced with 0 right so what i can simply do is i can replace all these remaining elements with 0. and wow you just arrived at the solution right all the zeros have moved towards the end and you are still maintaining the relative order of the initial elements and that too in place in the array itself so this is a space efficient solution you just took advantage of the fact that there is no relative order of 0s right you can add as many number of zeros as you like but you just needed to maintain the relative order of the non-zero elements relative order of the non-zero elements relative order of the non-zero elements now let us quickly see how you can do a dry run of the code on the left side of your screen you have the actual code to implement this solution and on the right i have a sample array and we will try to perform our operations on this array is passed in as an input parameter to the function move zeros oh and by the way this complete code and the test cases are also available in my github profile you can find the link in the description below so starting ahead what do we start with the first position and that is the first place that you have to insert an element right so the insert position is 0 right now next what we do is we start a for loop and we will fill all the non-zero and we will fill all the non-zero and we will fill all the non-zero numbers so what we do in this for loop is we start from 0 and go all the way towards the end and we fill all the non-zero numbers and we fill all the non-zero numbers and we fill all the non-zero numbers that means as soon as we find one what we will do is we will insert it at the inferred position so eventually this 1 will go over here then 3 will go at the next position and 12 will go at the next position what we do is for any number that is non-zero non-zero non-zero we insert the number at the correct place and then increment the insert position counter so after one iteration the insert position will change to one and then ultimately two because you will have inserted 1 over here then 3 over here and then 12 over here right so you have maintained the relative order the next part is just filling out the remaining zeros and that is what we exactly do in the next while loop we start from the insert position and go all the way up to the end and we will just add a zero over there so when this while loop runs i will add a 0 at the next position and 0 at the very end so you see we have arrived at our answer the time complexity of this solution is order of n that is because we iterate through the array only once and the space complexity of this solution is order of one that is because we do not take any extra space to arrive at a solution i hope i was able to simplify the problem and its solution for you as per my final thoughts take a moment and look back at the solution we just came up with most likely when you read this problem you might be thinking about swapping elements taking an additional array storing these elements somewhere right but when you look at the solution you will realize that it was so easy to solve right that is why it is always a good idea to draft out some sample test cases and work them out yourself come up with every idea that you can think of sometimes even the most stupid idea can lead you to an efficient solution what other methods did you try to solve this problem what innovative waves did you come up with did you face any problems tell me everything in the comments section below and i would love to discuss all of them with you would be also glad to know that a text based explanation to this content is available on the website a pretty handy website to help you out with your programming needs you can find the link in the description below as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where i can simplify programming for you also let me know what problem do you want me to solve next or rather what do you want to learn next until then see ya
Move Zeroes
move-zeroes
Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. **Note** that you must do this in-place without making a copy of the array. **Example 1:** **Input:** nums = \[0,1,0,3,12\] **Output:** \[1,3,12,0,0\] **Example 2:** **Input:** nums = \[0\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 104` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Could you minimize the total number of operations done?
In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.
Array,Two Pointers
Easy
27
300
hello friends my name is Tushar and today we are going to discuss a question longest increasing subsequence length what does this mean it means that given a sequence find the longest subsequence such that all the elements in the subsequence are in the sorted order so for this example our longest increasing subsequence is minus 1 0 2 &amp; 3 so the subsequence is minus 1 0 2 &amp; 3 so the subsequence is minus 1 0 2 &amp; 3 so the length is 4 for this example the longest increasing subsequence will be 2 5 &amp; 8 increasing subsequence will be 2 5 &amp; 8 increasing subsequence will be 2 5 &amp; 8 so the length will be 3 so how do we solve it yes we will have to use johnnyo programming to solve this problem let's try to solve this particular example so we start with a temporary array of the same size as the original array okay so now what if you know about the longest increasing subsequence for every element you all you can clearly say that at least the longest increasing subsequence is of length one at every position so let's fill this one with one initially okay so now let's have I start from the first position IV a disposition and J is at index zero okay if element and if element at J is less than element at I that means that the longest increasing subsequence at hi the at least be the longest increasing subsequence a J plus 1 so this becomes 2 okay now as soon as J which as I release it and we make I plus 1 and J again starts from 0 if a limited J is less than I which is not in this case we do nothing we increase G by 1 again element at J is not less than I so we do nothing and reset I to 3 and J again to 0 element IJ is again not less than I so we do nothing here also a limited J will not do less than I so we come here eliminate J is less than element at high so what that means is the longest increasing subsequence at are with at least be the longest increasing subsequence at J plus 1 so let's make this guy too and then we have I here and J again starts wrong 0 eliminate J is less than element at I so the longest increasing subsequence will be at six will be at least be one plus once a - okay now J becomes one element once a - okay now J becomes one element once a - okay now J becomes one element at j is less than element at ISO the longest increasing subsequence at I that at least be two plus one two three okay now J becomes too so the element at j is less than element at high yes but the longest increasing subsequence at six is already of size three while if we include this one the longest increasing subsequence at six we can do is one plus one - so why do we can do is one plus one - so why do we can do is one plus one - so why do we use that value when I'm already getting three from three and four so I will not do anything about it so now J becomes three again the bond is increasing substance elemental chain is less than high the longest increasing subsequence at six will be 2 + 1 3 but subsequence at six will be 2 + 1 3 but subsequence at six will be 2 + 1 3 but we only have 3 from 3 &amp; 4 so it makes no we only have 3 from 3 &amp; 4 so it makes no we only have 3 from 3 &amp; 4 so it makes no difference so now I becomes point Z 2 and G again starts from 0 element at J is not less than elemental type parameter J is not less than elemental time so J becomes to eliminate J is less than I so this value becomes 2 okay again element IJ is with an element at I so this value comes to +1 3 okay element so this value comes to +1 3 okay element so this value comes to +1 3 okay element at J is not less than element at time so we do nothing about it so now already I is this element it J is not less than element to type eliminate J is not less than a minute I so J becomes - element ik j is less than other than - element ik j is less than other than - element ik j is less than other than two tribes so here we it makes it - okay two tribes so here we it makes it - okay two tribes so here we it makes it - okay this guy is again less than this guy so this becomes 3 and j becomes points 2 6 this guy is not less than this guy so finally 2 points to 2 this guy is less than this guy so thus longest increasing subsequence here will be 3 plus 1 4 once it's an arrangement all you have to do is I tweet through this array and get the maximum value which is the length of your longest increasing subsequence so what is your formula here or formula is pretty straightforward if the are power of J is less than a power R of I and T of I is equal to max of what is already I or T of J plus 1 you can find the full solution at this link gate of calm machetes interview wiki thank you
Longest Increasing Subsequence
longest-increasing-subsequence
Given an integer array `nums`, return _the length of the longest **strictly increasing**_ _**subsequence**_. **Example 1:** **Input:** nums = \[10,9,2,5,3,7,101,18\] **Output:** 4 **Explanation:** The longest increasing subsequence is \[2,3,7,101\], therefore the length is 4. **Example 2:** **Input:** nums = \[0,1,0,3,2,3\] **Output:** 4 **Example 3:** **Input:** nums = \[7,7,7,7,7,7,7\] **Output:** 1 **Constraints:** * `1 <= nums.length <= 2500` * `-104 <= nums[i] <= 104` **Follow up:** Can you come up with an algorithm that runs in `O(n log(n))` time complexity?
null
Array,Binary Search,Dynamic Programming
Medium
334,354,646,673,712,1766,2096,2234
207
welcome to midnight coding today we will solve leap code problem 207 course schedule this is a graph problem but before we continue please like this video as it will give you all the luck you need to land your dream job and just as an extra measure subscribe to the channel and i promise you will succeed in your endeavors and also it encourages me to keep making educational content like this now let's follow our five step process now let's understand the problem so we're not given the number of courses and what they are and we're given the output so the reason why this is true is that to take course one we have to take course zero first so the ordering would be this so this is pretty intuitive and easy to understand but once we see the next example we're gonna really understand what this problem is asking us we are given the number of courses too so we have one and zero and the same for this one so the reason why this is not possible is that to take course one you gotta take course zero and to take course zero you gotta take course one so you can imagine that there is a cycle in this graph so since there is a cycle this is not possible and that's basically what the question is asking us is this possible to schedule this and the only condition that it's not possible is that if there's a cycle in this graph so now let's come up with our own example so in this case the number of courses would be four to take course eight we're gonna take course seven and to take course seven we gotta take course two and three so the ordering would be possible it'll be two three seven eight where we take course two three seven eight in order and this would be possible however this would not be possible if three was pointing to two and two was pointing to eight now what this means is that to take course eight we gotta take seven to take seven we gotta take two however to take two we're gonna take eight now this becomes not possible with that in mind let's think about how we can solve this since this is a graph problem we can come up with number of solutions we have dfs and we have bfs that first search we can go to all the paths in depth and then we're gonna say for example when you get to two are we visiting any of the note again we go from eight to seven to two and we are asking does 2.27 and we are asking does 2.27 and we are asking does 2.27 or does 2.28 if it does return false if or does 2.28 if it does return false if or does 2.28 if it does return false if it not continue that's a possible solution in dead first search in breadth first search we can also do the same thing we can go level by level and ask the same question and it will work however in this problem we are going to use something called topological sort is a special graph algorithm that we use to detect cyclic graphs if there's a cycles in the graph or any sort of problem that has dependencies on each other such as course scheduling from what we saw earlier like course a is dependent on course b and course b is dependent on course c so this is a dependency problem so we'll be using topological sort to solve this so this is how we are going to use topological sort we have our graph and then we have a variable called in degrees so now let's think of what they are so for example at vertex 8 or node 8 we have an edge to vertex 7. so in our graph we're going to say something like this and for seven we have two vertices two and three so we're gonna say and so on so that's how we're going to populate our graph and in degrees is basically the count of how many incoming edges we have to a given node so for example eight has zero in degrees meaning that there is no nodes that are coming to eight however for seven there is one we have eight coming to seven and the same for two and three however if there was another note let's say 10 and if it was pointing to two we were gonna say that two has two in degrees in topological sort we have sources and we have sinks sources are basically all the nodes that have zero in degrees such as eight and sinks are any nodes that have no outgoing edges such as twos and threes so topological sort starts with sources and ends with sinks and now let's take a look at how this might work i'm going to define a result variable and i'm going to take the source which is 8 and i'm going to put it in my result variable now that i've taken 8 i'm going to take it out of my queue so this would be a breadth first search algorithm and we'll be using cues now that we've done that seven no longer have in degree of one it has zero now it becomes our source and we're going to do the same thing we're going to take out seven and then now two has no longer an indegree of one it has zero and it becomes the source and the same with three then we know that we are finished with our loop because we have no sources left to iterate through now you can see that the length of our result is 4 which matches the initial number of courses that we've given in the first place so this is how we're going to utilize topological sort to tackle this problem now let's start coding so here's the solution to the problem in go for this problem we'll be using topological sort so let's define our variables so we need to define graph and in degrees and after that we're going to have to initialize our graph and in degrees so to define our graph uh let's make this a map let's make a hash map and our graph is going to have integer keys and array as values and now let's define our indegrees and our integrals is just going to hold integers as values now we're going to have to initialize our in degrees so to initialize our indegrees we're going to have to make a key for each courses so let's say index and then at this index our indegree's graph math hashmap is going to be initialized to zero in the beginning and then we can just loop over our prerequisite to fill in our graph and in degrees so now we're going to have to initialize our graph and in degrees with the prerequisites input so for prerequisite and range prerequisite and don't forget to add this for the index but we don't care about the index right now so source and destination is that at index 1 it's going to be the source because to take course zero you gotta take course one and the same for destination it's going to be at index zero now we're going to have to populate our graph to do that we can just say the graph source and we can just append the destination to this list and then in degrees we're going to have to update it as well so it's going to be plus equals one because the source is going to contain the destination and this destination has an incoming vertex which is source so we've got to update it by one okay now that we've done initializing and filling our graphs then we're going to find the sources so sources is going to be an array of integers and to find the sources remember in our drawing explanation we've said that any vertex that has zero incoming edge they are the sources so we're going to say for key in range in degrees if the key in this indegree equals to zero that means we've found the source so we can just append it to our sources all right now that we've found the sources we're just going to write a while loop and then iterate until we find all the course schedules so we're going to say for length of sources is greater than one greater than zero we're going to keep iterating through our sources array so the vertex the current vertex that we're looking at is going to be at sources at index zero and that means we're gonna have to update our sources and sources is going to be everything after this index so we're basically just discarding the first index after that we're going to have to save our vertex in an array as well so i'm going to call it far course schedule and it's going to be an array and after that we can just say car schedule equals to and car schedule at third time so this will keep adding our schedule in order so we can later on you can say if it's possible to schedule all the courses and the last thing we're going to do is we're going to update the neighbors so now that these vertex no longer exists in our sources we're going to have to decrement all the neighbors in degrees so we can say for neighbor and range graph at this vertex we're going to say in degrees at this neighbor is going to be decremented by one because the source is no longer there anymore and then we're going to say if the neighbor if this equals to zero meaning that there are no incoming edges that is known anymore we're going to make this our source okay looks like i have misspelled neighbor over here i'm going to just fix it quickly okay that's basically it for this solution um now we just got to return if it's possible to schedule or not and to do that we can just return if the length of our course schedule array equals to the number of courses and if it equals that means it's possible to schedule and if not that means there's a cycle in this graph and in that case we cannot schedule all these courses so we're going to say return the length of course schedule and we can say if it equals number of courses okay now let's run it to see if it works okay we're gonna define the variable now let's submit it and it works and now let's jump into step number five so i hope you learned something new today and step number five is that at the end of our interview we're gonna have to think about more edge cases and then how we can optimize our solution in a better way however on lead code we know that we have passed all the test cases in our actual interview we would want to come up with different edge cases and then we have to think about how we can optimize our solution so we can show our interviewer that we are thinking of optimizing our solution in a better way however for this problem topological sort would be as optimal as it would get so with that being said i hope you learned something new today and i'll see you guys soon
Course Schedule
course-schedule
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 `true` if you can finish all courses. Otherwise, return `false`. **Example 1:** **Input:** numCourses = 2, prerequisites = \[\[1,0\]\] **Output:** true **Explanation:** There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. **Example 2:** **Input:** numCourses = 2, prerequisites = \[\[1,0\],\[0,1\]\] **Output:** false **Explanation:** There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. **Constraints:** * `1 <= numCourses <= 2000` * `0 <= prerequisites.length <= 5000` * `prerequisites[i].length == 2` * `0 <= ai, bi < numCourses` * All the pairs prerequisites\[i\] are **unique**.
This problem is equivalent to finding if a cycle exists 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
210,261,310,630
1,910
Hello, this question is given in 1910, so whatever part we have to delete in it, like ABC, first I have to edit something, I will get that, then I have to delete this text, in the last I have to return it Because I need it, then I created a variable and the find function I am doing in it is a string function, if you give it a string or any character, then it returns its index which is first. In find, for example, the first index of ABCD will be 012, then it will be stored in the index and if you don't know about find, then it mines it, so I want to return it there because I don't want to erase anything again. If I don't want to get it, then I think it means that I will know that the part which is not inside my string, then return it, after that it will return the string, it will delete the answer which is in M-1. So that means after typing three characters, I will be left with this string, and so I have done this as Van Wille Van, so this will continue forever, lo end when I will not get the index, that means not even a single part will be left, it will break.
Remove All Occurrences of a Substring
check-if-binary-string-has-at-most-one-segment-of-ones
Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed: * Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`. Return `s` _after removing all occurrences of_ `part`. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "daabcbaabcbc ", part = "abc " **Output:** "dab " **Explanation**: The following operations are done: - s = "da**abc**baabcbc ", remove "abc " starting at index 2, so s = "dabaabcbc ". - s = "daba**abc**bc ", remove "abc " starting at index 4, so s = "dababc ". - s = "dab**abc** ", remove "abc " starting at index 3, so s = "dab ". Now s has no occurrences of "abc ". **Example 2:** **Input:** s = "axxxxyyyyb ", part = "xy " **Output:** "ab " **Explanation**: The following operations are done: - s = "axxx**xy**yyyb ", remove "xy " starting at index 4 so s = "axxxyyyb ". - s = "axx**xy**yyb ", remove "xy " starting at index 3 so s = "axxyyb ". - s = "ax**xy**yb ", remove "xy " starting at index 2 so s = "axyb ". - s = "a**xy**b ", remove "xy " starting at index 1 so s = "ab ". Now s has no occurrences of "xy ". **Constraints:** * `1 <= s.length <= 1000` * `1 <= part.length <= 1000` * `s`​​​​​​ and `part` consists of lowercase English letters.
It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones.
String
Easy
1999
1,816
hello quick introduction to the video my name is Cameron I'm a graduate Apprentice software engineer currently studying at Glasgow University and I'm using this video as a way to sort of rubber ducky debug a Le Cod problem just attempt to solve it talk through my thought process and hopefully it's useful to someone on here so the problem I'm going to be attempting today is 1816 Tron sentence so I'm just going to read the description a sentence is a list of that are separated by a single space with no leading or trailing spaces each of the words consist of only uppercase and lowercase letters no punctuation for example hello world and hello world or all sentences you're given a sentence s and an integer k h you want to truncate s such that it only contains the first K words return s after truncating it so hello how are you contestant K isal to four so it's going to take the first four words hello how are and you okay uh constraints s which is the sentence between 1 and 500 uh K is in the range one in the AM of numers so you're not going to get like 100 for here it's going to be less than or equal to the amount of words in the sentence uh the words s are they're only separated by a single space there are no leading or trailing spaces okay I'm going to go over to my notes so just off the top of my head um I think what we need to do is split up the words on the white space H and I think there's a python function for that H I think it's just split to split up the sentence into words and then use we could just slicing in Python to only return a certain range of words so let's go with that just going to copy my this into and comment it out so I can reference it so we're just going to do a we're going to I think we could put this in one line we could do return we're going to return uh s do split and this is going to s. split is going to take it and it's going to split up into it's going to split it make a list of words and we want to go from zero up to K but not including K so is this how it works uh so we returned this uh we returned a list of strings ah so right so I'm just going to do list we're going to have a list of words that's what we're going to have to start off with list of words is equal to just this do split and then going to do for word and range uh one or zero oh for word and range h k that's what we're going to do foren range K uh we're going to do output plus equals and output is just going to be a string output plus equal list of words okay list of words word sorry and then we can return output let's H run and this should just make a string not a list of strings ah plus equal um so it's not adding the white space in between them so we need to add white space as well have to wait space and just going to do dot do trim take off any weight space at the end a do strip I think it is okay those pass hit submit and accepted thank you very much for watching the video I hope it was useful to you in some way um if you have any other sort of solution to this that was maybe a bit more efficient or just different uh please leave a comment down below I love discussing these problems and yeah I hope this was useful to you in some way um and yeah thank you once again for watching and I hope you have a great day bye
Truncate Sentence
lowest-common-ancestor-of-a-binary-tree-iv
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation). * For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences. You are given a sentence `s`​​​​​​ and an integer `k`​​​​​​. You want to **truncate** `s`​​​​​​ such that it contains only the **first** `k`​​​​​​ words. Return `s`​​​​_​​ after **truncating** it._ **Example 1:** **Input:** s = "Hello how are you Contestant ", k = 4 **Output:** "Hello how are you " **Explanation:** The words in s are \[ "Hello ", "how " "are ", "you ", "Contestant "\]. The first 4 words are \[ "Hello ", "how ", "are ", "you "\]. Hence, you should return "Hello how are you ". **Example 2:** **Input:** s = "What is the solution to this problem ", k = 4 **Output:** "What is the solution " **Explanation:** The words in s are \[ "What ", "is " "the ", "solution ", "to ", "this ", "problem "\]. The first 4 words are \[ "What ", "is ", "the ", "solution "\]. Hence, you should return "What is the solution ". **Example 3:** **Input:** s = "chopper is not a tanuki ", k = 5 **Output:** "chopper is not a tanuki " **Constraints:** * `1 <= s.length <= 500` * `k` is in the range `[1, the number of words in s]`. * `s` consist of only lowercase and uppercase English letters and spaces. * The words in `s` are separated by a single space. * There are no leading or trailing spaces.
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
Tree,Depth-First Search,Binary Tree
Medium
235,236,1218,1780,1790,1816
144
hey everyone welcome back in this video I'll show you how to solve preorder traversal of a binary tree using a stack in a pre-order traversal as you know we in a pre-order traversal as you know we in a pre-order traversal as you know we visit the root node first process it then with the left child and finally the right child so here instead of recursion which uses stack implicitly we'll use our own stack so the idea is whenever we visit a node we shall process the node and add the node to the stack if the note that we visit is null then we will pop a node from the stack and move to which right child so we will continue this until the stack is not empty or the node that will visit is not equal to null so let's visualize that here initially the node current points to node 5 which is not null so we will add 5 to the output so we are processing the node and then let's add that node to the stack and move to its left child now no 9 is not null hence will process that node add to the output add the node to the stack and move to its left child now the node is null so we'll pop the node which is again 9 so current node gets the value of 9 so now current points to no 9 and then we will move to the right child of nine so current again current is equal to null so we will pop this node from the stack so current will be 5 and move to the right child of 5 so 8 is not null so we will process 8 first add 8 to the stack and then move to its left child again left child is null so current gets the value of 8 will pop the node and then move to the right child now 4 is not null so will process for I'd fall to the stack and then move to its left child three is not null will add three to output three to the stack and then will do its left child current node is null so we'll pop the node from this back and then we will move to the right tail of three current node is null so we will pop the node from the stack and then move to the right child of four note n is not null so we'll process then add ten to the stack go to the left child of ten now current is null so we'll pop the node from the stack then move to the right child now current is null the stack is empty so we can so that's the end of the postorder traversal now with this understanding let's try to code this here the output is a list of integer so the written value is a list of integers so let's create a list of integer call it out put its new ArrayList now we will create a stack of three nodes let's name it stack and then let's have a node called current gets the value of root so like I explained the idea is boiled stack is not empty so stack is not empty or the note that we process current is not equal to null in either of these two cases now we will check if the current node is not equal to null then we will process the node that is we are adding the nodes value to the output so output dot hand current dot value we will add the node to the stack start off push and then move to the left child if then in the other cases if the node is null if current is null then we will pop the node so current gets the value of stack dot pop the value in the top of stack and then we will move to the right child of current so at the end of it let's return whatever is the output so let's try to run this so this is working correctly I will try to submit solution all right it is working fine so thank you everyone for watching this video if you enjoyed it please hit the like button also do subscribe in the next video I'll be doing the inorder traversal using a stack thank you
Binary Tree Preorder Traversal
binary-tree-preorder-traversal
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,2,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
94,255,775
1,871
hello guys welcome to algorithms made easy my name is rijad and today we will be discussing the question jump game part 7. in this question we are given a binary string and two integers min jump and max jump in the beginning we are standing at index 0 which is equal to 0 we can move from index i to index j in the following conditions are full fit we need to return true if we can reach the last index or we return false we are given two sample example with the problem in the first case we are able to reach the last index so we return true in the second case we are not able to reach the last index so we return false so let's first discuss what the question is all about and how we can solve this so let's first take an example this is the string that is given to us which we have represented as an array for us to understand it much better similar to all previous jump games we are standing at a zero index and we can make a jump to a next index what we need to find out is whether we are able to reach the last index or not so when we are at the zeroth index we can jump to any index in the forward direction only but similar to all the jump games we do have certain condition attached to the jump that we are making so what all are these condition are the first condition is we can only jump at an index whose value is zero the second condition is the minimum jumps is given to us in this case it is two so we cannot make any less jumps than the minimum jumps and third is there is a maximum jump attached so we cannot make more than 3 jumps in this particular case now the jump that we made from index 0 to index 1 is not a valid jump because the value at index 1 is 1 which does not satisfy the first condition that we have so what will be a valid jump should be in the range of minimum and maximum jump and only to a index whose value is 0 which means this becomes our valid jump from index 0 to index 3. the jump is made to an index whose value is zero it is well in range in between the minimum and maximum jumps once we are clear about what is a valid jump and the condition that we need to follow in order to achieve a valid jump we can now move forward now you all might have solved the jump game 6 problem as well and in the previous video we discussed what is the approach that we will be following in order to solve that particular problem so in that problem we talked about some previous k steps because we had a value of k which says that from any index we can jump to any value ranging between 1 to k so we will use the same approach over here if you haven't watched the video yet i highly recommend you to watch the previous video the link is at the top and in the description below the rest of the explanation will make much more sense to you if you get a good grasp on the previous explanation now starting where we left off in the previous explanation we talked about having a previous case steps to any of the index and if we know that we need to find the maximum in the previous k steps we were able to find out the maximum sum for the current index so what was the k was nothing but the maximum jump that we can take from any of the indexes but the minimum jump in that case was always 1. so how about we change some of the parameters and take the maximum jump or ks3 and the minimum jump is two in that case how do you think this window should change the window will just shift because now the minimum jumps should be 2 and the maximum jump should be 3. so in order to reach the index 5 we need to either jump from index 2 or index 3 because from index 2 it will be 3 steps and from index 3 it will be 2 steps and this is very important logic in this particular problem as well so let's see how we can apply this logic on the current problem we found out that a valid jump from index 0 is only to index 3 once we reach that index the only valid jump remaining is to the index 5 so we are able to reach the last index and we can return true in this case now if we see and apply the window logic again we see that its window will live in between index minus maximum to index minus mention and if there exists any reachable 0 in this particular window we are able to reach our current index and this particular logic holds true for any of the index present in the array this window will just shift according to the current index now let's try and the example that we have and see if it works or not we are at an index 0 and the value is 0 in this case that means this particular index is reachable to us now let's move up the next index now this index value is 1 and there won't be any window attached to it because the minimum jump is still 2 and it is index 1. so in this case we cannot do anything and as the value is 1 we are sure that we are not able to reach it so it is a false value for this particular index now we are storing the intermediate results because it will be very useful for us and it will make much more sense as we go through the with this explanation now we move to the next index and here we get the window that we were talking about previously the window size cannot go beyond the size of the array so the index minus max jump or the zero value and then we have index minus min jump as we are having one value in the window we need to find out if there exists any zero which is reachable in this particular window now we already know that we cannot jump on an index with the value one so it will only be reachable zero now why we are talking about only reachable zero because not all zeroes will be reachable and we will discuss that example so we see that in this window we have one reachable zero so we need to keep a counter of how many reachable zero are present in the window that we have so the reachable zero is one so as we have a reachable zero in this window but the value present at this index is not zero we will put false in this case so what is this reachable zeros now let's talk about a scenario wherein we are not able to reach our index with value equals to zero suppose in the initial example the initial value was 1 and we were standing at index 2 whose value is 0 in this window there is no reachable 0 it is only 1 with a false value so if it is false the reachable 0 is still zero that means we cannot reach this index because there doesn't exist any zero from which we can jump to the current index and that is what the reachable zero represent it represent that whether there exists any index in the window from which you can jump to the current index and with each index we will be updating the number of reachable zeros so this becomes a case wherein the value is zero but it is not reachable to us so that's why answer for this index is false we cannot reach this particular index now coming back to the original problem we now move to the next index in our window grows again we are adding a new index into the window but it is false so the reachable zeros won't change but still number of reachable 0 is greater than 0 there exists at least one 0 which is reachable in this window and the current value is also 0 so we return true now we could have iterated through the range given to us in the window and found out if there exist any reachable zeros but that technique would have costed in a higher time complexity so we are using sliding window in this particular approach now we move to the next index and you'll see how the window slides with the current index when a window slides with the current index it affects two values one which is leaving behind and one which it is adding in itself we already know what we will do with the one value which we are adding in this window if it is true then we are adding that into our reachable zeros now what about the value that we are leaving behind needs to be taken into consideration in order to update the reachable zero as well we need to check if the value that we are leaving behind was a reachable zero if it is a reachable 0 we need to update the variable reachable 0 with the appropriate amount so as in this case there is one less reachable zero we will decrement the reachable 0 to but since the value present at this index is one will put false the reachable zero is also zero and also the value is one so the value will remain false now we move again in this case the value removed from the window was false so we do not do anything with the reachable 0 but the value that is getting added into the window is a true so we increment the reachable 0 to 1 at the current index the value is 0 and the reachable 0 is also greater than 0 so we put 2 in the case see how we are using the intermediate results of true and false whether we can reach that particular index or not as we need to return whether we are able to reach the last index we can simply return the last value which is true in this case so what all techniques that we are using over here we are basically using sliding window plus dynamic programming sliding window with the window that we use which slides with every current index and dynamic programming because we are storing the intermediate results every true false represent whether we are able to reach that particular index starting from 0 following the conditions given to us by the problem so what are the basic steps that we took during the course of solving this particular problem we see that it is only possible to reach index 0 if its value is 0 now for every index starting from 1 we find out if there exists a reachable 0 in the window between index minus maximum and index plus benjam we will be having a variable which keeps track of that if there is at least one value and the value at the current index is 0 then it is possible will hold true and false into an array and at the end we just need to return whether we are able to reach the last index or not as always i'll recommend you to solve this problem on your own with the explanation that we discussed and if you face any issue you can always come back to the video now it's time to code this particular approach so as discussed we would need array to store the intermediate results and the length of the array will be equal to the length of the string given to us we'll convert the string error into a character array now we know that we are standing at an index 0 and we need to put true into that particular index if its value is 0 otherwise we will put false into that so we'll update that at index 0. now we need to iterate from index one to the last index so we need to keep track for all the reachable nodes so initially there are no reachable zeros so it is initialized with zero the condition that we discussed is the value at this particular index in the dp array would be dependent if the reachable is greater than 0 and also if the value present at this index is 0. now we need to just update the reachable so we'll now do the two operations that we were doing while we are maintaining the window the first operation is when we are trying to add a value into the window so we'll first check if the i is greater than the min jump in this case we will be adding the value so the reachable will get the added value and we need to check if the value i minus min jump is true or not if it is true then we add 1 otherwise we add 0 and since minimum jump can be 1 we'll put a equals to sign over here now about the value that we need to remove from the window so this value will be i minus max jump minus 1 or 0. now why we are doing i minus max minus 1 because if you recall our window lies in between i minus mac jump to i minus min jump so the value that is getting added lies at the minimum side that is what we are doing which will be i minus min jump which is in the window that we are working in but this value lies outside the window which is i minus max jump our window starts from this range and we need to remove the value prior to this particular index once we have removed this value we'll have the reachable nodes we're updating the dp with that and at the end the answer will be at the last index now let's first try run this before running so we are putting the value true if the initial index has the value of 0 we have a reachable variable we are updating the reachable according to whether the value is getting added or getting removed by checking if the reachable is zero and the value at index is zero then only we are putting true otherwise it will be a false and at the end the answer lies in the dp of n minus one so now let's try to run this code for all the sample test cases so it is successful let's submit this so it got submitted successfully the time complexity in this case is o of n as we are doing an iteration from 1 to n well the space complexity is also of n as we are using a dp array in order to store the intermittent results i hope this video helped you do let us know your thoughts in the comments below thanks for watching this video see in the next one you
Jump Game VII
palindrome-partitioning-iv
You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions are fulfilled: * `i + minJump <= j <= min(i + maxJump, s.length - 1)`, and * `s[j] == '0'`. Return `true` _if you can reach index_ `s.length - 1` _in_ `s`_, or_ `false` _otherwise._ **Example 1:** **Input:** s = "011010 ", minJump = 2, maxJump = 3 **Output:** true **Explanation:** In the first step, move from index 0 to index 3. In the second step, move from index 3 to index 5. **Example 2:** **Input:** s = "01101110 ", minJump = 2, maxJump = 3 **Output:** false **Constraints:** * `2 <= s.length <= 105` * `s[i]` is either `'0'` or `'1'`. * `s[0] == '0'` * `1 <= minJump <= maxJump < s.length`
Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest
String,Dynamic Programming
Hard
131,132,1403
144
this lead code question is binary tree pre-order traversal it's lead code pre-order traversal it's lead code pre-order traversal it's lead code question 144. it's also one of the Google interview questions it's very similar to the previous one that we did just yesterday so here we have the roots of a binary tree and we have to return the pre-order traversal of the nodes values pre-order traversal of the nodes values pre-order traversal of the nodes values but we have to do so through a vector basically we have to Traverse the tree using the pre-order traversal algorithm using the pre-order traversal algorithm using the pre-order traversal algorithm but instead of Simply visiting and printing the values we have to store them in a vector in the correct order that is the pre-order sequence and then that is the pre-order sequence and then that is the pre-order sequence and then we have to return that vector so these are examples again very similar to the in order traversal question that we had yesterday so we have the same structure for a tree it has a value left and right child and we can assign values to those through these Constructors at first I want to add my Vector to my solution class so I have this private access modifier and I'm creating a vector of integers called values now I need to allocate some memory space to my vector and I'm using the reserve function because I want to specify the minimum capacity for my Vector otherwise I'm going to have a lot of reallocation whenever I'm pushing new values to the vector now here I have a condition for my function it's going to be recursive function and I will need to check all the time if my current nodes is a valid nodes so here I have if Roots is valid meaning it is not null then I want to store the current value inside of my values Vector so I'm having values dots and place back and I add the value of my nodes to the vector which is this one here before I proceed you might wonder why I have 100 here is because of the constraints where they say that the number of nodes in the binary tree is up to 100 so now continuing with the algorithm we need to visit the left after we add the value to the vector but we can only do so if the left is not null so first I'm checking here if the left child of the current node is not null then I want to call this function this pre-order traversal function but this pre-order traversal function but this pre-order traversal function but this time around I'm going to pass the left trials to the function so this here is recursion then I need to visit the rights and I do the same thing here if the right child is not null then I'm going to visit it and when I visit it I'm going to enter this logic again where I'm going to push that value to my vector and continue with the traversal and then when I'm done I have to return my invictor so remember that with a pre-order traversal the order is roots pre-order traversal the order is roots pre-order traversal the order is roots lefts and then rights but that's about it for this solution so let's run this code and we've passed everything for the sample test cases so we had case one and two and then three so two was empty and we still passed it because at every function call in our logic in the function definition we always check if Roots is not null so if it's null then we can return values which is empty so now let's submit this solution and we pass everything with decent speed you can see that in my previous submission sometimes it was 0 milliseconds but it's pretty good speaking of performance so that's it for this lead code question it was called binary tree pre-order was called binary tree pre-order was called binary tree pre-order traversal and it's a Google interview question that you can practice if you have an interview coming up but for now that's it for me if you like my solution and you like my tutorials please subscribe to my channel and I'll catch you next time
Binary Tree Preorder Traversal
binary-tree-preorder-traversal
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,2,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
94,255,775
925
Hello everyone welcome back you me channel Polity keyboard ok so let's see what is the question from you ok we have to print the name Pappu t a double p u ok now what have we typed double t double a Double P Okay, now look here, who wants to type this name, okay, what name we want to type, can it be? The name we have typed means that we have to type this, okay, but we have typed it. What is this, can this be made from this, then what is its logic, what is the meaning, have we understood from the question, what is our type which is string, what is the name of string, if our type is string, otherwise we will return water, then what should we see? Okay Double D Double A S Yes Okay now tell us what is this that we have typed like we have the name Daksh so we will expand both of them further so what will we do If from se huye k is moved forward ok we have moved g forward ok again guys move on then ok so what will we do ok we have again moved ib is equal ok now this is what we did to do this so we We will write the code which we saw here, it is completely fine, the code we have written to do this is fine, kept it at zero, it is fine brother, we have put a loop, it is fine and it is inside the loop, we first checked the condition, what is the name and its character. The one which is on ke is from se. If it is from se then both will increase. Okay, if there is no se then we will look at the old one of i and at ke. If it is from both then we will increase only ji. If that too is not from se then we will look at the result. I understood that there are three conditions, if both are there, then both will read. If they are there, then we will check I - 1 read. If they are there, then we will check I - 1 read. If they are there, then we will check I - 1 and 0. If they understand, then we will make K bigger. If even this is not there, then it is okay to do the army directly. Understand this much. So, if we don't have a name on it and we don't have an I-index, and we don't have an I-index, and we don't have an I-index, what do we do when we have differences in the first index of posting, then to handle this, we will do this mixer whenever we check I-1. we will do this mixer whenever we check I-1. we will do this mixer whenever we check I-1. But whenever we check I minus one, before that we will put the false condition is OK or Ali condition I is greater than zero is OK, we will put this and our is OK, we will put this then our index will not come out of Mount Everest. Otherwise, if we do not find this condition, as soon as first A goes, okay, second, we come with another, okay, then whenever it checks I-1, then okay, then whenever it checks I-1, then okay, then whenever it checks I-1, then we always see that I, one, three, four are not indexed, okay, different. It is done okay and it will give true if the eye goes out like before. Okay, according to the question it will be wrong, otherwise what will we do, our type length is shortened and the eye goes out like in this. Look, Aa came out first and Jai just went in. Okay, just like if this condition is checked then we will check whether k is equal to i - 1k, if i - 1k then we will do k plus i - 1k, if i - 1k then we will do k plus i - 1k, if i - 1k then we will do k plus, if it is not then we will pause return. Okay, we have to remember that like I came out, then we will check K with I-1 only because then we will check K with I-1 only because then we will check K with I-1 only because I is here, so I-1, what will happen to C, we will I is here, so I-1, what will happen to C, we will I is here, so I-1, what will happen to C, we will check it with this, okay if it will flood, then D and C are different, so it is possible, okay. So we have handled it here, okay if it goes out first, it will be water, okay and if the name dot length is big then by taking type dot, it will become small, it is the characters are small. So how will we make it, if we are not making a type from the name, then we have to check that it is greater than the type, okay, so this thing is done, so we have seen everything, we have seen all the conditions, there are three conditions, okay, first we have here. If you see then both will read i, if it is not from then if you see after i then only k will increase. Okay, now again we have the issue brother, if the index is already different then to handle it we will give this grater. The one with zero or we will put a check. Okay, after putting that check, there is another condition that if I goes out first and the K type is smaller than the dot pen. Okay, then we will put a condition for that too that if I. - 1 is not equal to k. Okay, if I. - 1 is not equal to k. Okay, if I. - 1 is not equal to k. Okay, so we will return the value plus. Okay, so we have handled all the cases. Now we are okay. What is the final code? Okay, both the points are missing and the first index is not there. Now we will check I - 1 and G. Okay then if check I - 1 and G. Okay then if check I - 1 and G. Okay then if both are done then we will increase only G and make name first. Okay and if this condition is there that I goes out first then A and K type dot. If R is smaller than the bank, then it has come out of the loop. Another check will be found that the hybridization is small. Yes brother, it is small, so here we will ask people inside, so we have first imposed the condition that I - 1 and if K are not equal then I - 1 and if K are not equal then I - 1 and if K are not equal then We will return with the result, if we get equal then we will give bigger G. Okay, when this check is done then we will directly come to the last condition. Our name will be smaller than the dot line. Okay, that means we will return okay. By removing this thing, we can simply write, both are equal, otherwise what will we do, it is simple, here we did not check here, okay, if both are equal, then i cannot be filled first because i cannot come out. It 's okay and 's okay and 's okay and if this is not possible, then we will check it directly. If it happens and do the length of the dot, I will put it in the description box below. Plus, if you want more questions because we are going to watch the daily video. YOU CAN FOLLOW CODE IN PRIVATE CHANNEL [MUSIC]
Long Pressed Name
construct-binary-tree-from-preorder-and-postorder-traversal
Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times. You examine the `typed` characters of the keyboard. Return `True` if it is possible that it was your friends name, with some characters (possibly none) being long pressed. **Example 1:** **Input:** name = "alex ", typed = "aaleex " **Output:** true **Explanation:** 'a' and 'e' in 'alex' were long pressed. **Example 2:** **Input:** name = "saeed ", typed = "ssaaedd " **Output:** false **Explanation:** 'e' must have been pressed twice, but it was not in the typed output. **Constraints:** * `1 <= name.length, typed.length <= 1000` * `name` and `typed` consist of only lowercase English letters.
null
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
Medium
null
152
in this video we're going to look at a legal problem called maximum product subarray so we're given an integer array nums find a contiguous subarray that has the maximum product and return that product value so subarray is basically a contiguous subsequence of the array so basically this question is kind of similar to the maximum subarray problem and basically the idea is the same we have given an array we have for each and every single element we have two choices one is we can't be able to take the current item and add it on to the current subcontiguous of array or we start a brand new current uh contiguous sub array starting from the current element right so one way we can solve this problem is we can use a proof force approach quickly for each every single item you do a linear scan on the right to find the maximum product subarray and at the end we're comparing each and every single iteration to find the maximum product sub array right so approach will give us a time complexity big of n squared so it's not the most optimal solution right so in this case to solve this problem using a linear is kind of similar to what i just talked about for the maximum product a maximum sub array right and the idea is same for each every single items we have two choices so but the thing is that we could have negative values right and we can also have zeros so in this case if i have all positive value like for the maximum value we have seen so far is just one or the current item right so in this case the maximum value that we've seen so far is one or just the current item right we're starting a brand new contiguous sub array or we're combining with the current contiguous subarray so in this case we're it doesn't really matter because we have two times one is two or just two itself right and then now we have three so in this case we have the side that we stick to three or 3 times 2. in this case 3 times 2 will give us a bigger product so the current maximum product sub array is going to be 6 right but if we have a negative values this will simply not going to work because for the maximum product for this position is going to be negative two for the maximum product for this position is either three or three times negative two in this case three is bigger right and then for this position we either have negative four times three or we have just negative four in this case negative four is bigger so we basically keep track of the maximum value in this case the maximum value that we've seen is three so in this case that will give us a incorrect answer because the maximum product that we're expecting is going to be 24 right sorry it's gonna be positive 24. so in this case uh we can't really use the same method because here you can see we always keep track of the maximum value right and we also need the minimum value so that we can be able to compare to see if it's the minimum value that we've seen is bigger or the maximum value that we've seen is bigger right so that if we have a minimal value or sorry a negative value right that will also because negative value times negative value will give us a positive value so we can be able to uh find the uh the maximum product sub array and let me show you an example initially we have an array and in this case we're going to keep track of the maximum uh the maximum value we've seen so the maximum product that we've seen so far plus the minimum value the minimum product that we've seen so far okay so in this case initially we have an array and the first element is going to be two and two right and then for when we get to the second element in this case we compare to c the minimum is going to be uh the current item times or the um the maximum value that we've seen so far times the current item or the minimum value that we've seen so far times the current item right so uh at the end it will give us negative 5 for the maximum value that we've seen so far and the minimum value is going to be negative 10. okay so we're going to use that later because in this case if i see another negative value like right here if i see another negative value i can be able to get a positive value right so that could also be the maximum product as well so if i continue you can see we have this the third element right for the third element we can either get a current item or the current item times the maximum item that we've seen so far or the current item times the minimum value for c that we've seen so far for the min and the max right so in this case we have three is the maximum value that we've seen so far and the minimum is going to be negative 30. okay and then in this case we continue for the fourth item and we have three as the maximum that we've seen so far and negative 30 is the minimum item that we've seen so far uh once we get to negative four you can see here um in this case we also have it compared with the minimum value right in this case you can see that once we get the negative value times the negative value right this will give us a positive value so we get 120 and then for the minimum value that we've seen so far is going to be 12 negative 12 right and then once we get to 0 of course we're also going to have a placeholder like a result which keep track of the maximum value that we've seen so far right the maximum um the maximum product sub array right and in this case so far we the maximum product sub rate is uh 120 and then for the when we get to zero in this case basically we kind of reset our maximum the maximum so far and the minimum so far to be zero and once we get to negative 10 you can see we're starting a brand new contiguous up array right and at the end you can see that the maximum 0 the minimum is negative 10 and so on and so forth so once we get to 2 you can see we have 2 negative 20. at the end you can see we uh once we get to 8 we have 16 and negative uh 120 right so you can see that we keep track of the maximum product sub rate throughout the array right and then we for each iteration we first get the maximum so far the maximum value we've seen so far and then we have to keep track of the minimum value to get so far so then once we update the max so far and the minute so far we also have to update the result so the result is either the current uh maximum product sub array or the maximum value that we've seen so far right so this will give us a time complexity of big o of n where n is the number of elements that we have in the array and the space complexity because we're not using an array or anything we're basically just using three variables to keep track of the uh the max that we've seen so far and the min that we've seen so far as well as the maximum product sub array right so therefore the space complexity is just going to be constant so now let's take a look at how we can do this in code we're going to do is we're going to use those variables right so we're going to have max so far which is going to equal to the first element that we have and we're also going to have min so far which is also equal to num0 and we're also going to have a result which stores the maximum product that we've seen so far right so in this case it's going to be numbers at zero as well so at the end we're basically going to return results okay so what we're going to do is we're going to have a for loop which start at the second element in the array so n is going to be equal to gnomes.length so what we're going to do is for each iteration we're first going to update the max so far so max so far is equal to the maximum okay is either the current item so nums at i or it's going to be max so far times nums at i or we have minimum so far times the current item okay and once we update our max so far we also have to update our min so far but the thing is that we also have before we update the mac so far we have to store the previous value right onto a temporary variable because if i update the current value right just like this one if we update the current value there's no way that we can be able to compare the minimum value so now for the min so far is equal to either the maximum that we've seen so far right so it's going to be the current either the current item or the maximum that we've seen so far or the minimum that we've seen so far right so maximum so far times the current item or minimum so far times the current item and we also need to put this in the math.max and this has to be a min okay so now once we update the max in the min we're going to update our result so result is equal to either the current results right the current maximum product or the maximum that we've seen so far okay and at the end we're just going to return results okay so let's try to run our code and now let's try to submit uh you can see we have a false answer that's because we have to get the temp max right so we have to use the temp max instead of the max so far okay now let's try to submit again and you can see we have our success so this is basically how we solve the uh maximum product subarray and there you have it and thank you for watching
Maximum Product Subarray
maximum-product-subarray
Given an integer array `nums`, find a subarray that has the largest product, and return _the product_. The test cases are generated so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[2,3,-2,4\] **Output:** 6 **Explanation:** \[2,3\] has the largest product 6. **Example 2:** **Input:** nums = \[-2,0,-1\] **Output:** 0 **Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray. **Constraints:** * `1 <= nums.length <= 2 * 104` * `-10 <= nums[i] <= 10` * The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
null
Array,Dynamic Programming
Medium
53,198,238,628,713
83
hi everyone today we are going to solve the ritual problem uh remove duplicates from a sorted list so you are given head of sorted list delete all duplicates such that each element appears only once return the linked list sorted as well so let's see the example so you are given one two so one is a duplicate number so return linked list should be like one two and uh let's see the example two one two three and the one and the three are duplicated so this should be one two three so actually this is a very simple question and let me explain how to solve this question now so head point is here and also i initialize the answer variables with at pointer and this answer variable should be returned value so i'll explain later so let's begin so check the first check the current number and the next number if they are same and just remove next node and then connect to next node here and then again compare the current number and the next number they are not same so in that case so head pointer move next and again current number is 2 and next number is 3 they are not same in the case head pointer move next and then again current number is 3 and the next number is 3. they are same in the case remove next node and then connect to next in the case i think now and then finish looping but problem is head pointer already move like a three until three but we want to return like one two three like an entire link to this so that's why uh we need uh this answer variable so if this one uh i returned this answer variables and that means i can return like a one two three linked list so yeah uh this is uh the like how to solve this program okay let's write the code okay first of all update answer variable with head pointer and start looping current and the current top next i exist if hit r so current value equal current next value then update uh next node with head dot next if not the case just uh move head pointer to next so just next and then as i explained earlier so head pointer already moved forward so that's why return as a variable so let me submit it yeah this solution works so i hope this solution useful for you and if you like it please subscribe the channel and hit the like button i'll see you in the next question
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,1,2\] **Output:** \[1,2\] **Example 2:** **Input:** head = \[1,1,2,3,3\] **Output:** \[1,2,3\] **Constraints:** * The number of nodes in the list is in the range `[0, 300]`. * `-100 <= Node.val <= 100` * The list is guaranteed to be **sorted** in ascending order.
null
Linked List
Easy
82,1982
1,304
yeahyeah Hi everyone, I'm a programmer. Today I'll introduce to you a problem with the following title: Find n you a problem with the following title: Find n you a problem with the following title: Find n unique integers whose sum is 0. The problem asks as follows, given an integer n, return any array containing n unique integers so that when we + Sum them all up, it is said we + Sum them all up, it is said we + Sum them all up, it is said to be zero, the problem request is quite simple. Let's simplify, let's look at them, for example one in example one, we give n = 5, it follows that example one, we give n = 5, it follows that example one, we give n = 5, it follows that we have to create a piece consisting of different elements but also of dissimilar elements and their ports must be equal. If not, here we see that they give us some problems, some strong ones, some valid pieces. For example - 7 - 1134, we valid pieces. For example - 7 - 1134, we valid pieces. For example - 7 - 1134, we see that the sum of the totals of these arrays is equal to 0 and In these arrays we don't have any numbers. It's strange that this is the same. Similarly, the following results can also be accepted like - 5 - 1 2 3 5 - a accepted like - 5 - 1 2 3 5 - a accepted like - 5 - 1 2 3 5 - a bad exclusion - 6 + 1 = -5 - 5 + 2 is -3 - 3 + bad exclusion - 6 + 1 = -5 - 5 + 2 is -3 - 3 + bad exclusion - 6 + 1 = -5 - 5 + 2 is -3 - 3 + three is zero and there is no number that matches A and yet we go into example 2 with n = 3 then - 1 0 1 n equals three is with n = 3 then - 1 0 1 n equals three is with n = 3 then - 1 0 1 n equals three is Now we only have the number sequence 0. Well, now we have removed the requirements of the problem, now we go into the algorithm thinking part to solve this problem, then my algorithm will be introduced to you. will be an algorithm inspired by example 2 and example K. As you can see in example 2 and example three, we have the return result as a number 0 and a number minus 1 and 1. If this case N is strange. You see, what about the case? For example, in another example that I think, for example, the case you have is zero and the case N = 2, then I case you have is zero and the case N = 2, then I case you have is zero and the case N = 2, then I don't need this zero, right? I just need - 1 and a medicine, so just need - 1 and a medicine, so just need - 1 and a medicine, so I will have an algorithm that says I will create a piece, then I will create a piece by letting Y run from 1 to n divided by two. That means I run to n divided Just 2 times, if I don't run all n in each time, I will add an element to my result piece at position ty and an element at the position I added, I will add an element with the value y and an element with the value - y into the an element with the value - y into the an element with the value - y into the resulting piece, after I add all the elements. Okay, we will end the loop at this point our piece will have pairs of numbers that add up to are not certain, right? Because I add a y value and a y value, the sum is zero, so if I add N twice, that number also definitely sums to zero, but in this case If N = N is an but in this case If N = N is an but in this case If N = N is an even number, then that is our result, but there is a case where n is an odd number, then you can see that the number of elements to plant trees on that network is missing one unit, and one element is missing. I add zero to that element like example 2 and example 3, then my fragment will be the returned fragment and then I will proceed to install the programs in Roland language first I will declare one forever J dau, then I will return it to the resort and now I will do the calculation, how about I will have a filter circle y go start like I said go from one y will going to n divided by two is as small as n divided by 2 and each time you go, y increases by one unit and then I skip the times like that, I will append two values to di strawberry which are the value of y a and the value of the field Y a ha means writing y means y multiplying dog - 1 ha means writing y means y multiplying dog - 1 ha means writing y means y multiplying dog - 1 Then after finishing this loop, our deep piece contains an even number of elements and the sum is zero. Now we Check to see if n is an odd number. If you owe the percentage divided by 2 and equals 1, it means that you divide n by 2 and leave a remainder of 1. This means that this is an odd number, so we will add it. add an element for gratitude, what number should I follow for this result now so that the total is zero and only I will be zero? If you ask like that, I will test run this program then you You see that I have solved the first example, but now I have less time to solve the other examples. You can see that it is not there, it forces us to follow the order. So I have gone through it. With all the examples of the problem, I will now quickly evaluate the complexity of these algorithms. Tonight, it is clear that we have the Energy filtering loop twice, so the complexity of the algorithm is The math will be n, but for n, we'll do a trick that n. Okay, the complexity of the storage space here, we have one more variable and the element in the resort, it will be equal to With the input, the level of complexity of the people of the word is also when I will end the video here. If you find it interesting, please give me a like, sub, like and share the experience. If you have any questions or comments, please contact me. If you have a better solution, you can write it in the comment section below. Thank you all. Goodbye and see you again.
Find N Unique Integers Sum up to Zero
longest-happy-string
Given an integer `n`, return **any** array containing `n` **unique** integers such that they add up to `0`. **Example 1:** **Input:** n = 5 **Output:** \[-7,-1,1,3,4\] **Explanation:** These arrays also are accepted \[-5,-1,1,2,3\] , \[-3,-1,2,-2,4\]. **Example 2:** **Input:** n = 3 **Output:** \[-1,0,1\] **Example 3:** **Input:** n = 1 **Output:** \[0\] **Constraints:** * `1 <= n <= 1000`
Use a greedy approach. Use the letter with the maximum current limit that can be added without breaking the condition.
String,Greedy,Heap (Priority Queue)
Medium
778
709
what's up guys welcome to tech grant do like and share the video subscribe to the channel and watch out for the data structure beginner playlist so that if you are new to the data structure you can learn something from there so here we need to solve the problem where we are given a string and we need to convert it into lowercase and return the same string in the lowercase and basically they are they want us not to use any library function and we have to convert it into the lowercase so the easiest way to do it is to go through the ascii value of each of the character that we have so if the character is an uppercase character you need to convert it into lowercase by adding something to it and that something will come from the ascii table let me quickly go to ascii table from google i just got it from one side so here if you see a the capital a starts at number 65 the decimal number is 65 and z it reaches at 90 and the small a it starts at 97 and the capital z it ends at 122. so if you see the difference between the capital and the small letter is 32 basically you add 32 to 65 you get 97 you add 32 to 66 you get 98 so the difference between these are of 32 so if i get a capital letter here so if i add 32 to that character to the ascii value of that character i will get the lower case value so that is what we are going to implement here so what we can do is we can convert the current string into uh into a into character array basically and then that character array can be further converted into string so we will say care array which will be my result so this result array will be new car array of sdr dot length and we will have a count which will be zero initially and we'll keep on incrementing it for each of the character that is encountered now we will have a c which will come from this string so str dot to get we convert it into can array and then we will see if this c is greater than equal to a and this c is less than equal to z so if it is between a to z in that particular case so in that particular case we have a capital letter coming in means we have a capital letter in this string so if it is between these two so what we will do is we will when we create our results so result dot count so this array will be a care so it will be c plus 32 so we'll simply add 32 to this character so if it is a will add 32 to it will become small a otherwise the result will be result of the count this is equal to c whatever care we have if it is not between these two so it means that it is a lowercase uh it is lowercase by default and will say so that is how we have this character array built up and since we have to return string so when we return we will say new string for this result and that's it so if i run the code so that is how this hello got converted into this hello so we'll submit it so that's it for this video see you in the next one take care bye
To Lower Case
to-lower-case
Given a string `s`, return _the string after replacing every uppercase letter with the same lowercase letter_. **Example 1:** **Input:** s = "Hello " **Output:** "hello " **Example 2:** **Input:** s = "here " **Output:** "here " **Example 3:** **Input:** s = "LOVELY " **Output:** "lovely " **Constraints:** * `1 <= s.length <= 100` * `s` consists of printable ASCII characters.
null
null
Easy
null
31
hey everyone welcome back and let's write some more neat code today and don't forget to like the video it supports the channel a lot today let's look at leak code 46 permutation and this is more of a math problem than it is actually like a coding problem which makes it kind of difficult so we're given an array of numbers a list of distinct numbers and we want to return all possible permutations and lucky for us we can do that in any order we want so in the first example we have one two three every single permutation is listed every single permutation is unique as well now what even is a permutation if you look at this array it has three values right three unique values how do we know how many permutations we can even make from that well it's a math problem right so we have three positions we know that in the first position we can pick any of these three values so we have three choices in the second position since we already chose one of these values now we only have two values left so in this position we can pick two values in the last position we know there's only one value left remaining so we do that and so it's three times two times one so it's six permutations that we can make and looking at the result there are exactly six so that's a little bit of like the math background if you want to solve this problem on pen and paper it's actually not that bad right because let's say we have like a decision tree type thing in the first choice if we're picking the first value we have three choices right we can pick one two or three in the second if we pick a one then we don't we can't pick a one again so we can pick a two or a three lastly if we pick a if we picked a one and a two then we can only pick a three here we can pick a two and i'm going to repeat that for the other examples as well and lastly we picked a three a one so we can do a two here and here is the opposite we can do a one so this is the decision tree but how does this help us if you notice these are the permutations right one two three is the first permutation next one three two is the next permutation and we could just keep doing this all day right three two one is the last permutation so solving this problem on pen and paper is actually not that bad but writing the code to do it is a little bit more difficult and i'm gonna show you the algorithm to do that so initially we have our input array right with three values the first thing i want to do is say okay let's say i got rid of this one and i just want you i just want the permutations of these two values then i can go down my decision tree down here and i can now start getting all permutations of two and three so i took this big problem right we had three values here i took it to a sub problem where now we only have two values and i want to take it one step further we have two values i'm gonna get rid of this two and now i want all permutations of this three so i'm going to go down my left decision the left subtree one more time and now this is the base case clearly we can't really go any further there's nothing left all permutations of three are just gonna be three so now we're actually going to go back up our decision tree this was the base case right with just one three and we got rid of the 2 remember so we have to add it again so we'll add it to the end of this list so it's a little messy visually but the new list is going to be 3 and 2 right so that's one permutation of two and three so i'm just going to put it over here three and two and we can repeat that process so we already looked at this case now we want to look at the case where we find all permutations of 2 so we can get rid of this 3 and then we're going to go down our right subtree and again we get to a base case so we're done with this value and so in our code recursively we're going to go back up and we're going to remember that we've removed the 3 so we're going to add it back to our list and then you can see we have two values in our list still two and three so i'm just gonna put that down over here two and three so these are the two permutations we got with these two values and one more time we're going to return back up we remember we removed this one as we were going down our left subtree so to each of these two lists we're gonna append a one we're gonna add it to the end so a one here and a one here so now so far we found two permutations we can add that to our result now so one permutation is three two one two three one so this is like the main idea this is what we're going to be doing as we repeat the process for these other subtrees and then recursively as we compute like the sub problem as we get permutations of smaller and smaller lists we're going to take those permutations return them back up to the result and then we're gonna add them to our result here and at the end we should have six of them and we can return that okay so now let's write the code and i'm gonna do this recursively because it's like a backtracking solution so the first thing i'm gonna do is have our result and it's gonna be a list and the next thing you wanna take care of recursively is always the base case and our base case is if the length of nums is equal to one if there's only one value then it only has one permutation obviously so we can return that and we have to return it as a list of lists right because if you look at this third example they pretty much hint to you even if you have one value it's going to need to be a list of lists so i'm going to take this list i'm going to take nums and i'm going to make a copy of it the next thing we want to do is we want to go through every value in nums so we're going to take the first value and pop it off so we're going to say nums pop zero so pop the value at the zeroth index and if you look at the visual explanation that's what we're doing here right we took the first value and we're popping it off and then we're going to get the permutations of these two values so perm mutations of so this is the recursive call and we're gonna pass in nums which now is gonna have two values instead of three so next we're gonna go through each permutation so for example if we had two and three and we had three and two to each of these we want to append the first value that we just removed which in the first example would be one so we're going to append one and then we're gonna have two permutations we're gonna take these permutations and then add them to our result lucky for us in python if you want to add multiple values to a list or an array you can just call a function result.extend result.extend result.extend the perms the permutations that we just got and you don't want to forget to clean up what we just did we took our array and we removed an element from it so we can't forget to add that element back except this time it's going to be appended at the end of the uh of the array last but not least once our loop is done once we've gotten all permutations we can return the result and now this time really not last but not least don't forget your typos i forgot my s and now it should work so this is kind of slow right it's slower than usual did we make a mistake well let's just cheat a little bit and use a neat little trick instead of nums dot copy i'm gonna do some python stuff and this time it's gonna go much faster so this time it's 86 i hope this was helpful please like and subscribe to support the channel it helps out a lot and i'll hopefully see you pretty soon
Next Permutation
next-permutation
A **permutation** of an array of integers is an arrangement of its members into a sequence or linear order. * For example, for `arr = [1,2,3]`, the following are all the permutations of `arr`: `[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]`. The **next permutation** of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the **next permutation** of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). * For example, the next permutation of `arr = [1,2,3]` is `[1,3,2]`. * Similarly, the next permutation of `arr = [2,3,1]` is `[3,1,2]`. * While the next permutation of `arr = [3,2,1]` is `[1,2,3]` because `[3,2,1]` does not have a lexicographical larger rearrangement. Given an array of integers `nums`, _find the next permutation of_ `nums`. The replacement must be **[in place](http://en.wikipedia.org/wiki/In-place_algorithm)** and use only constant extra memory. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[1,3,2\] **Example 2:** **Input:** nums = \[3,2,1\] **Output:** \[1,2,3\] **Example 3:** **Input:** nums = \[1,1,5\] **Output:** \[1,5,1\] **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 100`
null
Array,Two Pointers
Medium
46,47,60,267,1978
623
hey everybody this is Larry this is day five day 55th day of October hit the League Cup what hit delete Go Button hit the Subscribe button uh hit the like button hit the Subscribe button join me in this car let me know what you think about today's pop add one more to chewy okay so given a word and two integers why in debt add a row okay that seems pretty straightforward right in theory or you know I mean obviously these things I'm just initially talking about the idea um okay um I'm trying to think whether it makes more sense to do it um you know with a queue or a stack it doesn't really matter to be honest it's just about order right so let's do it I but these Farms I like to do them especially on stream recursively because I think that is in the spirit of binary trees in general and just kind of figure out that structure and kind of practice for recursion kind of talked about a little bit yesterday if you want to get back to that but uh so let's get started so we go okay let's just say rabbit reverse function we have a node and we have adapt right uh okay well we need to name it something else uh maybe left tap left so left um okay well if node is none then we return is that true um I will play around with this remember to test this I guess uh the reason why I'm thinking is that I don't know if I want left to be zero first like should I check that and I've noticed none then do we still create it like do we create leaves here they don't have any examples where that's true so we'll remember to test it hopefully okay and then here we just go towards know that love Love minus one two verse no that way left minus one right and of course if left is equal to zero that's when we do the good stuff and then we return otherwise we just do the traversion uh traversal right we have left is equal to zero then this is the debt that we wanna we move probably say uh maybe it's we're off by one but that's the idea the name is that note that left and we're gonna We want to update node.11 know that We want to update node.11 know that We want to update node.11 know that right sound like I got a stroke um and how we do that is just create a new node right and at the way again we want to return um do we insert so we choose depth is equal to one we actually um have a new root right so okay so in that case what I like to do is kind of the same thing as we have um in uh in a uh what you call a linked list right so new root is you go to tree node of negative one uh left we can just set it to the new the root right and then we just Traverse new root uh dab and then otherwise return new root dot left I think that's basically the way that we'll do it and here we what we want to do is create a new tree note with the value well right and then actually yeah the left note is note that left and the right is not that right since that's in the API that I'm just looking here in case you're wondering and then oh huh you can't do that can you I mean you can but the thing is that this is creating a new note but you want your parents to click uh to connect to it right so maybe you have to do something a little bit smarter meaning that left is equal to one what happens when love is equal to one that means that we want to insert the next level so then that means that um that means that uh this is a little bit yucky but imply we could do to clean this up a little bit but yeah and you can also depends how you want to do it because you can also return the tree node so let's maybe do it that way so we turn none uh otherwise uh let's see yeah and then return no right no dot left because you've got to treat this no dot right as you go to this then here then we can just return the new tree node if this is zero um yeah then we don't even have to be cursed anymore we just return a new tree that has that and this is roughly right maybe I'm wrong let's see I could be off by one as well obviously uh type we price anything maybe I delete something back because I need more visuals isn't it like a visualization button I thought there's like a visualization for trees back in the day something like this but you could do it for the answer as well right or did I misremembered it um I said I'm definitely missing a lot of stuff so this is the input so we have four to six and then it goes four one which actually starts off okay but um what am I missing I mean to one and the 315 is okay but then I lost a no two and six oh because I lost the note I just kind of replaced the note of the device okay let me rethink this a little bit so we want to return the new node which is this one but actually we want if left is because let's do left is equal to one then I think maybe that's a little bit easier again um is that true I don't know but yeah we returned a new tree note in which um so yeah the new tree though no it's going to be okay something like this I guess it's still like this no left is gonna know that left this is a little bit yucky we might clean it up later maybe we're not maybe we're lazy but yeah and then here we want to know that left as you go to tree node of Ryu um no left dot left node right dot uh no left dot right oops of course this is actually not super accurate yet because no that this can be none right so yeah uh yeah that's another Jackie but if this is none then this was just for an hour I mean otherwise yeah all right we'll fix that in a second but the autocomplete is still messing with me lucky dude it's not for contest so I don't care if I say also just okay and then now we turn No it should be okay we just have to check if node left is not none I think this is actually sufficient Maybe well I mean it's sufficient would be the right one this is not right of course only real quick hopefully no exceptions no exception this should be right I was wrong okay huh I'm still doing it what am I doing can we do a new node and a note that left what is this even corresponding to right so 1 is equal to three why do I do that so if node left is equal to one we return a new node in which the we upgrade to child right so why is that wrong note that left is equal to new why is this wrong huh oh because we don't have an else statement Maybe if no doubt left is none then no that left would still be none so you don't update it well today I'm a little bit not good do I have to do this because no I don't think so I think this is fine right hmm so at four we I mean the thing that I'm trying to figure out is because we actually lost another trade if I'm off by one you still have all the nodes but we just straight up lost the 206 and we replaced them by uh ones which is not great I'm clicking here you know if you can see but why is that so let's say we're at the four node and so this is where we have a four node right so maybe we can confirmed this by Queen node.walior I'll put what that's the output yeah okay so I just want to confirm our hypothesis that so otherwise you know um if they're not confirmed then that's bad okay so one and four and two is what we expect so that's good then okay so then node we return to four that's fine we create a new node of one that's true but then why is What happened to the oh no I misunderstood there should be no doubt left and this is none because we uh okay I mean I think I just misunderstood it a little bit yeah something like this is fine I mean you know we're gonna clean it up in a second I just want to see if this is right okay I misunderstood I didn't misunderstand I just kind of uh these things are hard just like doing the same thing with linked lists right is that when you're manipulating these pointers if you're not in a state in which you can keep everything in your head draw it out I didn't draw it out this time and that's why it took me so long to realize what I was doing um but yeah but actually I think you can even just do this really right I think this should be right and that's there's some like weird uh actually I guess technically this is unpredictable but maybe this is not I don't know that is guaranteed that this uh execute force or whatever but yeah maybe that's okay maybe I'm thinking of something else though cool um 918 day streak just looks pretty okay this is going to be linear time linear space um and by linear space I mean of H where H is the height of the tree or maybe even depth the minimum of those two um and we look at each note that mode most one so yeah actually we forgot to test this I got too confusing well now because I don't if enough is equal to zero we have to remember test this but I actually forgot to make That explicit or just delete the comment uh cool that's all I have with this one hope you enjoy watching me struggle on the road to be okay poem but uh the understanding was should be okay right like I don't think there's anything too hard to understand what they're asking now doing it as you can see it's a little bit trickier but hope you uh hope you did it okay I think if you don't try to be too smart like I maybe tried to do um I think you know a straightforward approach is flying because I mean I try to be too smart kind of all this stuff I think if I just did what I did before without the return node I think that would have been fine too like for example um I just did like I think I had this in the beginning so I just do this I think this would also be right it doesn't really change anything uh well now I now is wrong because I have this but this is the only time you really do an assignment anyway but uh website to subscribe thank you yeah so it should be good anyway um that's all I have for today let me know what you think stay good stay healthy to good mental health have a great rest of the week and I'll see you later um oh yeah uh what are you gonna say well what I was going to say is that uh for my uh I don't know that I hope I'm saying it uh well yeah it's what I mean to say is that is especially you know in New York there's a lot of people celebrating so well is that the way but huh because I know that is like a an atonement type thing I don't know okay well look I mean well I don't know the right things to say so maybe I should have done a little bit of research instead of uh of Yom Kippur like I don't think you say you know happy or whatever right I don't know anyway ah anyway I hope everyone who is celebrating or observing the Yom Kippur is having a good day and Etc I man I should tell a little bit more research there but and my you know my heart is to I'm making an attempt so my apologies if I'm butchering it a bit so yeah anyway I'll see you later and have a great rest of the week bye
Add One Row to Tree
add-one-row-to-tree
Given the `root` of a binary tree and two integers `val` and `depth`, add a row of nodes with value `val` at the given depth `depth`. Note that the `root` node is at depth `1`. The adding rule is: * Given the integer `depth`, for each not null tree node `cur` at the depth `depth - 1`, create two tree nodes with value `val` as `cur`'s left subtree root and right subtree root. * `cur`'s original left subtree should be the left subtree of the new left subtree root. * `cur`'s original right subtree should be the right subtree of the new right subtree root. * If `depth == 1` that means there is no depth `depth - 1` at all, then create a tree node with value `val` as the new root of the whole original tree, and the original tree is the new root's left subtree. **Example 1:** **Input:** root = \[4,2,6,3,1,5\], val = 1, depth = 2 **Output:** \[4,1,1,2,null,null,6,3,1,5\] **Example 2:** **Input:** root = \[4,2,null,3,1\], val = 1, depth = 3 **Output:** \[4,2,null,1,1,3,null,null,1\] **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * The depth of the tree is in the range `[1, 104]`. * `-100 <= Node.val <= 100` * `-105 <= val <= 105` * `1 <= depth <= the depth of tree + 1`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
421
Ratan Tata Cars Suggestion Who Is This At The Same Time Interest Prominent Maximum Two Numbers In A Relaxed Way In Clear Flats Reader Problem Government And Jerry Tom Maximum Result Of Not Equal Numbers Gomez And Online Witnesses 100 Problem Statement Quite Simple What To Do In This We Like This To suck the limits, if the episode maximum is okay, then let's see the example. First of all, this tube 310 528 tells us what the maximum episode can be. Back to Chintu numbers, so what we did is that we allowed as many users as you can for free. We could have taken them out with a tank like this, we could have taken out the lives of as many as we can add, with pipes like this, with F-35, with lives of as many as we can add, with pipes like this, with F-35, with lives of as many as we can add, with pipes like this, with F-35, with *, so our total number *, so our total number *, so our total number of players can be whatever we can make, we have taken them out. And our maximum which we have listed in the 28th over, let us try to understand the problem statement and see its solution. First of all, we will take the fact that Bigg Boss has pores and reached cultured. It was very simple like we did in our example that we take every element. People were coming by associating each element with its morning element. They took one element and married it with all the other elements available in it and did the same with other elements as well. Send all those messages to us maximum daily and return it to us like this, so this is what we have done to maximum vitamin, so basically we have done this to Bigg Boss house also with 2 follows and our solution is but is this a matup, this is better than this. Bhi approach's dat is this chief end approach that so what is there in it, we have to use it like this 103 comments solution is this and by using that extra leadership then try doctor sachet we is this ghee tata true grid travel information that is the option and the problems of this system are quite Therefore potatoes can have 1 juice, their problems in English are basically used like to computers etc. This triad is most used for computers etc. Tube is very useful, can be removed in order to complete and spring and will use the same doctors to solve this problem. Okay, so first of all, this data structure is not a doubt, we can understand it very easily, so if it is taking time that the doctor is the teaching staff, then remove this thing from your mind, if you see the operation would have been that If how is the operation, if we are a bean mixer in this country, then their answer is always zero time, this vast two different research of those who are with us and what we have to do is that this number has been given to us, we should make it 1000 with such a number so that Whichever answer is, if we get mixed, then okay, so what do we need, meaning if we have this, okay, you should definitely be one here so that zero exam is on top, okay, such where it should depend on the punctuation mark. Next Idli should be made Butter Next Tweeted Whatever is here, if there is a forest here, then whatever should be here, only then will that forest become Corresponding Maximum And if it is made here too, then whatever ideas and values ​​are with our earth, then whatever ideas and values ​​are with our earth, then whatever ideas and values ​​are with our earth, keep doing it, we will mix it, okay So to generate this number, we should understand the basic condition that if we have a number then we need a number whose bits are exactly opposite to it so that we can generate a next number, okay but this situation is always exit. Otherwise, we will have to find some way by which we can check that whatever number we have at this position, whether there is any acid there which is exactly what we need, and if it is not there, then we will have to follow the same path. If there is any, then we should put our maximum volume on it in that container, please do the same thing, let us also clean this cigarette, first of all, what will we do, if we get it insulted in all these ranges in the try, then how is the time in searching like I only have three If it is a year old, then this is my train and it will be so that so in this I have zero here aa we need a how to restraint will be made more structurally and in this Chittor child is what to delete so tea or ko zero delete the tweet And it should have been closed, that means if this note has P0 Matka number and there was a one bit number on that note, then Amar has placed some triangle, so basically here it will not happen, if our skin is back then my Initial first plate zero, is that 200 authority, what is the caliber, zero two, here we have a UK sweater, etc., one of our modes went off, okay, now again we have sweater, etc., one of our modes went off, okay, now again we have sweater, etc., one of our modes went off, okay, now again we have zero, so we called the districts inside, then we have zero or we have zero Prasad. If we offered it and then it was made with us, now it will become the child's responsibility because if the left is always kept by someone then we made it back and then we made the child fit in it became fine, neither is it like this, it is ours, it is for free, if transferred to Batamalu houses. We have to do it at 10:00. transferred to Batamalu houses. We have to do it at 10:00. transferred to Batamalu houses. We have to do it at 10:00. How can it be done at 10:00? In the first 90 days, we will How can it be done at 10:00? In the first 90 days, we will How can it be done at 10:00? In the first 90 days, we will follow the same thing. First, the strength of Britain was already there, so we will follow the same thing. The second belt is the butt. At this time, the zero that is only 0 child that we have stitched them is not 5140, we will join one in this, we will make one again and here we have made it, now here we start pouring tea, so now we will make its zero tea and then make maps. So we have its birth chart system, then we have zero Agra, then we have got its earthquake, then it will be a tan bean shot, so by doing this, we have to get all the notes inside. In this experiment, we have got everyone inside, so what is left with us now? So, what we have to do is to check every note, whether I now have all the insides in it, I have gone for a long time in the Iqraar note, we will make such a structure, expensive 32bit, its or us, like now I have One try note, the whole try has been constructed, off all the numbers are alive, now I want to see, with this three, someone gives me a number which is next Mukesh provides, then I will go, I look at the try, I am the first, that is ok. Now I see for the first time of three it is zero ok so if what I want is its corresponding one bit ok then dip me in scar water if it does 100% in my try then if it does 100% in my try then if it does 100% in my try then I will turn to one bit and go late Whatever one was doing in this till now, I will change it to the extent of one bit, but if one does not visit in this, then what will happen to the firm at that time or what is happening with our TRAI, if our company is found closed then it will be ours. First of all, Prakrit is that in 112 because if there is skin problem in the districts then it will be targeted by Titanium But if you are not getting the audit then we will report the project to our daughter Traction that he does that and to me, the footval the number and the result we will get in letters from these pen numbers will be our maximum result and we will return it in title browser. To ask a question, I hope that I have understood the solution, but we try it in the court and in the court, there is a little more fuel. Subhash, yes, if the problem is there, then let's start voting. First of all, do not take the class. Try noting that time and What content will it have? So 49 is being asked that Shahrukh Khan's praise should be on the photo, there is even a fear of it. According to the police, it has happened that it will be a class of Thomas Train and now we want such a function. Which can set the balance of our trend, so we took 1 inch and for sexual wealth, what does it do? Passed through the lettuce stomach with a number and try not to bring meat, so now we have to install this app and come to the root. How does this happen inside, then what are we doing that if we put all the beads inside this kit, then we will take the prize question restricted, now we will take its meeting from zero to thirty first, frill shifting because he is the maximum president, so this one is the first from us, we are the thirty first. Ko Insaaf 5130 Stone Continent We have reached 800 now everything is fine ok now we know its shape last year something like this now to take out seat claim we targeted it life came and end draw so what will happen to us its bit everywhere 20 or time, then that number will be towards the left from the target, like thirty-first son, if I like thirty-first son, if I like thirty-first son, if I make her 31st left, then she will come to zero police and I will take her end, I will get 2010 from them, the demonstration was done, descendants say that now we will check. Is it in the ad that weather is an integral part of the book, should we exit or not, so we have a new note in this, meaning this is not one and to get these issues from this or I am not this and your new time on the phone, in this way we next note The ban has started till today that this is your Cancer Foundation, after completing it, we did the main function on it in which our Anjor Rathore Kunwar, the trial court has made its wi-fi enemy in the video, its wi-fi enemy in the video, its wi-fi enemy in the video, now we will do all these things one by one. Mail second together can start and electronic that something that we this side subscribe button phone number idea coach eight fort is now all our foul smell that trainer inside and mixing that we get maximum out then first of all box dross and skimming side in it 12 Maths happened and then it was turned upside down that now write the code in the middle of this to plate a lot of benefits or Ireland [ benefits or Ireland [ benefits or Ireland So everything is there that now this is our ghagra of poor people by sticking to it that till now we have forced less maximum And 10 numbers, what is the maximum ignore? Okay, so this is ours, if we click for every phone number, then quarter inch JBT and Vijay would have been dehydrated by this number in 2016, so first of all, just like we removed them from the first, then they were divorced. Will do Ramesh I love Kush thing, please subscribe us for its recipe, so now what we have to do is that its appointment is available, then our current will definitely be maximum, so what do we have to check, if its appointment is available, then it is very useful for us. Looks good, here before you patience bills to grant problem is APC situation is in power of seats that is even calculator is happening then we will need it if we technocrat the place tax then this other here was a template created with MP4 is done, please see us August Hut's 40 is not a slot, but financial points will be 90, it will be 101, so I will definitely give it. If this is a notification, then I am someone's protection, after reading Main Tujh Par Hai, make a note of the current one. Two, I am Hans Pimbu Karnataka, my father and in this, by defeating the option, he chops in this case and adds fixed deposit, at that time, she becomes a Hindu, the purpose will be only, she will be the meter, then we Pushpa and Ko, if the bread is hot, then that power is our team mates to That and we will target the lutb by wearing alum this bill so if it was 2431 then don't forget to do 12538 and one week comes down then after that when there is a request that it should have power steering that then we have declared it as P so what about this There will be some of our cloth, we will get the maximum current job. Okay, so now you have to mix it, you have to make it a suite and we have taken macrame, so I think, we have taken fast, it has happened, here we have to add lace. Do 128 religious and change is making us spend the type of F1 in long so that 251 is stored in it, then there is garlic and ginger or the Supreme Court has gone, so now let's submit it in a big way and see if this research is accepted by the court. Been accepted by you must have understood this solution and if you have any doubt then comment it definitely 100 crores thank you feel like definitely video second like button should share the video and subscribe my channel thank you for watching my video Thanks
Maximum XOR of Two Numbers in an Array
maximum-xor-of-two-numbers-in-an-array
Given an integer array `nums`, return _the maximum result of_ `nums[i] XOR nums[j]`, where `0 <= i <= j < n`. **Example 1:** **Input:** nums = \[3,10,5,25,2,8\] **Output:** 28 **Explanation:** The maximum result is 5 XOR 25 = 28. **Example 2:** **Input:** nums = \[14,70,53,83,49,91,36,80,92,51,66,70\] **Output:** 127 **Constraints:** * `1 <= nums.length <= 2 * 105` * `0 <= nums[i] <= 231 - 1`
null
Array,Hash Table,Bit Manipulation,Trie
Medium
1826
145
Have Fennel Laga Study Baikunth Chaudas Question of List Code Special Poster Colors Life Mein Entry Ok So in the last two videos I had turned on inverter free mode and ordered these ok Logic is exact same The only difference is that pre quarter What were I doing, first keep returning the value, okay, what did I do in the inverter, then return the value in the play list, and now what to do in it, I will give it in the belt, okay, by going to the last, then to the right, its okay and by going to the right, its We will do calibration, okay that is to say, we will go to the left and turn on the weather mode to the right. Okay, now very simple logic of attacks that first Victor, we will do this, let's delete why because our return time is a tractor, do American in the chapter itself. So, we will have to declare it in the lighter. Okay, now what will we do, we will see the fruit element, whether it is a tap or not. Well, how is this code running in our mind, so we are saying a thousand times that we can do it in attractive and we will use it because it is requested. This is a very easy method, okay, the easiest method among all these questions, it is very much felt by the barrister, okay in code interactive, first let's copy us, the name is very long, paste the function, okay, first we have to go into it. Reaching home on the left is good, okay in this loot and then we have to go, it has come to the right, wait, it has come to the right, and then what do we have to do, we have to back it up a bit, I am talking to you, who knows? The value of the route is a simple kurta and what to do in the end is I return it with a specific difference and let's see if it runs ok or not. Will give the complete details in the drum description. Check it. If it's ok then it's run. Submit it to Roadways Workshop. It's fine and it can hang, it's fine, so basically that was what I had to do, first declare the doctor, why because we are in the office, return it, otherwise, if you type your return, if Word opens, I will just get it printed. Have to shoot the scene, just pick up this entire statement and seat it, and do the entire code, remain active, it will come to life, okay, then the same logic will come to your house, and we are saying again and again, always to question the concept of Prince. Try to use the program from the record because otherwise you will get a lot of messages. If you do the code in interactive then if it is said that you have to do it in interactive then you can try but if there is no restriction like this combination is not there then you can do it in any If you can, it's okay, then you can do it here, it's okay because it's easy, it's okay, so like the video, share it and subscribe to the channel, it's okay, thank you.
Binary Tree Postorder Traversal
binary-tree-postorder-traversal
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[3,2,1\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of the nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
94,776
468
Hello Hi Guys Mandir Gaye Jamsetji Today Will Go Through The Sixteen Problems Validate IP Address Please Like You Don't Forget To Subscribe To R Channel Darshan Even Supposed To Check Weather And Represented In Decimal To Decimal Numbers From 500 600 800 Id Group Representing With Printed All Over In the middle and lower blood pressure that now which dynasty highway that video replay it constitutes a group of zero with single MP group using to consecutively learn to pose simplicity decide extra leading heroine ipv6 also invented a village mein azeem dozens of extra spaces and special characters Inputstream a yesterday morning examples kevin the post descendants pilot ipv4 address president this velvet ipv6 address various third one is the present and water sanitation birth number spray bottle 255 se zee tv and pilot ip address this problem latest regular expression properties the expression properties the expression properties the character dot Four groups of these and wed as vacancy detail daughters will contain only on behalf of thursday here ipv6 will have sector-56 numbers here ipv6 will have sector-56 numbers here ipv6 will have sector-56 numbers for alleged by akoland seven times for boy is just this get number one is not the condition ipv6 vivo v9 maximum 350 500 600 characters leaves means number 8 class play list ride drive regular expression on ipv4 to get the value 102 255 without reading zero vihar divider number 202 more than 90 cruise exclusive and only modi can appear at a time for regular expression of 60 numbers To 9 to the Page if you liked The Video then subscribe to the Page Complexity of Divide and Rule 10 Problem is a String Contains Three Dots It is Likely to be United for String Subha Twitter Wildlife in the Western Container Calling Veer Velvet ipv6 Otherwise Blurred ipv4 and ipv6 subir and who is the time complexity of this approach is of in the space complexities varna-vyavasth ko in the space complexities varna-vyavasth ko in the space complexities varna-vyavasth ko also in description a thanks for watching the video reply to video please like share and subscribe to channel pad media comment protein kabaddi video
Validate IP Address
validate-ip-address
Given a string `queryIP`, return `"IPv4 "` if IP is a valid IPv4 address, `"IPv6 "` if IP is a valid IPv6 address or `"Neither "` if IP is not a correct IP of any type. **A valid IPv4** address is an IP in the form `"x1.x2.x3.x4 "` where `0 <= xi <= 255` and `xi` **cannot contain** leading zeros. For example, `"192.168.1.1 "` and `"192.168.1.0 "` are valid IPv4 addresses while `"192.168.01.1 "`, `"192.168.1.00 "`, and `"[email protected] "` are invalid IPv4 addresses. **A valid IPv6** address is an IP in the form `"x1:x2:x3:x4:x5:x6:x7:x8 "` where: * `1 <= xi.length <= 4` * `xi` is a **hexadecimal string** which may contain digits, lowercase English letter (`'a'` to `'f'`) and upper-case English letters (`'A'` to `'F'`). * Leading zeros are allowed in `xi`. For example, "`2001:0db8:85a3:0000:0000:8a2e:0370:7334 "` and "`2001:db8:85a3:0:0:8A2E:0370:7334 "` are valid IPv6 addresses, while "`2001:0db8:85a3::8A2E:037j:7334 "` and "`02001:0db8:85a3:0000:0000:8a2e:0370:7334 "` are invalid IPv6 addresses. **Example 1:** **Input:** queryIP = "172.16.254.1 " **Output:** "IPv4 " **Explanation:** This is a valid IPv4 address, return "IPv4 ". **Example 2:** **Input:** queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334 " **Output:** "IPv6 " **Explanation:** This is a valid IPv6 address, return "IPv6 ". **Example 3:** **Input:** queryIP = "256.256.256.256 " **Output:** "Neither " **Explanation:** This is neither a IPv4 address nor a IPv6 address. **Constraints:** * `queryIP` consists only of English letters, digits and the characters `'.'` and `':'`.
null
String
Medium
752
210
hello friends and welcome back to another discussion on a lead code problem so the problem for today is course schedule too let's go through the problem description there are a total of n courses you have to take they built from 0 to n minus 1 some courses may have prerequisites for example to take Co 0 you have to first eight course 1 which is expressed as a pair 0 comma 1 given the total number of courses and the list of prerequisite pairs returned the ordering of courses you should take to finish all courses there may be multiple correct orders you just need to return one of them if it is impossible to finish all courses return an empty array so now let's go through the examples we have the input as to which means there are two courses and we have been given a list which contains another list and it has elements 1 comma 0 so this means you have to complete course 0 before completing course 1 and hence toutput 0 comma 1 again we can go through the explanation there are a total of 2 courses to take cosine you should have finished core 0 so the correct course order is 0 comma 1 so let's go to another example and we have four courses and the input is again a list of lists we have elements 1 comma 0 2 comma 0 3 comma 1 &amp; 3 comma 2 so 0 2 comma 0 3 comma 1 &amp; 3 comma 2 so 0 2 comma 0 3 comma 1 &amp; 3 comma 2 so that means to take course 1 you need to take co 0 before that to take course to you need to take course little before that to Pecos 3 you need to complete one before that and again similarly you need to complete the course tool before completing the course 3 so there are multiple outputs which are possible here and 0 1 comma 2 comma 3 or 0 2 1 3 both are possible here in the notice mention that the input prerequisites is a graph be presented by a list of it is not interesting see matrices it more about how a graph is represented here you may assume that there are no duplicate edges in the input prerequisites so all right we can just go through this link quickly third what we have got is a list of edges which represents the graph another way to represent the graph is an adjacency matrix here we have a mapping from each node to itself and all the other nodes and anyone in the matrix represents an edge so here this means there is an edge between 0 and 1 and similarly again this means that there is an edge between 1 and 4 and so on another B to represent graphs is adjacency lists here each node of the list contains another list which contains all the elements or all the nodes this node is connected to so here node 0 points to 1 comma 6 comma 8 that means there is a edge between node 0 and 1 node 0 and 6 unknown 0 and 8 so if you compare between these 2 ways of storing you see that the list is more compact and it uses less space so we will also try to use something which is pretty similar to lists and let's see how do we do it if you would have watched my previous video you know how should we approach this problem as this is a typical example of topological sort but I will just like to take a couple of minutes for a quick recap on how topological sort works so we discussed in our last video the first thing which we need to compute is the in degrees of all the nodes then we need the queue to store the nodes in the correct order and they'll call it them which we used was find out all the notes within degrees zero push it into the queue and then pop each of them out and keep on storing them in our that is at least once we are done with this we will keep on updating the addressing modes of the initial nodes and whenever we find that the in degrees of any of the nodes become zero will push them again into the queue and we'll repeat this process we will visit all such nodes and finally this would give us the sorted result so the only extra thing which we need to do here from the example we discussed in the last video is to construct the graph into the way which we need it so currently we have the prerequisite graph which holds only the edge list but we need to transform it into a graph which would solve our purpose we can use an adjacency list to construct our graph just modify it slightly so that we can improve its performance so instead of storing all these nodes in a list we can actually store them in a hash map for faster retrieval I will keep this part same where we are you know storing the adjacency list of each of the node so let's see how do we write the code for it so first we would need an array which would hold all the in degrees we can initialize that as new end and it will be done courses next we'll use a hashmap to construct our graph so let's write a hashmap integer and each of this value or each of this key will actually hold a list of integers graph is equal to new hashmap now let's construct this graph by the trading over the edge list so for and edges in prerequisites so here let's define a convention start and end to get a sense of the direction so in the example one comma zero means there is an edge from node zero to one and not vice versa so what we need to do here is write in start and this is actually edges one in pink and this will be H is zero so this actually means that there is a node called start and there is an edge like this so whenever we find such edges what we need to do is increase or increment the in degree of the node end so in degree of n plus now we will store this node into the graph so for that we write graph dot put if absent note start comma no hairy list so what this link means is if the graph doesn't contain the note start then we initialize it with an empty rlist otherwise if we already had a start then what we need to do is we'll have to fetch the list which it was storing in its value and append this note to it so for that will write graph dot get start this would give us the list which was present at the node start and we add the current node to it which is the end node so once we iterate through all the prerequisite edges our graph will be formed now as a second step we need the queue which again will hold integers and there are quite a few ways to initialize at you but let's use a linked list in this step what we need to do is find out all the nodes whose in degree to 0 they are our first candidates to be inserted into the queue so we'll iterate over all the courses so in I is equal to 0 I understand number courses I plus whenever we find in Big B of a node to be equal to 0 all we have to do is insert this node into the queue so we can write it u dot offered I so now we have constructed our graph we have computed the in degrees and we have also inserted the first set of nodes whose nth degree was 0 into a queue so next step if you remembered just to pull this queue and update the in degrees of the adjacent nodes for that we can write it why is not increase course is equal to Q dot Poli so this is the first course and the correct course in the ordering and we have to insert it into a result set so let's define that here so let's call it ordered is equal to the new end and again it will be num courses we also need available to iterate over it so let's define K and initialize it to zero so since we know that this course resulted correct position so we can varied order k plus is equal to course so we have our first element correctly inserted into the result list now if you remember we have to check on the edges in nodes of this list so first we can check if graph dot contains key course so now we need to update the in degree of all the nodes which were adjacent to this node so for that filter it for in node in graph dot gate course this would return linked list which will be holding all the edges in nodes of the node course so now what we need to do is update the in degree of all the edges in nodes and also at the same time check that if any of the adjacent nodes now have an N degree of zero we would need to insert those nodes into the queue Sarita eat if - - in degree of node Sarita eat if - - in degree of node Sarita eat if - - in degree of node equal to zero we'll do a Q dot of the node so at this line we are updating the in degrees as well as checking that if any of the in degrees have become zero then we'll insert that mode into the queue we are actually done with our recorded them and we can return order there's just one case which we did not handle properly we just assumed that there is a proper order possible for all the input values but let's say the input values are not correct or let's say there is no ordering possible then the way to determine that is the ordered list should not contain the total number of courses because here the ordered list will only contain those courses between which my dependency can be formed so a way to determine that is if K is equal to num courses that means all the courses were iterated and inserted into the list and when that case we need to return order else we just need to return an empty list so let's try to run this there was a type of death it works let's submit it great it works thank you guys for watching I'll try to cover one more example when topologically sort so that you can understand this concept really and also use it and apply it and other algorithms please like this video subscribe to the channel and share this video with your friends thank you
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
692
hello and welcome back to the cracking Fang YouTube channel today we're solving lead code problem 692 top K frequent words given an array of strings words and an integer K return the K most frequent strings return the answer sorted by the frequency from highest to lowest and sort the words with the same frequency by their lexicographical order let's look at an example and see what we want to do here so we have the words I love lead code I love coding and we want the top K words which is two in this case so how often does each word occur well we have I how many times does that occur two okay what about love occurs twice as well here and here we have lead code and this occurs once and coding which occurs once as well now we want the two most frequent Words which is I and Love Now we can't just stop here because we need to sort the words with the same frequency so these have the same frequency by their lexicographical order and that's just a fancy way of saying like which one would come first in a dictionary so obviously I comes before l so the return should be I and then love right so pretty simple right we just get the counts of each variable and then somehow need to just find the top K and then rank any kind of like match is based on their dictionary order so you know whenever you hear top K the first thing that you should think of is to use a heap and that's exactly what we're going to do here but I bet the solution to this is something that you have never seen before because this isn't your standard heat problem we actually need to be a little bit tricky here because we're not just dealing with the counts here we also need to deal with lexicographical order so our Heap actually needs to be a custom Heap or at least have a custom method such that it can actually handle um ordering but taking into account the count which is what we want to order on and the lexical graphical order so instead of kind of going over this in just like a drawing we've kind of gotten the general intuition we need to build a map of basically all the counts for each word and then we need to build some sort of Heap which will tell us the top elements but like I said it has to be a custom Heap because we not only need to keep track of the highest count we also need to make sure that it's in lexicographical order so when we compare two words in our Heap um operation to see which one should come first it also needs to take into account not just the count of that word but also the lexicographical order so this is where this problem solution gets very cool now let's go to the code editor and type this up because the solution is just a pretty typical Heap solution it's actually the extension to the Heap um that makes it interesting and makes it I guess even a medium or maybe even a hard question uh if you've never done this before so let's go to the code editor and type this up I guarantee this is probably one of the first times you'll ever have seen this in a leite code problem so I will see you there we went over the general intuition for the question uh in the previous segment now let's actually code this up now I told you that we need to extend our Heap by essentially having some sort of way that when you compare an element inside of the Heap it needs to take into account the count of the word and also its lexicographical ordering so what we're going to do is we're going to define a custom class called a heap item which is what we're going to put in our Heap so we're going to say class Heap item and this is going to have an init function um and it's going to take whoops uh self and it's going to take a word which is a string and it's going to take the count of that word which is an integer and obviously we're not doing anything here actually why am I typing things out it doesn't really matter uh so we have in it so we want to just say that self. word equals to word and self. count equals to count okay that's the init function done simple now what we need to do is actually Define how when you compare two Heap items inside of the Heap how is it actually going to determine which one is larger so we're going to do def D _ LT and what this means is less than so basically we are defining for this Heap item how to actually compare two elements um and then to see which one is less than and the reason that we're using less than here is because the default Heap in Python is actually a Min Heap so it looks at the smaller elements if we're using a Max Heap then we would do GT which is greater than but because we're doing a Min Heap and it Compares which element is smaller uh we need to do less than so we're going to have self and whatever we want to compare it against right um and to compare is going to be a heap item but we don't need to do all the typing so let's just say all right so for LT what are we going to do if we're going to say if our current elements count actually equals to the count of to compare do uh the count so remember to compare is a heap item and uh we're going to get the count variable right we have the count variable on each item if they're actually equal then what we want to do is simply return the word which comes first lexicographically so we're going to say return uh self. word greater than to compare uhw and when we do less than or equal to remember that it actually returns a Boolean here and it doesn't actually return the word uh and then it uses the whether or not it's greater than or less than to determine how to actually sort it so when you do LT remember that when you do like you know minus one less than 5 uh this actually returns a Boolean so that's why we need to return a Boolean here and not actually the one that's smaller um and okay so if they're equal then we want to return whether or not the current word is actually comes before um the other word right so that is going to be how we Define it if they're equal otherwise um we want to return self. count uh is less than two compare. count so basically if our current count uh is less than the count of the other one then our value is actually less than um the other one otherwise uh it's the other way around right the other value is actually smaller um and there we go so this is our custom Heap item that we're going to be using and you know this is just going to really test your knowledge of data structures can you define a custom data structure can you actually override or actually Define the you know less than comparison operator so this is a really good question for actually testing your core data structures knowledge because you know have most of you actually written and overwritten the less than comparison on a class so this will really test you in depth because the Heap part isn't that complicated anyway so we've defined our Heap item and now we actually need to use it within the context of the problem so remember that the first thing we wanted to do is actually Define the mapping uh between word and its count because we also need to populate these Heap items and put them in the Heap with that so we're going to say that uh word counts is going to be equal to collections. counter um words so now we have a map between each word and the uh count of that word then we want to Define our Heap which is just going to be an empty list in the beginning now we actually need to populate our Heap so we're going to say for word count in word counts. items what we want to do is we want to create an item for uh to put in our Heap so we're going to say item is going to be Heap item uh with the word and count Okay so we've created our item now what we want to do is we want to determine whether or not we want to put this onto the Heap or not so if the Heap doesn't have count elements into it uh sorry K elements into it uh then we just put it in there because we don't have to worry about potentially popping an element out so we're going to say if the length of our Heap is actually less than k then we can just push this element onto the Heap we don't have to worry about uh getting rid of it because we only want to keep K elements on the Heap and if we don't have K yet we can just put it in there without any worries so we're going to say Heap Q do Heap push and we're going to push onto our Heap the current item okay otherwise we have to make a decision whether or not we actually want to keep uh this element and now remember in Python the default Heap is a Min Heap so what we want to do is we want to say if the current item is actually uh greater than Whatever item is at the top of the Heap then what we want to do is we want to basically get rid of that current item because even though we're using a Min Heap we're actually going to only be storing the K elements that have the greatest frequencies so if our item actually has less um count or potentially if it's the same count but it's Lex lexicographically first then we actually want to get rid of it in favor of this better word which is our item here so if this is the case that we want to get rid of whatever is at the top of the Heap we're going to say Heap q. Heap pop uh from the Heap so that will get rid of the top element then we want to say Heap q. Heap push onto the Heap whatever our current item is so that will go through our for Loop and basically process all of our items and you know either put them onto the Heap or we make the decision that we don't want to pop them from the Heap now what we want to do is actually get our result so we have our result here and this is just going to be an empty array now we need to get those K elements um from our Heap so how many times we need to pop from the Heap K times so we're just going to say while K and we're going to say the current is whatever is at the top of the Heap so we're going to say Heap q. Heap pop from the Heap so that will give us the top of the Heap and we're going to say res. append uh the current. word right we don't care about the counts at this point we've already processed everything made sure the counts are in the correct order so we're good to get there uh and then we're going to do K minus one right so this will basically run until our K is exhausted at which point we have all of our elements in result now there's one last thing that we need to do here and that is remember that in Python the default Heap is a Min Heap which means that the top of the Heap um will actually be the smallest count so we will have all of our elements here but they'll actually be in the reverse order because we pop the smallest element first and then the next smallest until we get to the largest uh which is you know the kith element in our Heap so what we need to do here is simply return uh reversed of our result to actually get the right ordering here so let's run this make sure we didn't make any syntax mistakes and we are good to go let's submit this and accepted perfect so that is that what is the time and space complexity here so like any uh heat problem the time complexity here is going oops the time complexity is going to be n log K uh K obviously because that's the size of the Heap and N because we have n words to process here so that is going to be the time complexity for the mapping um that we built here um we are basically storing a big O of n so it's Big O of n to store all of those words and then the Heap itself is also Big O of n because you could potentially in the worst case have k equal to n which is the number of words here uh so time space complexity is 2 n but ASM totically we know that's just uh Big O of n so that is how you solve top K frequent words this is a very strange problem uh in that you probably have never created this custom class and then had to define the less than operator on it such that your HEAP would work but this is one of those problems that actually tests your knowledge of data structures uh and how you use them so one of my favorite problems for sure you can also solve this with a try but I like the Heap solution it's very cool uh but either way even if you do the try you're still going to have to define a custom class the try class and the TR node class to actually solve this I just think the Heap solution is a little bit easier to um think about it's a lot easier to code and yeah it's just really cool that you define this uh less than operator so don't just think that um it's all straightforward sometimes you will actually have to know your data structures uh to solve these questions anyway that's enough rambling thanks so much for watching if you enjoyed the video why not give it a like And subscribe to the channel really helps me grow trying to get to 10,000 subscribers grow trying to get to 10,000 subscribers grow trying to get to 10,000 subscribers relatively soon otherwise thanks so much for watching again and I will see you in the next one bye
Top K Frequent Words
top-k-frequent-words
Given an array of strings `words` and an integer `k`, return _the_ `k` _most frequent strings_. Return the answer **sorted** by **the frequency** from highest to lowest. Sort the words with the same frequency by their **lexicographical order**. **Example 1:** **Input:** words = \[ "i ", "love ", "leetcode ", "i ", "love ", "coding "\], k = 2 **Output:** \[ "i ", "love "\] **Explanation:** "i " and "love " are the two most frequent words. Note that "i " comes before "love " due to a lower alphabetical order. **Example 2:** **Input:** words = \[ "the ", "day ", "is ", "sunny ", "the ", "the ", "the ", "sunny ", "is ", "is "\], k = 4 **Output:** \[ "the ", "is ", "sunny ", "day "\] **Explanation:** "the ", "is ", "sunny " and "day " are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively. **Constraints:** * `1 <= words.length <= 500` * `1 <= words[i].length <= 10` * `words[i]` consists of lowercase English letters. * `k` is in the range `[1, The number of **unique** words[i]]` **Follow-up:** Could you solve it in `O(n log(k))` time and `O(n)` extra space?
null
Hash Table,String,Trie,Sorting,Heap (Priority Queue),Bucket Sort,Counting
Medium
347,1014,1919
380
today we're gonna be working on it code question number 300. and 80. uh insert delete and get random we can Implement these three functions uh for this randomized set class so randomized set initializes the randomizer class uh Boolean cell is gonna insert an item value into the set if not present return row if the item was not present okay that means like you were able to successfully insert false otherwise if the item was already present and you didn't do anything Boolean remove end value removes and item value from the set if present so it's gonna remove it uh returns true if the item was present for the device and get random is gonna return a random element from the current set of elements it's guaranteed that in at least one element exists when this method is called but when we are randomly selecting an element every element should have the same probability for this one we're going to be using uh we're going to be using an array list so that we can kind of using it as a set but we also wanna uh based on where it is located uh that would play a role in our algorithm so we instead of just using the set we'll be using the arraylist okay and this is going to be of integer let's call it nums the other thing is going to be the hash map which is going to be keeping record of like where it is located and uh where it is located and like what is the value so for hash map it's gonna be integer I'm gonna call it locations okay and the third one is the random one so we will call it Java dot utility dot random uh then which is going to be equal to new Java Dot okay so this is the random function we're going to be using in order to uh get basically select the random element okay when we are uh initializing it this last so inside the Constructor we're going to say initialize the nums which is going to be equal to new array list of integer and the locations are gonna be equal to new so it's going to be a new hash map uh this location basically it keeps a record of like what is the location of that number so we're going to initialize these two so when we are inserting right when we are inserting we're gonna check that weather in the locations which is a hash map does the key exist or not right so let's call that answer as contain so if it contains right if it contains if contain is true basically we're going to be returning false that we don't have to do anything it's already in there now we can't reinsert it right okay the other one would be uh locations if it does not uh in there then we're gonna put it in so we're gonna say value and the nums dot size so we're gonna take the size of these nums that how many elements we have put and so we're going to be putting it in uh and that would be the location of that we're gonna also put it into the nums oops and then we're going to Better Learning true inside the remove one again we're gonna have a very similar logic uh inside this one we're gonna have contains key uh a value we're gonna check that out okay and then we're gonna say call it uh contains contain right and then if the contain if like say it is not true right that means it was not in there in that case uh we're just gonna return the false otherwise if it was there we're gonna get the location of that let's call it location okay uh once you have the location we're gonna say that if the location is less than num start size minus 1 meaning if it is the last one if the location is the last one inside the nums right uh then uh sorry if it is not the last one because it's less than it's not equal to that if it is less than that then we're going to uh then we're going to be actually over override the last one I will make them peepee and make a peanut butter sandwich I need to eat it okay so and last one we're gonna have the last one equals to numbs not good nums dot size minus one so that's the last one right so basically we're getting the last one and then we're gonna uh override it num start set this location the value of the last one okay and then we're gonna put in that uh the last one inside that location so nums we are setting at the location we're setting the last one and the last one we are updating uh the inside the location we are updating the up over appearing the uh the location of that uh okay then we're gonna be removing it from the logs first and then we're gonna be removing it uh from the num start size minus one so we're going to be removing the last element of the nums which has to be the uh location and because we just updated that okay and then we can return true get random is quite easy it's just like we are gonna be saying that the nums.get we are gonna be saying that the nums.get we are gonna be saying that the nums.get we're going to be using our end function okay it's called the next and sorry next and we're gonna tell him what is the size of the like how uh what is going to be the maximum limit for that and it's gonna just give us a random element from the nums looking good and it works
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
3
welcome to Lee codes blind created 75 where I'll be solving the 75 essential legal questions this question is the longest substring without repeating characters given a string find the length of the longest substring without repeating characters say we're given a string like this ABC BB we want to return 3 because the longest length of any substring without repeating characters is going to be either like it's gonna be 3 it's going to be ABC BCA also accounts c a.b also counts but that also accounts c a.b also counts but that also accounts c a.b also counts but that either way all those are going to be a maximum length of three in order to solve this how could we take advantage of a hashmap so we could easily go through the entire list to find the longest substring without repeating characters if we always started at 0 if we had a hashmap that said okay have we seen a yes B SC yes and we've seen a we could just stop here and say well yeah it's gonna be three but how do we have some sort of pointer to move our substring to the point at which we can no longer count anything else so say for example we're given this string we have ABC and now we've seen a but and we've seen our lookup that we've already seen a before right well basically everything from here on out will need to be disregarded because we have a here if we want to count anything else afterwards we have to get rid of everything from the point at which the string appeared and before that so for example if we didn't have a we had B let's say we're cutting ABC and now we have B well a am b can't count anymore like from B leftward we can't consider that part of our substring because even though we haven't seen a up to this point because we're gonna have seen B that just can't be counted right so if we had like some sort of starting pointer to indicate what's the point at which we could consider it to still be a non repeating substring we could calculate that each time by you a hashmap and updating that each time we see a new character so let's start to code that out let's start with having a pointer that starts at zero as well as our max length amount and we'll initialize that to zero and we'll have a lookup table that's going to store the character as well as the index point at which it appears now we want to iterate down our string right so we'll have the index point as well as the character and enumerate string and this will make it a little bit easy for us easier for us to look up our dictionary so what's the first thing why I checked is have we seen this character before right because if we've seen this character before we need to update our start so if see in lookup well then we want to update our start point so start point is going to be equal to let's think is it'll be just the lookup character and we're actually going to add one to that and I guess we'll show you why I like later otherwise if it's not our lookup what do want to do we want to calculate our max length right so max length is just going to be equal to max of either the max length or whatever this point is right now minus the start point which starts at zero but we also need add one because if we get our index point because it's 0 indexed like say we are here at 2 and we say 2 - like say we are here at 2 and we say 2 - like say we are here at 2 and we say 2 - start port 0 that's 2 while the length is actually 3 so we have to add 1 so just keep that in mind otherwise every single time what do we want to do we have to update our lookup right so we'll just say ok our lookup for the character it was just going to be equal to I and that's great but there's one edge case that we need to remember we need to take care of so say that like here there was another a write and we already updated our start point to start at C now right because we seem B here we said all right we've seen it so we have to start at see now we've seen a and which says oh well we seen a update our start point all the way back here and that makes no sense because we've already know everything before that like we have to start here they just can't be considered the starting point anymore so we have to have one more case here to say okay well just make sure that the start point is just make sure that it's what we're greater or equal to the lookup point that we're looking at right so let me see if that's right starting point just make sure the starting point is greater or equal to the lookup see yeah and then we'll be able to update our starting point so if we finished that should be it that should give us the next length let me see if I've forgotten anything because the next point let's make sure this just works up so looks like I missed something here I want to make lookup point that's gonna go see index and we'll have plus 1 i minus start plus 1 mmm oh did I screw that up yep okay so I messed that up the starting point needs to be less or equal to the lookup that we've thought what that we have and let me think why did I make that mistake ABC will only update our starting point if it's less oh of course because it's only when the starting point is less that we want to disregard everything else right if it's all the way around we yet we run the risk of making our startup our starting point less so my mistake it should be this okay so hopefully it's pretty tricky to think of this you can almost think of it like a sliding window sort of solution but it's not exactly that because we're not popping everything up anything off it's a hash map but we're continually updating it as we move along so thank you
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
112
a binary tree is such an amazing data structure right it is formed in so many ways it can have so many variations and hence you can have so many different kind of problems on it as well right in this particular problem on lead code what you are given is you are given a sum and this binary tree has some values now you have to tell me if there is a path in the binary tree from the root node such that when you add those elements you arrive at that particular sum correct so what can we do about it let us try to explore it out Hello friends welcome back to my Channel first I will explain you the problem statement and we will look at some sample test cases next we will try to approach this problem using a Brute Force approach and see what limitations you want to encounter going forward we will solve for efficiency and try to use the level Auto traversal technique to lag to an optimal solution after that as usual we will also do a dry run of the code so that you can understand and visualize how all of this is actually working in action without further Ado let's get started let us quickly make sure that we are understanding the problem statement correctly in this problem you are given a binary tree and some Target value right and you have to determine if there is a route to Leaf path which when you add up it adds up to the Target value so what does that actually mean let us look at our first test case in our first test case you are given the fruit value and this binary tree and you have a Target value of 22 correct so you need to determine if there is a path from the root to any of the leaf node that when you add up that gives you 22. for example this is one path 5 8 and 13. you have starting from a root and going all the way to a leaf correct so in this particular test case if you travel through the path of 5 4 11 and then 22 if you add up all of them you get the value 22 correct so in this test case you can write down true as your answer correct similarly let us look at our test case number two we have a relatively smaller tree right and look at the Target value the target value is just 2. so in this tree although you have two ever node but there is no way that you can start from the root node and reach the leaf node with this target value correct because you only have two paths one and two that will give you a three or one and three that will give you a 4. so in this particular test case you will write down false as your answer now if you feel that you are understanding the problem statement even better feel free to try it out first otherwise let us dive into the solution when you start to solve this problem what is the first thing that comes to your mind what is the first approach that you can think is that okay I have to find out the path from root 2 Leaf right so what I can do is I can first of all identify all of the leaf nodes right in this particular test case I have four leaf nodes right so you have to verify that a solution to this problem exists what I can do is I can try to write down all the possible paths from root to the leaf correct so I will have one path as 5 4 11 and 7. then I will have another path as 5 4 11 and 2. and similarly I will write down all my remaining parts as well once we have got all of these paths you can just add all of them now these are all the possible sums that you can obtain from root to the leaf of this binary tree correct and you just have to verify that if you can find the target sum of 22. you can see that you are able to achieve this target sum of 22 if you follow this path correct so you can simply return true as your answer right in this case instead of 22 if it would have been 33 then no matter what path you take you cannot arrive at 33 right and hence you would have given a false Azure output correct for this solution works and it will give you a correct answer every time but the problem with this approach is it will take up a lot of time and that time will be mostly consumed when you are hydrating through this entire tree trying to find out all the possible paths think about it if you have a lot of branches then you will have a lot of leaf nodes as well right and you will have to determine the sum of all of these paths correct so that is going to take up a lot of time fertility we need to be smart about doing it so let me show you one technique how you can go about approaching this problem once again I take up my example of binary tree and okay let 22 be the target value for right now when you are finding these sums you are going from the root all the way to the leaf node right and in doing that you take up a lot of time you start from the root and go all the way to the leaf node right if you find a Target sum well good if not you again start from the root and you will try to find an alternate path to form another Leaf node if this is also not good then you will start and try to find another path right so this is where you're taking up a lot of time so what we can do is how about if we store the sum that we are getting at each of the level when we are traversing through our tree so for example when I am at my root what is the sum that I have I only have the value 5 right and that is my maximum sum now what happens when I move on to my second level I will be adding values right so 5 plus 4 will give me 9 and 5 plus 8 that will give me 13 correct so at level 2 I get the values 9 and 13 right so now if I have to travel downwards I do not need to look up what was the value I already know that if I travel down the value will be greater than 9 and I have to add more to 9 itself correct so similarly if I try to add up all of these values from 9 I go to 11 and I get a value 20. 11 to 7 I will get 27 and then 11 to 2 I get a 22. similarly on the right hand side from 8 if I go to 13 I get a value 26 if I go to 4 I get a value of 17 if I go to 1 I get a value of 18 right you can see what I'm doing over here right 5 plus 8 that will give you 13 plus 4 that will give you 70. 17 plus 1 that will give you 18. and this is how I am determining the maximum possible sum at each of the nodes correct now think like this up till now you are trying to find out all the possible paths right try to look at this problem now from a different angle for look at each level one by one at the first level you find a value 5 right and that is not equal to your target sum correct now move on to the next level at this next level you find the value of 9 and 13 right they are still not equal to your target level move on to the next level so at the third level I get these values now right 20 26 and 17. once again none of these values match your target right so similarly just move on to the last step now at the last level you get your value of 27 22 and then 18 correct now verify all of these values with the target value you can see that 22 matches right so this will tell you that okay maybe this node this is a potential candidate for the path sum you only need to verify one more condition and that is if this node a leaf node so you just need to check if this node has any child nodes if yes then it cannot be your candidate and you will have to return a false because you couldn't find any value but if you see that okay this does not have any child nodes and hence this is a leaf node so you can see that yes I found a path and you can simply return true because 22 was found similarly let me tweak this problem a little bit let us say the target value of 26 instead of 22. now think about it when I am traversing through all of my sums first of all I get a 5 this does not matter 26 then I get 9 and 13 this does not match 26 then I get the value of 20 26 and 27 right so voila you found a 26 and this matches when you verify your node you again see that okay this does not have any child nodes this is a leaf node so this can be a valid path right and hence you will simply stop over here and return true as your answer so you can see that how you're able to skip all the remaining calculations right you do not have to go through them however there is one more thing you need to take care of for example let us say this tree had one more node over here right now when you're going through the value you see a five nope does not match then you see a 913 nope does not match then you see 20 26 and 17 right you would say that okay 26 matches but now when you look at this node you see that this node has a child as well right so this will not be a potential candidate for your path firm because the complete path will be formed by adding all of these four nodes and this value will not equal to the Target sum and hence this cannot pure answer so once again you will have to move on to the last step and then once again try to compare all the values so this way you can find a efficient solution just by traversing all of these nodes only once and how do you do that let us try to understand it with a try run of the code on the left side of your screen you have the actual code to implement the solution and on the right I have a sample tree whose root is passed in as an input parameter to the function oh and by the way this complete code and its test cases are also available in our GitHub profile so moving on with the dry run first of all I have a base case that if root equals to null that means there is no path and I will simply return a false right moving ahead do you remember how we were traversing the tree we were traversing it one level at a time right so that tells you that you need to have a level order traversal technique but you have to maintain all the sums as well right in the sum at each node so this tells me that I should need two stacks one of the stack to maintain the order in which I am getting all the nodes and one of the stack will just maintain what if the sum at each of the node so I create two stacks over here one is a path stack that will contain all of my nodes and one is a sum stack that will contain all of my sums to start off things what we're going to do is we will push the value of root to both of our Stacks right so in a path stack we are actually going to add the root node 5 and in my sum stack I will just add the sum and that is 5 right and both of them are done in this step correct moving on to the dry run I will now start a while loop that will Traverse through this entire tree based upon what do I have in my stack so when I started first of all I take out both of these temporary values and I pop them from my stack I get my Note 5 and similarly I will get my value 5. both of them are popped from the stack now you will check if this node a leaf node since this node is not a leaf node it cannot be a candidate for our path sum right because it has children so moving on to the level order traversal what I'm going to do is I will take its children and put it into my stack so first I will take this node 8 and I will add it to my path stack so I added a Note 8 and then I need to add the sum as well right so I'm going to look up at this value 5 and I will add it to 8. so 5 plus 8 will give me 13 correct so you can see that I am maintaining an equivalent of the node and its sum and if you remember we were doing just that right at the root note the sum of 5 at the Note 8 the sum is 13 correct now 5 has one more child node and that is the left node so I will take this 4 and I will add it to my path stack and similarly what I'm gonna do is I will look at this value that I popped and I will add 4 to it so 5 plus 4 gives me 9 and in my sum stack I will add 9 over here so you can see how I am maintaining this relationship at every node I know exactly that okay this will be the sum at this point right so we are doing exactly the same thing that we just discussed a couple of minutes ago right now keep moving ahead you have to do a level auto travel right so node number nine should come next look in your stack now what do you have this node 4 right so pop This Out and because we have to work with our thumbnail just pop this out once again you're going to do the same thing compare if this node is a candidate for path sum because it has child nodes you are gonna add those child nodes to your path stack and you're gonna add those subsequent sums to your sum stack and then eventually what will happen if this Loop Will Go On You Will iterate through each of the node and the sum at every node correct if your sum matches the target sum that means you stop right over there and simply return a true and if you complete the loop that means you are unable to find any sum that match the target value you simply need to return a false and that will be your answer the time complexity of this solution is order of n because we are iterating through all the nodes only once and the space complexity of this solution is also order of n because you need some space to maintain both of these stacks I hope I was able to simplify the problem and its solution for you as per my final thoughts I just want to say that the level of trouser technique is very important you can realize its potential right it enables you to iterate through every node in the tree and it is also beneficial when you are trying to debug your code so the level order traversal technique will have a lot of applications whenever you are forming tree based problems I know that recursion is also a trick when you are doing tree wave problems but then it becomes very difficult to understand and visualize what is actually happening behind the scenes so there is your tip of the day always watch out for level Auto traversal technique you never know when it can become very handy so while going through this video did you face any problems have you seen any other problems where the level of the traversal technique was very handy tell me everything in the comments section below and I would love to discuss all of them with you as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also let me know what problems do you want me to follow next until then see ya
Path Sum
path-sum
Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22 **Output:** true **Explanation:** The root-to-leaf path with the target sum is shown. **Example 2:** **Input:** root = \[1,2,3\], targetSum = 5 **Output:** false **Explanation:** There two root-to-leaf paths in the tree: (1 --> 2): The sum is 3. (1 --> 3): The sum is 4. There is no root-to-leaf path with sum = 5. **Example 3:** **Input:** root = \[\], targetSum = 0 **Output:** false **Explanation:** Since the tree is empty, there are no root-to-leaf paths. **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-1000 <= Node.val <= 1000` * `-1000 <= targetSum <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
113,124,129,437,666
332
what is going on everybody it's your boy average leader here with another video and today we are tackling number 332 reconstruct itinerary as you can see this is the second most asked graph problem out there and uh in fact it's commonly asked by uber amazon twilio bloomberg facebook microsoft intuit expedia and a few other of these companies if you guys can go ahead and hit that subscribe and like button that would mean the world to me it helps my channel out a ton by giving it more exposure to people that don't know me and if you want to see another problem done just comment down below and i'll make sure to do it for you and with that all out of the way here we go you are given a list of airline tickets where tickets of index i equals from i to i represents the departure of the arrival airports of one flight okay so let me see here so we have these tickets here and then each of these inner lists represent the from in two airports so we're going from muck to lhr wherever those are um okay and we need to reconstruct the itinerary in order and return it okay that's not that too bad all of the tickets belong to a man who departs from jfk thus the itinerary must begin with jfk okay so that makes things a little bit easier we have a starting point if there are multiple valid itineraries you should return the itinerary that has the smallest lexical order when reading when read as a single string for example the itinerary jfk lga has a smaller lexical order than jfk lgb oh okay so whenever we have to break ties we need to break them such that uh we are picking like the lexicographically smaller itinerary okay and you must you may assume all tickets form at least one valid itinerary you must use all the tickets once and only once okay so this is actually a lot to unpack when reading through the problem for the first time it's actually very intimidating i'm not gonna lie but i think when we look at some of these examples it's a little bit easier to see what's going on so let's look at example one and two on the ipad so i took this example uh straight off elite code this is example number one and you know the first time i saw this problem i actually thought that because we were given this graph representation uh which you know that was a big hint uh from lead code's perspective like they gave us like a graph so it made me already think okay so we should probably start like representing this as a graph so because we had a graph from the get-go and because we had these get-go and because we had these get-go and because we had these tickets which represented uh a before and after airport like we'd go from jfk to muk and muk to lhr and whatnot uh because we had these before and after airports are almost these were you can almost look at these as like they were rules and for me if i know that i have a graph and if i know that i have a set of rules i need to follow in order to get some type of ordering i immediately go to trying to code out a topological sort for this type of problem and um you know looking at this output right here uh this actually looks like a topological ordering for this graph right here but when i go to example number two i get this graph right here and uh for those of you guys who don't know what a topological sort is i actually go much more in depth in my course schedule 2 video and when i saw this problem i also said to myself like oh wow this is very similar to course schedule 2. so that also kind of like got me thinking i need to use a topological sort so go watch that if you go if you want to learn about topological sorts and stuff but when i look at this example here i see that we have a few cycles in this graph specifically this one right here we have jfk and sfo to atl now we cannot do a topological sort on a cyclic graph topological sorts can only be done on dags or directed acyclic graph so you know my topological sort uh hypothesis doesn't really work uh in this situation so the next thing that i did was i looked at the output here and i tried to figure out how we could get this output in this order and because we're told that we have to start at jfk i'm just going to trace through this output uh with the graph that was provided to us and i noticed something pretty interesting so looking at this graph we go from jfk to atl and the and this represents these two elements in our output and then from atl we go to jfk so using this bottom arrow we go from atl back to jfk and that arrow represents these two then we go to jfk sfo and then we see that there's an arrow connecting jfk to sfo uh and that handles these two and then from sfo we go to atl and that's represented by that arrow and then atl to sfo that's represented by this other white arrow so once i realized that we can get through all of these outputs by following each of these arrows specifically in a depth first search manner i realized that this was just a dfs problem it's just a depth first search problem and that makes things so much easier because now all we have to do is you know really just implement a dfs the only thing that's a little bit different here is that this dfs goes to the lexicographically smaller node before going to the larger one or in other words if we had jfk here we see that uh we see that jfk goes to atl before we go to sfo right uh so in other words we're going to the alphabetically smaller elements here or the smaller node here so the real question is how are we going to represent our graph in a way such that we go to the lexicographically smaller element first um in a tie breaker type situation well the first thing that i thought about was okay how do we normally represent our graphs in code we normally represent our graphs like this we say our graph is a hash map where the key represents the type of each of our nodes so in this problem each node type is a string and the value is usually an array list of the type of these nodes a string and this arraylist just holds the neighbors of each of our string nodes so for instance normally we'd have uh we'd have a graph where let's say we had jfk as the key the neighbors would just be sfo and atl and just you know in no particular order if i could have put atl sfo but like it's completely random at that point so is there a way where we can hold our neighbors uh with this ordering this alphabetical ordering in mind is there a data structure that we can use that has this ordering property well if we used a priority queue instead of an array list that is our that is the way where we can get our ordering that we want so i'm going to use a priority queue and just for those of you who don't know if we stored all the alphabets in a priority queue a through z at the top of that priority queue we would have a so if we pulled at the top of that priority queue we'd have a and if we pull it again we'd have b then c and d and so on and so forth so we would have an alphabetical ordering using a graph where we store the neighbors in a priority queue so with that being said what would that graph look like it would look like this so in here we'd have a graph hash map where we have the keys jfk sfo and atl and fun fact i actually live in atlanta i live in atl so there's a little fun fact for y'all and in our priority queue because we have everything alphabetized we can store these neighbors like this so jfk what are the neighbors we have atl and sfo so i'm going to store them in alphabetical order and then sfo we have atl only so i'm going to store that here and then atl we have jfk and sfo so i'm going to store that in order because we have a priority queue here all right now we have all of our pieces right we have our graph and we know that we have to dfs from jfk and every time we're performing another iteration of death first search and when we're picking the neighbors we want to dfs on we're always going to pick our neighbor in alphabetical order so uh in jfk's case we're going to pick atl before we pick sfo so now what i'm going to do is i'm going to do uh do a dfs on jfk and using this graph that we have here and see if we can get the output that lead code has provided for us so i'm going to move this output right here and i'm going to make it a little smaller so i'm not taking up too much space all right so now what i'm gonna do is i'm also gonna have this result uh variable that's gonna hold our you know ending result here so let's do a dfs on this thing so we're told that we have to start at jfk so looking at jfk here we know we need to dfs on uh one of its neighbors either atl or sfo and looking at uh jfk in our graph we see that its neighbors are atl and sfo in that order so what we're going to do is we're going to pop off or pull an element from our priority queue that we have here so i'm going to pull atl and every time i pull an element from our priority queue that is going to represent the node that we're going to dfs onto so since we pulled atl i'm going to dfs onto atl and that's going to be our first iteration of our dfs okay so now we're at atl so looking at the neighbors of atl we see that jfk is uh the first neighbor that we can uh dfs to since and that's what's in our priority queue so we're gonna pull jfk so i'm gonna pull this and i'm gonna go back to jfk so this is gonna be the second thing that we uh that we dfs on now we're back at jfk so since red jfk again uh we see that we've already gone to atl so we can't look at that again but we have sfo so now we're going to pull sfo and we're going to go to sfo so when i do that's going to be the third thing that we iterate onto and now we're at sfo we see that sfo only has an error going to atl so acl is its only neighbor so i'm going to pull atl and i'm gonna go to atl so that's gonna be the fourth iteration of our dfs and finally uh we're at atl again so the last neighbor that it has is sfo so we're gonna go back to sfo and that's gonna be our fifth iteration of dfs now if you look at this order that we have here jfk to atl and if we just like wrote out that result we have jfk and then from jfk we're going to atl then from atl we're going to uh jfk so i'm going to hit jfk again from jfk we're going to sfo because that's our third iteration so sfo and then what's our fourth iteration we are going to atl so atl and from atl we're going right back to sfo so sfo i'm going to put right here because i'm running out of space and notice this result equals the output that lead code had provided us we're getting that same ordering now there is one big question that we need to ask ourselves and with dfs type problems i usually mess up on this particular step the question that we're going to ask ourselves is are we going to add to our results before we actually iterate to uh to the next neighbor or are we going to iterate through all the neighbors and when we recurse backwards are we going to add to our result so in other words in this case right here notice how i said okay so let's look at our iteration step so um from step one we have jfk atl from step two we have atl jfk so and that's the order that i put in it so in other words i'm i basically put it in the order uh before we iterate through our neighbors now if we coded this out we are going to get some type of error and if you said that in an interview situation hopefully your interviewer will tell you to rethink that thought maybe they'll give you a hint or maybe they'll give you a situation where that might not necessarily work out so let's think of a an example where that situation might not work out so this was an example test case that i actually failed on lead code because i added to my result array before dfsing on my nodes instead of adding after i dfs on all my notes so in other words my answer looks like this so in that situation we're going to start at jfk so i'm going to have my result variable right here and what i'm saying is uh okay so we're at jfk so before we dfs any further let's add it to our result jfk now uh we see that jfk has two neighbors we have kul and nrt and because we're going to go to the neighbor that has a smaller lexicographical number than the other neighbor we're going to go to kul now when i go to kul i'm going to add that to my results before doing any other dfs step now i'm going to check its neighbors does kul have any other neighbors no so i'm going to go back to uh jfk here now jfk does it have any other neighbors yes it has nrt so we're going to go to nrt and add that to my results now nrt does that have any other neighbors yes it has jfk so now we're gonna add jfk back to our result and we'd be done here but look at this our result has to be in an order such that our result needs to be in an order such that if we're looking at two airports side by side there needs to be a connecting flight between those two uh airports or else there's gonna be an invalid itinerary so looking at jfk to kul we see that there is a path from jfk to kul and i'm going to use another color here jfk to kul now looking at kul to nrt is there any flight that goes from ko to nrt no there's not so this would not work for us this is actually a an invalid itinerary it's an invalid result and remember what we did here was we added to our results before doing any uh dfs onto the neighbors so is there a way to combat this is there a way to get a correct answer while doing a dfs absolutely what we can do is dfs through all the neighbors and the last step that we can do before going backwards in our dfs and like kind of recursing back to a previous airport is that's when we can add our uh airport to our results and you know i think if that didn't make a lot of sense i think when you see this example you'll see that this will make some sense okay so uh i'm gonna erase some of this stuff right here okay so once again i'm gonna have my result array right here we're going to start with jfk so jfk doesn't have any neighbors yes it does it has kul and nrt and because we want to uh go in alphabetical order when we're doing tiebreakers we're going to go to kul first so we're going to go to kul now kul does it have any other neighbors no it doesn't so when we do a dfs we notice that this is the last step that we're doing here with kul before we return back to jfk in our recursive stack now since this is going to be the last time we see kul we know that we need to add this into our results at some point right but looking at this uh graph we know that there's no way that we can go back to kul once we've seen it already so since this is the last time we see uh kul and after we're done dfsing through all of its neighbors and noticing that there are no neighbors of kul that's when we're going to add uh kul into our results and we're going to add it at the end actually we're not going to add it from we're not going to add it to the beginning and then append everything else onwards we're going to add uh everything from the end and just going to keep adding to the beginning okay and you'll see why we do this after i'm done with this so now from ko kul we're back to jfk now does jfk have any other neighbors yes we have nrt so from uh jfk we have nrt so we're gonna go here now does nrt have any neighbors yes it has jfk so we're gonna go to jfk now does jfk have any other neighbors since we've seen kul already and since we've seen nrtr already we don't need to iterate through those again so right before we go back we recurse back to nrt we're going to add it to our uh result so i'm going to put jfk into our result and i'm going to iterate or recurse back to nrt now does nrt have any other neighbors to uh recur through no so we're going to add nrt to our results and now finally we're going to recurse back to jfk does jfk have any other neighbors that it has to recurse through no so we're going to add jfk to our result and by doing this is the real key to the problem appending our nodes to our results after we're done dfsing through all of our neighbors and after realizing there are no more neighbors to dfs onto and also adding to the front of our results every single time and that way we get a result that actually works so look at this jfk to nrt uh we can do that let me erase some of this real quick we see that we can go from jfk to nrt and then from nrt to jfk we can also do that and then from jfk to kul we can also do that so we're going through all of our airports we have a valid itinerary through all of our airports and we don't have an order where there's like gaps between airports like kwel to nrt we don't have that anymore so that is how we are going to do this problem hopefully that made some sense um and now let's dive into the code so first things first let's figure out what we're trying to return we it says here we need to return a list uh list containing strings so i'm going to return a list here and i'm going to call it answer and remember what we just did in our example on the ipad uh we realized that we have to add to the front of our answer every single time or we're going to add to the front of our list every single time so between an arraylist and a linked list what is uh more efficient time complexity wise well if we had an arraylist and we kept adding to the front we have to shift all those elements in our backing array to the right one to uh actually add to the front but if we had a linked list all we have to do is create a node and then like add that to the front which would be an o one time compared to the of end time complexity uh at worst case in a arraylist so what we're gonna do here is we're going to initialize a new linked list instead of an arraylist and let's also create our graph so remember our graph is going to be a hash map where the keys are going to be strings and the neighbors of each of our nodes is going to be a priority queue not a arraylist that we're so used to seeing uh and i'm gonna call it graph and i'm gonna say equals new hashmap all right so we've done that and now let's go ahead and initialize all of our nodes in our uh graph to an empty priority queue a new priority queue so for uh list string tick in tickets uh all i'm going to do is initialize each of the nodes and what are the nodes that we're actually going to store here since we're trying to store the neighbors of each of our nodes let's store the first airport because this is the airport that we're departing from and this is the airport that's going to have the actual neighbors right because like muc has the neighbor lhr here nbc has the neighbor lhr sfo here has neighbors atl and jfk has neighbors atl and sfo so we're going to want to put uh tick.get zero tick.get zero tick.get zero because this represents the you know the from airport quote unquote and i'm also going to turn off auto complete i don't know why that's on um and what am i putting with each of these airports i'm going to put a brand new priority queue and this is going to initialize a bunch of priority queues for each of our nodes and this is going to remember these priority queues represent the neighbors of our nodes and it's going to hold the neighbors in alphabetical order which is exactly what we want so from there let's actually build our graph so for and i'm just going to copy list you know string tick and tickets again and to actually build our graph i'm going to get the from and two airports okay so string from equals tick dot get zero and then string two equals tick dot get one and because i want to make a direct connection from the from airport to the two airport what i'm gonna do is grab the neighbors of the from and i do that by doing this priority queue string and i'll call it neighbor equals graph.get graph.get graph.get from and to make a direct connection from the from airport to the two airport all we have to do is add two to our neighbors and then store that back into our graph so i'll zoom neighbors dot add to and finally i'm just going to store this back into our graph along with the from airport so this is kind of like updating the neighbors of our from airport and it's kind of updating our graph and actually adding that directed edge into our graph so the output from neighbors all right hopefully i didn't spell that wrong because i always spell this neighbors wrong when i do these graph problems but okay look at that though i mean after those lines after those quick one two three four five lines we've built up our graph right here and all we have to do now is our dfs call so let's do a dfs and what we're going to do is we're going to dfs on a specific node that we passed in so the first node that we pass in is going to be our jfk and you know we need uh our answer list to actually append our values onto so i'm going to pass an answer as well and we also need our graph just so we have like you know constant access to like each of the nodes and their neighbors in our graph so with these three parameters let's go ahead and create our dfs helper method so that would look something like this public void dfs and in our dfs we're going to take in a string and remember each first parameter is going to represent the node that we're going to actually dfs on actually search on so we're going to take in node and i'm going to also take in our answer list so i'm just going to copy this in to here and finally we're going to take in our graph so i'm just going to copy this in to here all right now from here all we have to do is grab the neighbors of our node here and just dfs on that neighbor so it would look something like this priority queue a string and remember i called it neighbor or i mean let's just call my neighbors equals graph dot get note so now we have all the neighbors of our node that we'd like to dfs on and since we have them in alphabetical order we can just iterate through these neighbors and just do a dfs on them so how do we uh actually iterate through the neighbors well i'm thinking let's use a while loop here and what are some conditions that we need remember we pull from our neighbors and after we pull from the neighbor that is going to be the node that we're actually going to dfs on so at some point we know that our neighbors is going to have a size of zero so while our neighbors dot size is greater than zero and we also want to make sure that our neighbors uh isn't null because in this situation look at this all of these uh three nodes here have some neighbors right but now if we looked at example number one we dfs on jfk and then that'll take us to nbc then we dfs on nbc that'll take us to lhr and this will and once we dfs again we go to sfo and once we dfs here we go to sjc now the fir now let's pretend that we're looking at uh sjc right now the first line that we have here is we're grabbing we're doing graph.get sjc but now we see we're doing graph.get sjc but now we see we're doing graph.get sjc but now we see that sjc doesn't have any neighbors so it's actually going to return a null uh value so let's also make sure that our neighbors isn't null so while our neighbors does not equal null and our neighbors that size is greater than zero let's hold the first neighbor in our priority queue so string and i'll just call it two again equals neighbors dot poll stop pull yeah that's it and remember since uh we're storing all our neighbors in a priority queue this is going to be the lexicographically smaller neighbor amongst all of the neighbors that are in there and now that we have this neighbor we just want to dfs on that neighbor so dfs2 and we're going to pass an answer and graph once again and just like we did in our example on the ipad when do we actually add to our result well we add to our results after we are done dfs through all of our neighbors right so after this all we have to do is answer dot add and since we want to add to the beginning every time we're going to pass in 0 which is going to represent the index that we're going to add to and what are we going to add at index 0 well we're going to add the node that we're on right now so once we do that uh that should do it and finally uh we can just return right here but we don't really need this line but i believe that is everything that's how you do this problem so hopefully this works when i run it they ask you how you are you just have to say that oh of course i made a mistake that was pretty dumb mistake right here i just did graph and then i put in tick dot get zero new priority queue what i want to do is graph dot put tech dot get zero new priority queue so hopefully that fixed that can't find symbols one neighbor one neighbor did i spell this wrong of course i did when i tell you that i knew it i freaking knew i spawned neighbors wrong so i also did that okay sorry about that everybody so neighbors and neighbors i knew i always felt that long so fine when you're not really fine but you just can't when i rerun it oh missing a return oh duh of course so after we're doing this after we're done with our dfs see here we're adding to our answer that we passing that we're passing in here so all we have to do after this is return our answer uh list that we have up there so return answer all right let's run it and boom that is accepted let's submit it my laptop just died so yeah we see that this is accepted i'm gonna submit it now oh right look at that uh we got a runtime of five milliseconds faster than 78 of java submissions so it's pretty good uh let's talk about the time and space complexity here so looking at what we did here so we're just iterating through all the vertices and edges so that's a linear time complexity right there and here we're also iterating through all the nodes and edges but every time we go through a neighbor of uh of a node we're actually storing that edge and vertices into a priority queue and remember every time we add to a priority queue that is a uh log n time complexity so every time we do this uh we are actually inserting into our priority queue with the time complexity of log e plus v so since we are iterating through all of the uh nodes vertices and edges and since we had to add uh to our priority queue every single up on every iteration in the beginning i believe our time complexity will be uh o of i'm gonna type this out time complexity would be o of e plus v times and this would be in like parenthesis here times log e plus v uh since you know we go we have this which is like a linear time complexity for any and when we're looking at a graph since we're iterating through all the vertices and the edges and if we have to multiply uh log e plus v since and upon each iteration of us like building our graph we had to store a node and its edge into our priority q on every iteration so at the worst case time complexity our uh time complexity would be o e plus v times log e plus v and our space complexity uh is a little nicer than this since we only have a priority queue that's holding everything at the worst case it's holding all of our nodes and edges so our priority queue or our space complexity would be o of e plus v where e represents the edges and v represents the vertices and um that is it guys i hope uh you know this explanation made some sense i feel like i wasn't on my game today i think i stumbled a little bit more on my words today so i'm really sorry about that um but yeah guys i mean if you found any value from this video go ahead and give this video a like and subscribe to the channel and just let me know uh if there's any other things that i could do to improve you know i really want to make the best possible content i can for you guys so let me know if there's anything i can improve on and um if you want to see any of the problems done just comment down below and i'll make sure to do them for you and um yeah guys i hope you guys have a great rest of the day and i'll see you guys next time
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
139
hey everybody this is larry this is day 29 of the league code daily challenge uh hit the like button hit the subscribe button join me on discord let me know what you think about today's prom and today's problem is uh let's see my neck feels a little better by the way because you're wondering ah okay one week uh did i click on the one week again what is going on here uh in today's problem it is worth quick um building loading okay give me the 9mt string yes in the dictionary not an empty word 6100 segments of space okay so this team is pretty straightforward in theory um the problem is that it can have the so the problem is just try to figure out the constraint for this problem that's what i'm thinking about are there a couple of way excuse me there are a couple of ways to do it there's uh dynamic programming there's breakfast search there's that first search um and variations on between um so and which one is the right answer it really depends on the constraints and it requires a little bit of mind reading uh because i so i don't know but let's kind of do it the naive way uh with dynamic programming and then we'll figure out from there um okay so what how do you solve this as dynamic programming right well so the way to think about this as a dynamic programming problem is that let's say you have a word in this case you have apple pen apple uh you can think about uh there's a no uh a node or vertex in between each character right and now if you have all these notes there's an edge between two characters if the word is inside so for example the space that's between the before the a goes all the way to after the yi because apple is a word and similarly uh this oops this a uh this space between a to the space which after the year also has the same thing and now that you have that uh now that you kind of formulated as a graph problem now we can think well at each node can we get to the last node right so basically what we're essentially answering with this question is still a way to get from the first node here to the last node and this is you know this is a problem that you could ask recursively right uh in both directions so it depends on how which way you want to do it and what i mean by that is you can we ask this by okay it's from this problem of getting from uh left to right is still uh you know you could use the sub problem of here all the way to here which is left plus one to right so that's one formulation of the sub problem or you could get it from left to right minus one so both of them are equivalent you just have to choose one uh in this case it is equivalent as long as you drew the edges correctly and that's basically how i would solve this with dynamic programming so let's kind of uh start that so dp is equal to force times n uh technically it's not n but let's say n is the length of the string and this is n plus one and yeah and then now i'm gonna do a bottoms up though you could do it uh tops down if you like just using this formulation of recursively asking the question of can i go from left to right and then keep on you know making that interval smaller by um you know and this could be technically actually left plus k uh for some k let's say if we go to apple right uh so we could definitely do that and that's what we're going to do so that means that for each slot and what is the what are these dp states right so dp sub i is equal to the node that represents the space before the if character so in another words because uh we're using n plus one dp sub zero means for example the node that is before all the words the order the entire s uh dpf1 is the note that is before the uh sec the first index character but the second character right and so forth okay now that we have that defined just to be clear uh now we could do a folder before x in range sub from zero two uh and i know that you know i'm just writing out explicitly but from n to n plus one say and technically you could it's supposed to be inclusive you can maybe go to n plus two but when you're in the last node you don't really have to ask that question it's just to fall true right so yeah and for me i'm gonna ask this question from the beginning which is that uh yeah like i'm gonna go from left to right asking with whether there's a way to go from left to left plus uh left press k meaning the bot this version this variation of it right uh because this could also just be you know left plus k so now we go for each word to see whether we have it but first we have to do the base case of true for the oops zero is equal to true uh because why is this the base case this means that we can always reach from the starting node to the starting no which is like by definition true in the beginning you could start at the beginning right so now we just go for the words for word in uh word if uh s sub x uh and there are different ways to do it but i'm just going by s sub x uh i was gonna write starts with but let's actually be a little bit more precise which is x let's do k is equal to length of the word uh and then this is x plus k right if this is equal to word then that means that dp sub uh x plus k is equal to the db x and this is an or equal to right or maybe another way to put it just to be more precise is if this is true and dp sub x is true uh and then at the very end we can just return whether dp sub n is true uh and i'm going to do a couple of minor optimizations just because it pains me a little bit not to do them uh even though i this should be right and you know it's just performance uh and i okay not doing uh not caring about premature optimization until you get more familiar with it but uh but it just bothers me a little bit uh and one is that okay when we look at all this recurrence if dp sub x is false this would never be true right so that or yeah so that means that we don't have to care about this loop if db is four so if not db sub x uh we could continue and now that means that we could do factor this out and we know that dp sub x is true so we could just say this is true another optimization you can do is just pre cache the length of each word but i think i'm okay for now so let's uh let's run this code real quick uh looks good i think there's some base cases with empty strings or something like that uh the dictionary gonna okay uh and that should be it let's give it a submit maybe i have some edge cases but i'm okay with that okay so that's good uh so what is the complexity of this right so because of the language that i use there is some uh nuance in how to determine the running time complexity uh and maybe if i had done it in top down it would be easier to see but i don't know i think i've just keep on selling stuff top down so it's good practice for me to get back into doing things bottoms up uh but let's do the space complexity first right uh and the space complexity should be straightforward we look at dp as you go to this linear array so linear complexity or size space complexity is linear in the size of s right and in the space we don't really care about the dictionary at all and then time complexity is a little bit complicated right because we do it by himself we can count the loops a little bit and here we see that you know we do overlap and iteration outer iteration we have o of w let's just say for the number of words in the in a uh iteration and the thing is that this actually um costs stuff as well right this cost k so and what is k well k could have worst be n so another uh for each inner uh the work that is done per in the iteration and for this string comparison right and in that case then in this and if you just multiply them all together um because for each you know you could say that loud using english which is why this is easier for each outer iteration there's w iteration inner iterations so it's n times w and then for each of those loops uh you do of n work so combined it is all oops oh of n squared times w uh cool so that's all so that's the space complex oh sorry that's time complexity uh this is dynamic programming you could have also done breakfast search that first search maybe play around with those ideas uh definite search of memorization perhaps uh yeah uh let me know what you think hit the like button hit the subscribe button join uh me on discord and i will see y'all tomorrow bye
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
7
one welcome back and let's write some more neat code today so today let's solve the problem reverse integer even though this is marked as an easy question i would say that this is definitely more of a medium question and that's probably why this question has so many different uh so many dislikes but i don't think it's actually a bad problem it's definitely good when it comes to bit manipulation so we're given a signed 32-bit integer x the fact that it's 32-bit integer x the fact that it's 32-bit integer x the fact that it's 32-bit is very important here we want to 32-bit is very important here we want to 32-bit is very important here we want to return this integer x with all of its digits being reversed and the only catch here is if reversing this integer x causes the value to go outside of the 32-bit the value to go outside of the 32-bit the value to go outside of the 32-bit integer range which is this then we basically want to return 0 if that's the case because we're working with 32-bit integers if the integer with 32-bit integers if the integer with 32-bit integers if the integer overflows then we want to return 0. and this is the portion that's actually going to make the problem difficult because we are working with 32-bit because we are working with 32-bit because we are working with 32-bit integers and we cannot assume that we can store 64-bit integers or anything can store 64-bit integers or anything can store 64-bit integers or anything greater than 32-bits that's what makes greater than 32-bits that's what makes greater than 32-bits that's what makes this question difficult i think because if we just take a look at the standard procedure that we would do take the first example over here we have one two three did you know we can chop off this one's place digit pretty easily you can do that by modding this by 10. if we mod by 10 we're basically dividing this by 10 except we're getting the remainder which is exactly what we want that's how you get the ones place if i took 123 divided by 10 what would be the remainder it would be 3 of course right so then we can get 3. so with this digit we want to create a new integer right so we're going to start our new integer just being 3 right this is the result that we're returning it's going to be three let me you know write it down over here three right then another operation we can do on 123. now that we've processed this one's place we don't really care about the ones place anymore right we don't care about this three now we want to look at the next digit right so how can we basically chop this digit off well it's pretty easy you basically take 123 divide it by 10 when i say divide we're not doing decimal division we're doing integer division so when you do integer division we round towards zeros if we divide this by 10 we will get 12 because we're rounding down we're rounding towards zero so now we have 12. we're going to basically repeat that exact same step that we just did over here basically now we're going to take 12 mod it by 10 and now we're going to get the ones place which is 2 right that's the digit we were looking for so now we want to take this 2 and add it over here right now how can we do that well we have a digi we have a value three so let's take three multiply it by ten what do we get thirty right why did we multiply it by ten because we wanted to shift this three to the left by one because now we're going to take this 30 add 2 to it why are we adding 2 because that's the digit that we just computed up above right so we add 2 to 30 now we get 32 right so we've almost we're almost done reversing this integer right if you take a look over here we started with 123 we've reversed the first two digits right but now we want to reverse the last one which is one and that'll be pretty easy we'll just continue the steps that we've just done up above so then we'll at the end we'll have 321 and then we'll return that which is exactly what we wanted to do and believe it or not we can do this exact same procedure on negative numbers and it works out the exact same so that's the good thing the only downside is we haven't covered what are we going to do if the digits overflow so let me kind of explain that to you this range that we have to kind of meet oh in the description they say that if the value goes out of bounds so take a look at the left they say if it goes out of bounds from this range then return 0. now what is the value negative 2 or 2 to the power of 31 negative right negative 2 to the power 31 what is that value well you can see over here this is that full value these are the digits what is 2 to the power of 31 minus 1 this is that value so what if we had a example that looked basically was too large right what if the value was too large to fit what if the value was actually larger than the max value that we can possibly have what if the value was two one four seven what if the value was the exact same as this except plus one you can see that this is the exact same value except i added one so this is an eight instead of a seven and actually what if the input value was this basically what if the input value was the reverse of the max digit plus one right let's say this was our input value right and let's say we reversed it if we reversed it this is the reversed value up above right this is what we would get but what we know is this integer is actually too large this integer is greater than the one up above so this would not even fit into memory so we would need to return zero now how could we detect that this integer overflows without actually calculating it right because we can't have this digit is impossible to have in 32 bits so how would we detect it without actually building this number without actually taking this and reversing it all the way to here well that's the trick that i'm going to show you we actually are going to reverse this input digit by digit except for the last digit we're not going to reverse we're not going to add the last digit yet what we're going to do is once we've reversed this right we have all but the last digit we're going to check okay is this value exactly equal to this value basically all everything from the max digit except the last digit how are we going to actually get this basically we can take the max digit and divide it by 10 right because dividing by 10 we'll take the ones place digit and chop it off right so if we do that like this we're going to check okay is our reversed integer equal to this one yes it is right it's exactly equal in this case okay and then the next question we're gonna ask ourselves is okay we're trying to also we're now trying to add another digit we add the ones place digit okay so how do we know then if the resulting integer is going to be greater than this max integer up above how do we know that well all we have to do since we know that this is equal to this now all we have to do is compare the ones place is eight greater than this integer we have over here which is seven in this case it is greater than it right so then we're not actually going to take this eight digit and add it to here add it to this entire integer we're actually going to return zero immediately so that's one trick that we're gonna basically to detect if we go out of bounds and basically i just showed you the example of what we would do for positive integers the exact same is basically going to be true for negative integers except instead of checking if this digit is greater than the ones place of the max negative integer or the minimum negative integer we're not going to check if it's greater we're going to check if it's less than because this is a negative number right so that's one way we could detect if we did go out of bounds another way we can actually check is taking away this final digit right this one's place digit and taking away this one's place digit again and we do know how to do that in the code so i won't explain it but if we were comparing all of these digits right and we were comparing all of these digits and let's say we knew that yes we are about to add another digit we know for sure we're going to add another digit then what we're going to ask is or is this portion down here that i have squared up is this greater than this over here right for example over here that we have a value 2 followed by 8 different digits right so suppose this value over here that i have written over here it wasn't 2 followed by 8 digits it was a 3 0 followed by 8 0's right then we know for sure this is actually larger than this integer i have up above since we know this is larger and let's say we're adding another zero to it so now we have nine zeros then we know for sure it's gonna be greater than the max integer up above because that max integer starts with a two followed by nine digits right we know for sure this is gonna be greater so basically that's how we're going to compare it i know this sounds confusing right but to put it simply if we compare this with this up above and we know that this is greater than we know we're out of bounds and then we're going to again have to return zero i know this seems really complicated but let me show you the code and it's actually gonna be probably even more simple this is definitely why i would say this is more of a medium problem not an easy problem okay so now let's get into the code and i already wrote out the code because i think it's going to be more easy to understand if you can kind of see the entire structure written out so in most languages you can find the max integer and minimum integer in 32 bits right this is the max integer this is the minimum integer and i have those coded up above in python the math it kind of works out a little bit differently compared to most languages but i'm basically doing the with the following while loop i'm doing what i explained earlier in the video so we have our result initially zero right we're passed in some integer x so while this integer x is not zero let's continue the loop right now we're in the looping phase we're going through each digit of x what we want to do right just like i mentioned earlier we want to take x and mod it by 10. now you would you're probably wondering why can't i just take x and mod it by 10 why do i need this helper function or whatever uh basically because python is kind of dumb it does some unexpected behavior negative 1 modded by 10 should not be 9 in most cases but python is a little bit different than most languages in most languages you can just do the mod operator but we're doing math f mod to get that digit in python once we have that digit we're clear right then we want to take x and divide it by 10. you're wondering why can't we just divide it by 10 well python's a little bit weird so we're doing we're dividing it by 10 and then casting it back to an integer to make sure that we can round towards zero in most languages you won't have to do this you can just take x divided by 10 but python's a little bit weird so excuse that so then we've we have the digit and we took x and we chopped off the digit so that's good next we want to do the stuff that i just mentioned actually right so i want to take that result right we have a digit we want to add it to the result but you can see i'm doing a couple if statements before i actually execute this line down here where i'm actually taking that digit and adding it to the result right result multiplied by 10 and then add that digit which is what we discussed earlier but before i do this i have to make sure that this is not going to overflow how can i guarantee it's not going to overflow well if we take the current result and we take the max value divided by 10 why are we taking this max value up above and dividing up by 10 because we don't want to look at that last digit yet because we can't look at that last digit until we know for sure that this value is not going to overflow so we're going to compare every other digit so if this result is greater than max divided by 10 then we're going to return 0 because we know it's going to overflow regardless of what that digit is it's going to overflow because uh the result is already larger than max divided by 10. so that's one case the other case is if the result is exactly equal to max divided by 10 right if it's exactly equal to this max portion except the last digit and if that's true and if the digit is greater than 7 where did i get 7 from well basically this is max modded by 10. if you take this max integer mod it by 10 you're gonna get the ones place which is seven so if the digit is greater than seven and this previous portion executed as true then we're going to return zero so that's basically the case if the resulting integer is going to be too large the bottom if statement is the exact same thing except if the resulting integer was going to be too small if it was going to be smaller than the minimum integer we have up above so if that was the case then we'd return 0 as well and if those don't execute then we can go ahead and finally take that digit and add it to the result and then we can when once the while loop is done executing if the result has not overflowed then we can return that result so that was a lot of information but i hope that these if statements are finally starting to make sense and the good thing is once you run the code it is about as efficient as it can possibly be so i hope that this video was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
Reverse Integer
reverse-integer
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`. **Assume the environment does not allow you to store 64-bit integers (signed or unsigned).** **Example 1:** **Input:** x = 123 **Output:** 321 **Example 2:** **Input:** x = -123 **Output:** -321 **Example 3:** **Input:** x = 120 **Output:** 21 **Constraints:** * `-231 <= x <= 231 - 1`
null
Math
Medium
8,190,2238
146
hey guys has been good mrs. J sir who's not do the algorithms in this video I'm going to take a look at 1:46 LRU cache going to take a look at 1:46 LRU cache going to take a look at 1:46 LRU cache design an implemented instructor for lists recent used cash well issue support following operators get input get a key get the value of the key if it exists in the cache otherwise return -1 exists in the cache otherwise return -1 exists in the cache otherwise return -1 but set or insert the value if the key is not already present when the cache reach its capacity you should validate the least recently used item before inserting a new item the cache is initialized with a positive capacity okay I do both are for your appreciation oh one time complexity example is like we create a cache with two capacity up to first we put one in the valleys 1 okay now we go to in with 2 so the capacity is full now we get one we return 1 because 1 is in it and then we put 3 in now it's overflow right we need to remove 1 because 1 is product is get it is got and the 2 is not processed at all so we can remove 2 so the cache becomes 1 and 3 ok let's just write down example 1 2 now get to get one right so I think for the water 1 should be that the should be latest trust ladies to use now we push 3 and so to need me to be removed right something becomes that's so now have 1 3 and now we get to 2 this is 1 so we put 4 okay so for the same one is calm uh-huh get to it really same one is calm uh-huh get to it really same one is calm uh-huh get to it really get for yeah it's actually we're going to get this well of course for the key value we need to do some map I use math to be valued so how we can how can we handle the order well good thing is that for a map right 4matic JavaScript the order is kept Wow which is pretty cool so when we push a new one map that javascript keeps the order so if we put new things the order is kept push if we couldn't remove something but we need to remove right we need to find the first one well we should get against the first one from map and if we get dead one and update the order why it's obviously we could just delete it and I push the game right so actually for JavaScript this is it's so simple so this we just said the capacity is pasty this would have to caution you that we can someone get some tea if this map has to be returned this map of return in this map get killed but still come out it goes this map get the key but we need to move this one to the end so what you do is map delete key and then this map set up set it back that and then we return the power 1 and what cool Wow wait do something we put something we need to check it is over capacity or not right so if is map size if it is the map size Hoess this capacity we need to remove least use least used so how could it be that office circle we let key this man if only process one so great and matt these map and delete he so we remove the least useful and then we set this man set to Barry I think we're done we gotta wait mm-hmm okay we get to which is mm-hmm okay we get to which is mm-hmm okay we get to which is new one more with two sexes they put one object one exist okay put one four one five okay now we put one two Oh update ah this is mistake this case of update it's not always new one so okay sorry if it exists update right okay so we and because I need to set the order I need to just use the gap so now this and it exists we always update it now we could say this man okay if three now equals minus one we need to do that as we check right if not you just say please mm-hm now we need to check it doesn't mm-hm now we need to check it doesn't mm-hm now we need to check it doesn't exist can't snap this map sighs this passage we need to remove the first what the players minus 1 which means this isn't so we check the size and against the capacity if it is we need to put oh and forgot to ah we need to set the key here so I need to check you feel more you press submit great and there were accepted so that's all for this one for the time and space well actually we have a hidden we have hidden the internal implementation of this into this building map to the structure so if we get actually if you see me delete one and set delete one and sent a new line right but we don't know how the map delete cost maybe just technically I think it should be costing time here then cos I'm here so forget and put there all constant right so what it's actually what we want here custom time complexity but if they're not we're not going to use this feature like the default map which we gonna do while wiki is a use a map but with the order thing the order we need to be done by ourself right so obviously if you take a look at the array like okay for that like this as we did here when we want to get the value while it could be you be directed fetch from a map it's so it's constant it's nothing but when we get a number we need to leave the index to the previous to that to look to the top right it's like this so if we now need to move the two to the top see what we can get a first one is need to is to why we need to search for the add right to back for to search for two so how we do that well if we do in search like this is Casas linear time but of course we could store the index or stored index directly to with the map it's constant time and then you slice it so this will cause some scale in your time because I need to remove it and the append to at the end right so it's a linear time here but also okay linear time here if we store the index here we need to update the odd indexing in the map so it's still or this one constant linear time now yeah we could do yeah slice will cost linear time and then three push at the end it's constant so technically it should be linear time but you see with the internal you temptation of map we could do this constant time so what we do of course it's array is not gonna be working right for array if we insert like spy something it will cost the rest element to be indexed shifted so it's not possible so what could you use for two to means we lose the element with custom time and push to the end with constant time mmm well it's a remember we do something with custom time it should be linked ellipse rice so if we keep something like 1 2 3 like even for if you gotta remove the two we first define it we could just use this approach we store the map like the node right so we could guess search the node goodbye the map from map its node eval okay at least do something like this map with No so you could get it as discussed me and two we slice it well we will slice it we need to collect one two three right so we don't know what which one is actually we need to keep two-way one actually we need to keep two-way one actually we need to keep two-way one two-way nuke list so now we couldn't two-way nuke list so now we couldn't two-way nuke list so now we couldn't know where the parent is and where the okay where the next one is we need to add a head cool slice it and this will cost us constant time because we just connect one two three okay and now we need to move to the end we got no - need to move to the end we got no - need to move to the end we got no - so we need to collect four - four right so we need to collect four - four right so we need to collect four - four right something like this well this could be done in constant time by remembering last note right so the at the now becomes simply free not okay to use the native map we could use a linked list right and so the solution use a linked list - way to way link tool if you're list - way to way link tool if you're list - way to way link tool if you're interested please have a try and a shoe should not be that difficult okay so for one so javascript remember the map actually keeps track of the order a chi order which is very important okay so that's what this one helps you next time bye
LRU Cache
lru-cache
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`. * `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key. The functions `get` and `put` must each run in `O(1)` average time complexity. **Example 1:** **Input** \[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\] \[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\] **Output** \[null, null, null, 1, null, -1, null, -1, 3, 4\] **Explanation** LRUCache lRUCache = new LRUCache(2); lRUCache.put(1, 1); // cache is {1=1} lRUCache.put(2, 2); // cache is {1=1, 2=2} lRUCache.get(1); // return 1 lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} lRUCache.get(2); // returns -1 (not found) lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} lRUCache.get(1); // return -1 (not found) lRUCache.get(3); // return 3 lRUCache.get(4); // return 4 **Constraints:** * `1 <= capacity <= 3000` * `0 <= key <= 104` * `0 <= value <= 105` * At most `2 * 105` calls will be made to `get` and `put`.
null
Hash Table,Linked List,Design,Doubly-Linked List
Medium
460,588,604,1903
1,800
Ajay in New Delhi, member Shivani Gupta from on coding and suggestions or bunkers solution of class loss middling all exams of birth point 233 ok to jhal ki sari efforts kya hai to discuss we are discussing come watch Android our WhatsApp. After discussing, we go quickly and bring the question, okay, what will we do with it, we will also bring one thing with us and okay, quickly net it and make ghee Ray of Positivity Juice Nusrat Maximum Possible in the morning Give positive returns maximum possible early morning aa 110 2335 center stitch now semi arid and values ​​in values ​​in values ​​in love you all subscribe 2030 like I wo n't won't because we have 2030 morning here he has changed but here What if not cigarette then change here that their first morning what happened to us our first morning us life from here 080221 e want to then our first sending subsiding morning from zero to intact adulteration which was understood whose what we had 100 plus 30-day test 6 December What was six 100 plus 30-day test 6 December What was six 100 plus 30-day test 6 December What was six Like we started recreating our channel from here We have reached here our second early morning and 500 index 2502 Now this is our relationship and this second part plus subscribe channel both maximum This does not mean that you If you make then there is nothing like that which of the two would have liked the 65th texture password in the last 500 tourists and this is what you have kept as maximum possible one question early in the morning if you understood then subscribe to ok now let us discuss Take because we discuss, you can subscribe, what will you do, you will travel on your face, we have done our airways, we were our drivers, so one plate, we will keep the subscription and one, we will keep our result, which will be the final answer tips. Sonu Sanjay Mishra will like us that someone has done it to someone and if something like this happens that sex payment then it would be for you in the morning because after this what fifth space chain was formed, this structure broke just like that and Second of all, this is the minimum possible, we will get you first, that morning 's lesson must have been done, okay, I have understood this thing, I 's lesson must have been done, okay, I have understood this thing, I 's lesson must have been done, okay, I have understood this thing, I kept the time because of this, now I am dialing the phone, where are everyone dialing, I am going, some 217 Market size is open for what will enter? Hey, okay, Amit set, Am I bigger than my previous element? If I am bigger, please do it to me. Okay, then I was plus. If I am bigger, am I bigger than my previous element? Elements I 3030 Research Greater Than Twenty Vacation Need Me What Do I Add In Front Okay We Submit Or My I What Happened Plus That I Mera Plus Happened Is Not Fight Am I Bigger Than My Previous Elements Fans Greater Than Thirty Conditions for are conditions for, so what are you doing? You are the one who started making the second thing from here, then before making the second thing, I wanted to show you that we two tables, someone we two, we cannot do that, whatever you do not want to do, you How many months, who knows how many elements of yours you will make, you don't know that means how many are going to be made, so you make these multiple levels, otherwise what are we doing here, like I am here, this is a condition of mine for sure, we will go to this block. As we go in the exam, I will update my given results available. How much less time have we got so far, I have compared 6260 marks with these heroes. Who among the two has increased zero more? Trained teacher is the bigger one, so please update this. This is the only answer I have got in my sixty years and from the same time back we have mixed the stories with our name Saunf Aayi, that is, now we are scientists in cleanliness, in this time of the institute of the sixties and beans, we will come to you, the review will go, the wife will come and Now if we start the change back, then if we start the chat again, then what will become of the fan? We got the fiber from here to all of you, now I will check, again my tension came from here to here, am I bigger than my environment element in turmeric? I am elder, what did you do in front of me, I added the oil to me, then my I plus happened that the figurative dance was the previous element condition to your time, add us that no I plus happened, now we now I have no elements and I have children. So I have come back, I have explained to me till now, I have got five plus tennis 1515 subscribe now, you have to keep this in mind that you are finished, but as you come out of the crops, you will have to check back again, this is going to tone the result. If you can return it to the MP, then it is completely over, otherwise you will have to return it once Subscribe Result What will you do, this updater is 60, you must have understood that if we do it quickly then if we do more then we will get these results sequence 204 vacancies in teacher Job has happened that dot person we tow maximum gadgets in it and one we have to make int 9th me request zero we will flip for that these islands zero I don't believe in what is the length torch light plus that i plus chilli one have to do App not Darkness if they start looking from one and some Vinod Govt will be number initial first element I against we have done art in it only numbers of came this Great Dane of - numbers of came this Great Dane of - numbers of came this Great Dane of - bada hoon me kal me simply you if you do this or not like this If we want to create another news channel and do New Zealand Cricket, then first of all we have to check whether the change till now was the maximum or whatever will be made in the future will come to the maximum, so I have checked that the result will be full to 8 maths dot maths. off but some form of result and then I came back out of the fold I request that the result is done in nath dot prof and we will return and the driver will see that we can run it once quickly but this time any Roy ok and I do n't have oil yet but it is an effective answer but I can see now let's dry it quickly. Do you understand what I did? What was ours? It was only 80570 but at that time I have kept it in front of me. So we've put okay by 10 line convention so I've installed and I've started it Z2 pmpoint 551 I've set they or greater than it's previous element is 1000 500 condition what we have to do I have to do in where I am At that time, I came back, my iPad is in condition, we will go otherwise what happened from back, I Plus happened I Plus, then mine came, you had to pause it, okay, I set Thirty is Great Chapter - One by Two Minus Thirty is Great Chapter - One by Two Minus Thirty is Great Chapter - One by Two Minus minus one number phone is 2030 begin to any condition proof add me to it add time add holiday art episodes dandruff plus happened i plus happened here I have greater than it's - - - - greater than it's - - - - greater than it's - - - - 235's 10:30 235's 10:30 235's 10:30 condition is so We will be able to subscribe to this, we went to the village in this, now I was the one who used it, I showed him my result, I decided that it is the biggest till date or else - then he said till now I swear how to see, so or else - then he said till now I swear how to see, so or else - then he said till now I swear how to see, so I updated my result Gave the result updated and time boat now instead of sixty in place of this tree I have put someone I have put myself now I am creating news channel from here ok s blog you went to add lol After being cute our I plus happened Our soft fight I plus that test for Connect here Tennis Greater than 50 sweater Unfit I will add me for my private limited's four for - honored guest limited's four for - honored guest limited's four for - honored guest after 5 benefaction ₹2 crore no after 5 benefaction ₹2 crore no after 5 benefaction ₹2 crore no I will add me at both the time I am here, time complex is added, okay, then what happened I Plus happened that now if you shift great and condition to condition, then I have to remember, I have to make myself eight, time no I Plus, I have added length now ipl- 6 Loot ipl- 6 Loot ipl- 6 Loot Hello Friend Action Force We came out of look ahead follow here on this then what did I check outside, once again checked whether my result is big or my oath is still big then I came to know my Till now I swear, Gretel Doctor, so I updated my wrist wearable this last time and from here you have upvoted the answer, you must have understood the thing and that you have got it so clear, so Internet Video Bihar Point Discuss the Solution of Class Ninth of Birth Contact Us Love You Dance by Thank You to Jhala
Maximum Ascending Subarray Sum
concatenation-of-consecutive-binary-numbers
Given an array of positive integers `nums`, return the _maximum possible sum of an **ascending** subarray in_ `nums`. A subarray is defined as a contiguous sequence of numbers in an array. A subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is **ascending** if for all `i` where `l <= i < r`, `numsi < numsi+1`. Note that a subarray of size `1` is **ascending**. **Example 1:** **Input:** nums = \[10,20,30,5,10,50\] **Output:** 65 **Explanation:** \[5,10,50\] is the ascending subarray with the maximum sum of 65. **Example 2:** **Input:** nums = \[10,20,30,40,50\] **Output:** 150 **Explanation:** \[10,20,30,40,50\] is the ascending subarray with the maximum sum of 150. **Example 3:** **Input:** nums = \[12,17,15,13,10,11,12\] **Output:** 33 **Explanation:** \[10,11,12\] is the ascending subarray with the maximum sum of 33. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
Express the nth number value in a recursion formula and think about how we can do a fast evaluation.
Math,Bit Manipulation,Simulation
Medium
null
274
Hai gas welcome back to me channel and this video they are going to solve the next problem of top interview 150 So what is the problem is our index so let us see what has been given to us in this problem statement here we have one Hey Citizens of India have kept a serial where your side is representing three numbers of citations received by the researcher, on which we have to donate, what do we have to donate, now this is the definition of what is an index, it has also been defined as the maximum. Value of HA is the true date of life of the researcher. Look at the list of published papers. Here it is basically given that if any researcher has HA index, it means that he/she has published HA people, means that he/she has published HA people, means that he/she has published HA people, who has got the scientist's list first. Through the example, it is okay, so what is given here, 30165 is given, okay, what does this mean, if there is a minimum, then it will do, okay, if the maximum is found from here, then it is okay, so you have understood this much from this statement. The index that will be there cannot be your indicator, it can be less than N and that is Ericcisse, because here it is given that only N papers should be published, then here if only N papers are published by the researchers, then it It cannot be more, it must be less than that, but it cannot be more than that, so see here how, if we sort it, we have come to know who has the least, who has the most, so now see here that Zero paper, if we take ha as zero mother, then it should be from zero paper, we can give it from Mohan only, we take it from one, okay then h1n list should be one paper, whose site should be there, then such tax papers are total, so this one is possible. Okay, then let's take h3. There should be three papers which are more than the public, so there are three papers which do not have a side. There are not five papers in total, so there cannot be six. Sorry, I have shortened, not short. I did five, there will be six, then at list there should be five purposes, at list five papers are not here, now from five papers, but their side or is not more than five, which of the papers, if the side or side of all five papers was more than five, then yes. Our index could have been five but it is not here. There are only two such papers which have a side or more than five. Okay and in this case also there are six papers otherwise h6 would not be there and if it was a possibility then This also will not happen because it is not like this here. If you look here, if there are five papers suggested here and everyone's suggestion is five and six are six, then the list of five papers is such that the one whose site is or has more rights than five, then it can be five. Is it possible to have six, no, there is no six pe bus here, even if there are six packs, mother lo, there are six papers here, then along with having six papers, there should be all the atlists or will there be a six seater also? It will work but here it is five, not six, there are six papers but all the cities are not six or more than six, so what will happen here also, what will be your sanitation, yes, what will be the index, what will be five, okay next, what will be the index, what will be your five, if Mother, here you have given 100, there is only one paper, what is its citizen? If the citizen is 100, then will the agenda here be 100 or not because there is only one paper, yes, papers should be published. Hundred papers have not been published, isn't only one paper published? It is published on the same page, its side A should be more than one, it is 100, so what will be the ha index here, what will be the one, so I hope you have understood what the ha index actually is, okay Now we see that we can solve this problem also in this way, so what can we say, let us expand this example and see how we can solve it, no problem, nothing like this is given here, you see. In the first example, I have kept it like this, okay, now what is the total here, I have my total, let me reduce one message. Okay, so here N is your six, so your maximum possible can be less than six. Okay, the answer can be less than six or six. You must have understood that it will never be more than six. Now look here, what will we do, we will see how many are there in the paper, how will this help you, I will tell you first. Let us count from zero to zero one to three five six index. For this we will have to take n + 1 size and if we take all the accounts then our take n + 1 size and if we take all the accounts then our take n + 1 size and if we take all the accounts then our three count will be in five wicks. Okay if it is yours then it is not greater than one index. If you add only 6 to the count, then it is okay, then seven's value is greater. Give equals, if you are N then it will come inside your N. Okay, we will count inside this. Okay, we have done it, and we have done three together, we have done six. Now what will we do, we will start from the back. Okay, what will we do, we will start from the back now. Here you have come to know that what is N is possible, here what is this index, this is basically in the form of further index, okay, we told you what is the maximum index that can be, okay, so we will start from the back because we want to see the maximum. Yes, so let's see for six, is six possible, what is six or six sitter, how much is the paper, we will see that, six or greater than six, there are three papers, okay, but we want at least six, so this is its equal reality. It has to happen, but these two are smaller, right, so this is not possible, now if we come here, then how many papers of five scientists or with five citations are there, the ones with side distance greater than five, you got three in the previous element, this is Atlas. Look, what should we do, ha, if we find the index, then we are seeing that there should be list of papers and there should be list of all the papers, if even the gutter of all the papers will work, then the six one will also come, for this, if 5 further index is possible or not? If we have to see, then this is a spelling mistake, see yes, if we have an index, here we are looking at the possibility of whether 5 is possible or not, then for this we need to list five papers, then we will see how many papers we can have. From here, we will get three and we will take this three, we will add both, why will we do this, what is your problem, because if any three papers have a six, then it will also come that the list is greater than five, isn't it 6, or 5 second? That too will work, if 3+3 is 6 papers, then That too will work, if 3+3 is 6 papers, then That too will work, if 3+3 is 6 papers, then you have come to know that there are six papers such that what is your greater den five, it is equal to you or greater den five, still if it works then it is ≥ 5, this condition should be fulfilled. still if it works then it is ≥ 5, this condition should be fulfilled. still if it works then it is ≥ 5, this condition should be fulfilled. This means that this is possible for us, we will definitely have to look behind it, won't you because you know that from here we are moving, we are only looking at the maximum, so the more we go towards the left, the less we will get. We will return at this time, okay if we don't even get it on the story, then let's look at the first example. Okay, the first example was here, it was element 306 15, whatever it was, so now what do we do with everyone's account. Let's say its size is five, from zero to what is the possibility, what is the power. Next, the power of the index is from zero to 1 2 3 4 5. If we want up to five indexes, then we will have to take the size of N + 1. The want up to five indexes, then we will have to take the size of N + 1. The account of three should be one. Zero account will become one. Six's account will become five. Okay, then one's account will become one, then five will come. OK, what will we do now? Why will this count happen? I have told you this because you know that if there are more papers then further alliance with India cannot happen. Okay, either there can be maximum N or It can be less, so if the number of gateway elements we get is more than N, then what will we do with it, MBA will store the papers, it is okay to call the papers, now we will see how much can be our possible further index, we will see from here from the last We will see because if we want to find the maximum then 5h index is possible or not. Five next is possible or not. If we want to see that then here we will see how much paper is there, such a paper is two papers like this, okay, we should have listed five, it is not possible, okay. Now we see for four we will see for index 4 and for Now we come to three, okay, three is next possible or not, so here you are already there, that is paper tha, that is two and its index is three, yes index can be possible because there are three papers which have 3 or 3. If it is greater than , then you have three such papers, greater than , then you have three such papers, greater than , then you have three such papers, what is its separation, 33, what will you do in thermusic time, you will donate here, three ok, so what do we do, we have shown you the code is also very easy, what are we doing, first of all, take it immediately. Where we are, what are we doing, how much is the count of the possible side, meaning it is possible citizens paper is given exactly, how much is its account, if we store it, then we have taken one, vector and count and plus one, size n + 1. Because we size n + 1. Because we size n + 1. Because we need index up to n is possible, hence we will take n+1 so that we have is possible, hence we will take n+1 so that we have is possible, hence we will take n+1 so that we have index up to more in our account, now we will see the value of citation, if the value of the side is @ = n then count and value of the side is @ = n then count and value of the side is @ = n then count and plus. Will do another vice count it will do it plus okay this I explained to you now how many papers are there total they will see these papers we have taken zero now we will start from back we will add and see what papers I greater give equals tu aayi hai kya agar hai Because that might not have been your maximum possible, so I hope you would have understood it. If you liked the video, please like it and subscribe. Thank you.
H-Index
h-index
Given an array of integers `citations` where `citations[i]` is the number of citations a researcher received for their `ith` paper, return _the researcher's h-index_. According to the [definition of h-index on Wikipedia](https://en.wikipedia.org/wiki/H-index): The h-index is defined as the maximum value of `h` such that the given researcher has published at least `h` papers that have each been cited at least `h` times. **Example 1:** **Input:** citations = \[3,0,6,1,5\] **Output:** 3 **Explanation:** \[3,0,6,1,5\] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. **Example 2:** **Input:** citations = \[1,3,1\] **Output:** 1 **Constraints:** * `n == citations.length` * `1 <= n <= 5000` * `0 <= citations[i] <= 1000`
An easy approach is to sort the array first. What are the possible values of h-index? A faster approach is to use extra space.
Array,Sorting,Counting Sort
Medium
275
336
Prompt OK 200 E-mail Tum Baat To Hai Nahi Stream A Limited Check If Stream Has Started Or Not A Strange Block So Do We Like Share And We Complete's Body Will Just Tell Me That Any Disturbance Any People Volume Anti- Oxidant is the giver, Any People Volume Anti- Oxidant is the giver, Any People Volume Anti- Oxidant is the giver, all were fast, tell quickly, the voice is all clear, everything is in short and leave me to increase the volume decreases volume minute, tell quickly, to man ka manka ban gaye se mere pas telecom company, Daredevil's loot, come quickly or quickly. Please tell me and the mic is my hello that Lalit Modi and Billu are showing in it here. The mic is the volume. Now okay, I will tell people the name of this tow. From now on increase the sound coming. What about the volume and the elders, now it is fine, now it has been increased a lot because of this trick and you might appear in Lord of Noise, like this and the fan's air currents were made in which there is a clear mention, I will get this cleared after two days actually. The set up may have changed but you guys have to manage a little bit, just 2 days, this will also be fine in two days, two or one day, that blind 100 welcome back to back and finally Bigg Boss subscribe 200 final year back up delivery will be late night. Scene will be everything with help from today itself I am fine first that all that is too much now it is fine ok it is coming absolutely clear quickly tell me you are also getting some cool that I am feeling and tell me what has happened yes It's done let's start this 123 It's done and everyone's A+1 concern Very nice seven people A+1 concern Very nice seven people A+1 concern Very nice seven people watching write quickly b coming after long time and if you like it then subscribe as soon as possible hello how are you that and policy in every buddy seven people Coat Bro Lalit and Komal Anurag Festival Bakrid Stream That a little bit since BSP - It's okay to do it, little bit since BSP - It's okay to do it, little bit since BSP - It's okay to do it, everything else is shot, it's okay Pranam Sorry for lips toxins, it's okay so aloe vera juice problem today and big Her Lord of Funds that's very sweet Problem Very Sweet Very Easier Problem and Solution Ok 200 Again The Hero Rituals Are Difficult Problem Is The Problem Deep Misted The Earthen Tube Problem Then How To Do A Hi Janvi Sharma Ok Should Avoid Being Copied Quiz 2 LAC Everything In The Great Of A Wise This Question Marks Heart Attack UP Course A Very Easy Solution 282 Ok So Looking Towards Decide To Chat On Meeting Either My Screen And Camera Is Right In The Middle So Don't Get Angry Where Are You Looking This is that was ok so basically scene what wife its very easy solution but only News24 Hussain in thy soul with top badle yaar the response extra constrained andher interview under-14 used oil at that time limit acid under-14 used oil at that time limit acid under-14 used oil at that time limit acid where in square only you have to select AP is so country wise with the number adventure time space complexity that and time complexity is 442 due to use of which commissioner accident happens that's why it is only and only festival date is fixed very easily this question page of ₹ 100 So solve that this question page of ₹ 100 So solve that this question page of ₹ 100 So solve that scene that ours are different, it is okay to miss a call, so let's start that garlic battery discharge problem is life and springs are of science and okay so give one of the most runes a guest prince's bribe Having size of admission number of dreams Raghubir they found the eggs subscribe and objective withdrawal player of the year of sexual disease a list it has 24 problem come to minor page setup in interview words like and tell they will come late for this dabish in our Personal 22 Edison is a deep love and size and ok hai to a specific are his size and hoga in which will have to select two elements ok hai images of mother is bcd aisa kuch ki and from this you have to select elements where Roy plus share object Mirwaiz room is room I isi showing of more compare to coding compare to if members what Ayush Mishra want to say okay so this point is round and effective check out the in court that and output which provides to us and Then Something Like This A Good Okay Nine Wickets Out Is The Best Yes Vivo Zip Code The Original Number Kind Of Cancer If GTV's Fa A Scene From And Start Like A Baby Check Out CBI Okay So Now Comparing And Problem Controversy Check Out Speed Any two strings ok subject 123 456 sexual frustrations and solution and output set up achcha ok hai and other sports hai to like ghee with passion this is Zee TV's Eid effects of equal standing problem hai achcha ok ki problem hai is this dish app Now how is the scene that me too check out that brother the gif is in the middle that jee will see easy are equal but what is the role of this f-100 ek to hota hai brute force support f-100 ek to hota hai brute force support f-100 ek to hota hai brute force support simple sabji kaise banna hai its different use to flu run Most of the companies list possible combinations and give in which combinations you get a parent but don't know what happens. For running through all Dual Me very song ok is basically check out for land reforms in every district forest officer the wards of dow the state for string android chowk ok that now dish a plus time string will give your room and asked what will appear account one Understanding is simple, it is a simple thing that the first spring plus the second string is our third spring, which will be one of the calendars, it is true, then we will get our account, one is so clear, it is a simple thing, this is the Puranas, it is the clear so. Quickly gas ovens were a coven pass divine qualities acommerce were first ring plus se contesting from dr itself likewise should be that idea together will give me a first intro mixed ring which if and our an account closed dubai a pan Rome is ok but no ho to search out your room which suits my first ring what were to is basically select district institute ok these 250 units are ok super person looking at the filter element and electronic string then the painter mixing desired Yes, in future also Enfield will be like this Tasty Stairs Only Suji White Roaming facility Want in B.Ed Picture Partition and Share and Chilli Want in B.Ed Picture Partition and Share and Chilli Want in B.Ed Picture Partition and Share and Chilli One Then Reverse Pay Interest of all Subscribe Must drop down up the phone that Suji Mix Element Voice Less Mute Being Cheated This Paun inch is ji apan room no chief is this apan room no cheating and no different from pearl drop ki aapke to is you right participant rom yo how to search the arrest reverse of the left or right foot enrollment to left research karna hai front Part follow rom hai to right research karna hai super love you search electronics sorry for the right this subscribe to mean simple soft feb25 reverse lay on the back the present overlap is simple hai guys understood that this is the feet of Dimple Yadav nice who is intelligent I call it DC, yes, say that a few chats from the American plane, now from here, this pan of the subject, center chat show, CID, easy, simple, clear and check BSS, first key will be for the last character, basically, the first key will be for the first character, left and right meaning. If our left character is then we will search, if our at character is Panrom then we will search for left reverse. Here, in this app, we are getting the complete first step. A Trend Us Loud Angry Birds Editing The Amazing Then To Blueprint Raw Milk Contamination Hui Jaga Kar Badi Fear Not Getting It's Due Hath Ko Check Hum Politicians Beach You Can Club To Streams Where Is The Middle Character Candidate Single Character In Which Country Wear It Rome All If they are together, then either it could be that it is the WTA energy of the double face of double E or it could be that it is the double of the fans of wi-fi. If or it could be that it is the double of the fans of wi-fi. If you understand, then by which the difference is made, first do it for the whole lion. After that check, unmute the single character limit, these steps are a very simple problem, article two chords were taken, that as long as the constraint is middle hot, it is fine that I am Aishwarya fast, that your ES Swift code, no, Vinayak only will understand. And other reminder has Vitamin Vidur 131 out of which take out just a look that Ajay straight has given off the code oil explain and honest till these days only triangle will show that an inner gate and more that for Subhe Singh in this code On track courts crystal clear yes man taste a little bit bigger I from morning for that first win light look wash function so that you create the British rule in this GT Vice President will search position to take the position if the President is there then positive thinking But yes because BT doesn't want a palindrome is a single string with water contamination were so basically we just don't want this dead inside are behave screen fair remuneration this Vivo D string plus another swimsuit come to be first role understood is explained are Swiss Role by Chetan Reverse in the video Neetu and Right Palan Room Bullion FD Match Is Match Point 180 I Don't Dub Slight See Every Party Has Different Approach The Das Theek Hai Wah Completely On Accha Theek Hai Isi Bag User Actors Aishwarya Rai Bachchan and Depp Suggestions on the Bill of Development Office Second Function Congress Ruling Alliance From Abroad And What Do You Mean That Man It's OK Let A Shopkeeper Decrease A Little People Like You Sound Okay Even After Declare Android App Witch Cold Yeast Chinese Dictionary Over And what to do that Veerana for loop in this to all elements that in the form of this and wish to the existence of elements in sider dictionary app I understood simple string ji Guddu bhaiya alias aa and after that inside which we have that aa We have left everything inside our dictionary that we can deny which software this is global hand laptop what is the present inside or if day country you also have a blank posting do
Palindrome Pairs
palindrome-pairs
You are given a **0-indexed** array of **unique** strings `words`. A **palindrome pair** is a pair of integers `(i, j)` such that: * `0 <= i, j < words.length`, * `i != j`, and * `words[i] + words[j]` (the concatenation of the two strings) is a palindrome. Return _an array of all the **palindrome pairs** of_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "dcba ", "lls ", "s ", "sssll "\] **Output:** \[\[0,1\],\[1,0\],\[3,2\],\[2,4\]\] **Explanation:** The palindromes are \[ "abcddcba ", "dcbaabcd ", "slls ", "llssssll "\] **Example 2:** **Input:** words = \[ "bat ", "tab ", "cat "\] **Output:** \[\[0,1\],\[1,0\]\] **Explanation:** The palindromes are \[ "battab ", "tabbat "\] **Example 3:** **Input:** words = \[ "a ", " "\] **Output:** \[\[0,1\],\[1,0\]\] **Explanation:** The palindromes are \[ "a ", "a "\] **Constraints:** * `1 <= words.length <= 5000` * `0 <= words[i].length <= 300` * `words[i]` consists of lowercase English letters.
null
Array,Hash Table,String,Trie
Hard
5,214,2237
352
Hello everyone welcome, my channel is going to do my video number 37 of Good Story. Do n't know I think it should have been called a medium question today because when I will tell its solution either medium is fine, it should have been medium because the solution when If I tell you then you will really feel that this is medium and maybe if you understand it well then it will also seem easy. Okay, so let's see the question number. Data joint interval is fine Let's see the input output and understand what the question is. That you have to keep adding a stream update, okay, so let's see which is the first number, when the WAN came, so we added the WAN, okay, after that what it is saying is that get interval means it is saying. By doing this, break all the numbers you have till now into cute doubles. Okay, so right now I have only one number, brother, there is only one number, so what will be my answer, from van to van, I have only one number. Okay, okay, that's why see what is its output. The answer to the first gate interval on 17th is WAN. The answer to the first gate interval is OK. Called again anonymously and which number did you give in it? He gave me three. Okay, I also have WAN. And now three is also a. Okay, so let's see again, I said it is the second candidate interval. What will be the answer to this? See what I said, it should be consecutive, so one and three are a little consecutive. There is a number between one and three. It also comes, okay, so brother, van to van will remain the same and three to three, okay, you cannot merge these two, there is still a gap in between, so thoughts, our answer will be only this, which is the answer to our gate interval of 173 seconds. That will happen, this will happen, okay, now let's come to this, I have been given one more number, now I have given 7, okay, so let's see if this can still be merged, no, the merge will still not happen, van to van will remain, 3 to 3 will remain and seven. Seven will remain, no one can wish to do so, look at the third one, the next one, the gate interval which it has asked, the answer is 13 to 377 from the van, okay, this is cleared, now let's move ahead, second, what is the add number after that? Look at what you have given, pay attention to this, it is important here, this one has given me you, so let's see what can be merged, then look, van tu and three are consecutive, na, van tu and three are consecutive, so from van till 3, we get consecutive. I am sure, and after that what is 7? So 7 will remain, so our next answer is whatever could be merged, I have merged it. Okay, three and seven cannot be merged. There are many numbers in between. 45 means there is a gap. Isn't it, but van you are seeing three, if they are in the same range, then I have collected them, merged them with this, so see, the answer is 1377, okay, next number, what did it give me, next number, this gave me six, okay, now more. A good answer will come, see how you see, van tu three, it has merged, it can be from van to 3, because the just cap between the two is van, six and seven have also merged, okay, so our answer is a question, it is also easy to understand now. Let's see how we can solve this. Okay, so I have solved this with two approaches, so I will tell you both the approaches. Okay, so let's start with the first approach. So let's look at the first approach. Look, now I am obvious. First of all, I will tell you which thing I am doing, why I am doing it, why it came to my mind, it is okay, after that you can pause the video and it is okay, after that you can code it yourself, people. Pretty sir ok han I will tell you by coding but let's start with D intion look in my man he gave the most basic one ok then he gave me three then what seven did he give me after that you gave after that he gave 6 ok so remember You have to merge, when can any two things be merged when the difference between them is just van, like man, here is five, here is 3, here is that brother, this will become a range from van to tu. Look at your three, okay, so you said no, hit that three also, you can get only one range, you will also be included in it, so this will also get merged into this and the five will be separate, five from five, this is a sorted order, you are seeing the whole 123 55 What does it mean in my man that brother, get it sorted, Sam House, get your answer from him, take it man, this was the input, right 1532, I have shorted it, man, let's short it 12345, okay now I have the range. Make it simple, I = I will range. Make it simple, I = I will range. Make it simple, I = I will start from here, okay, I am making the range, now by the way, if I start from here, then I will consider it as the left of the left range, brother, this left point means the left part is the part of the range, now till the time I move ahead. I will go as long as there is only van in the differential, then as I take it, when I came here, I am seeing that ok, this is you and this van, what is the distance between the two, there is only van, which means we can make the consecutive right range now. Meaning, three can also be right range, this is left, three can also be right, coming next, is this the distance between five and three, is 1? No, there is no van, so we will not include 5 here, so I have used the for loop. When I started, I covered so many elements and the distance between them was only van. If conjunctive was formed, then left train became this, train became mine. Okay, so I became three from van, one became mine. Then next time I will start from here. Then there is nothing after five otherwise brother fiber 5 will be my answer. So you have noticed that sorting is a very simple solution and if you sort then less will be lost and one more thing which is 150. This means that its answer will change, no, from 1 to 3 and 57, so it will remain 13 and from 5 to 5, even though it is a duplicate element, neither will we reduce one nor will we keep the set. Ok, we will keep one set, there will be unique element in it. We will keep one, you three five, this is a duplicate, isn't it 5 and 3, which is repeated, we will not keep it because I will get this answer, if we want to keep the duplicate, what is the need, then we will take a set, we will remove it, okay, what did I say that I will take one set? I will take it, then what will I do with it, I will store it in one, three, five, I will sort it again, okay, we will take it out, this is simple, so you saw, we took one separately, we also took a separate set, okay Then, if we have sorted them, then first of all we are taking up space and sorting them all, which is also taking time, okay, so this is what we are doing, okay, so you have understood here. Brother O of N, we have taken the space and what is our time and people and our constraints are also not so big, so I would suggest that you solve this by pausing the video for now and I will go to the lead code and fix it. If I solve then let's court the court, let's code this in the let's code. You must have understood the question very well. What I said is that I will keep a set in which I will keep showing all the numbers. Okay, in the beginning, let's clear the set. Okay, if a new set is created for every new session, then we will clear it here. And the add is very simple, in that I just have to enter the number, I have given the number in the set, okay. Now what did I say that where will I take it in which I will give all the numbers from the set? Okay, so they take the interior and give the numbers. This is a very good shortcut to put all the numbers from the set. Indo Vesti, all the numbers given in the set, they are in this. The names are all gone, then what did I say that brother, you have to sort, and why did sort come in my mind, I also told you about the tuition, okay, I have shorted it, from the beginning and the reward, after that, obviously, we have to send the result. So let's make vector un vector of brick in which I will put the result till here it is clear and for look let's end and end it is equal tu nas dot size na fall look let's go simple as told and intaha is equal tu zero i less give And I Plus Okay, now pay attention to what I said that brother, he will take the start, this will be my start, either take the left man, he will have the left range, no, the one who will be my range will have the interval, his will be the one on the left, now I will see. I want to know till where this my range ends, so Will I &lt; I will keep searching for my right range, if I find the left range here, then I will know that if I have found the good right, then I will know the left here. They give the left part and where did the number stop? Is it ok in your result? Someone, follow this, it is very simple, you will understand it very clearly and you must have already understood what to do in the last return result. You are looking to do and just one thing that you have to pay attention to here is that look, I am adding one in the name soft i, so I am checking whether it is equal to the next element or not, we are equal to brother plus van, so now i is like that &lt; N - 1 will have to be done, the equal to brother plus van, so now i is like that &lt; N - 1 will have to be done, the equal to brother plus van, so now i is like that &lt; N - 1 will have to be done, the character will go out of down, because if I take the value of i, then it is minus one, five plus one, what will happen, if it becomes N, then it will get fat, this code is fine, I have given this check team &lt; It will be N - 1, let's run it and I have given this check team &lt; It will be N - 1, let's run it and I have given this check team &lt; It will be N - 1, let's run it and see, it should work, this is a very simple code, it is just the same as the instruction given, right, we have found out the range by shortening it, submit it and let's see, it should run, ok in this one I will tell you a small one more variation, this will be submitted first, this has been submitted, it has been solved in N people, it is ok, now tell me one thing, what did we have to do, sorting it again and again was the task, otherwise reduce it by one, we would have taken the set. What does a set do? And it keeps the numbers in an already sorted order. So, we will pick them from the set. The order will come directly from the set. This is the set which is C plus internal. It is implemented to keep the set balanced. Neither is there any operation on its inserts, so now it is just from Unlimited, so those people will also get the time from us and people, but still I am telling you, this is also a method, okay, just for your knowledge, I am telling you, nothing is hanging. So what we did here was take an ordered set and put it directly in the lamps. There was no need to sort the namas separately. Okay, but due to time complexity, I am telling you that there is no improvement, just and enhancement of your knowledge, brother. This also happens, okay, so this is our first approach, now we move ahead and see what the second one is proposed, see, this also gets solved, we move ahead and see what is our second approach, okay, now we have our second one. If you see the post then look at the other man's idea, how I built it is the same, it is important to understand the idea, there has to be some benefit in telling the solution directly, you will not forget it immediately, it is ok, so I thought that I would like to take it, I just got a number. For example, six, I got a number, okay, which was the add number of function, no, I got six in it, brother, six has to be added, okay, so think about one thing, I would like to check, which is the range which is sex. Just after which the one whose left is right is not the range whose left is nor is it just bigger than the sex i.e. is nor is it just bigger than the sex i.e. is nor is it just bigger than the sex i.e. six plus one is equal to its left, okay then it is very good, okay or so, what would I like to see in one more thing that this The range which will be just behind six means which such range is right equal to its right. If I understood this then what does it mean that it is marjible, it can be merged with it, okay, it is clear till now. If I get it then I will try to find two things which are already available with me, I will try to find two things that brother, which is the range whose starting date is on the left which is just plus one and is bigger than the value which I want. Have I come to add or is there any range whose right one is better than the value, then what will happen, there will be difference of just one, you can merge these, either only these two will be merged, or It is or only these two will be merged, or It is possible that both of them get merged, okay, the mix is ​​making a very simple sense, okay, the mix is ​​making a very simple sense, okay, the mix is ​​making a very simple sense, here we just have to do whatever we want and pay attention to which of the two, I will just check the smaller one and I will just check the bigger one, see. I will take it, if there is a difference between plus van and minus van, that means it is marble, okay, the first thing is done, the second thing, what will be the second thing, what did I say in between while telling that what am I saying that I have, the range is available in it, what are the available ranges? I will try to find these six among them, so it is a matter that I will have to store the ranges, okay, so that means I will take a table like this and I will take this was the first range, okay this That L1 should be smaller than its right six, just mines van, okay, it is understood that what data structure has to be done in which I can color it, the album will be done a little, it means a very expensive post will go, right, I take one and the second number is Then you will search on stable, it is for album and R1, neither is it just greater, just less, so obviously there should be some efficient data structure by which I can do direct search, then do you know what I will do, I will take a map, ordered map is ok, audit. I will take it and how will I search the direct address, brother, which is the range which has a function of LL, which knows what it does, just greater male provides, you check that just greater is there, I have taken but plus. Whether it is the difference of van or plus one or plus three, whatever it is, we will check it. What we needed in an efficient way is that the one with just greater is fine, then if we go just behind it, then obviously the one with just previous will also be found. Right, we will find the band with just weight, we will do the bond on you, okay, and what is the upper bond, there is a logration, okay, so our complexity is reduced, we will just do it, we do not need to sort, right, we are in the map. Those people who are keeping it, we can access it. Okay, so now let's see how to approach it with intuition. So we understood what to do, how to take it with a careful approach, how to code. -What to do, the cases will be handled by us, we will -What to do, the cases will be handled by us, we will -What to do, the cases will be handled by us, we will read, okay, so let's move ahead, so let's start, let's say that I just got the number van, he said, brother, add the number van, okay, but what did I say, I am in the range. I will store it in my map, okay, so first of all I also said that I will first check if there is any such range available whose left side is just bigger than the van, then I will hit the upper bond, I am okay but this. It is obvious that this map is empty right now, so now the range that I will add will be on the left and the one on the right, I will keep it as Van and Van only. Okay, there is nothing in my map, so I have added Van on the left. The van team was given on the right, till now it is clear, it was very simple, the van process is done, now the man has come, let's take what was our input in this and he had given three, okay then let's go, okay, so first let me see what is in this map brother. Is there any such range, why not the one whose left is no, sorry, whose left is just bigger than 3, then there is no such element, neither will give three parties of direct three and three parties will be given, okay and Pay attention, this is a map, actually this is the key on the left and this is the value. We have made up our mind that we will take the key as the left one and its just values ​​will be given to the right one, it will give and its just values ​​will be given to the right one, it will give and its just values ​​will be given to the right one, it will give me the right one. What was after that I was allowed to add seven to it, I am fine, let me add 7 edge, then I will check the same, brother, is there any such range in this map, is there any such value, is there any such left value which is just from seven. If you are not big, then quietly we have given a team of 7 and 7 left and right man, no problem, and Han in the middle, if you tell me brother, return all the intervals and show me, then brother, I will not do anything, I will travel on the map, van. Three Seven Whenever you ask, I can give it because all the answers are stored in my map itself. Okay, now coming next, after seven, what did he give me in this? After 7, he gave me six, okay, you look, pay attention. Now it will be important, what did I say, let's go, right? I see that there is someone just bigger than you in this map, or there is someone just bigger than you on the left in this map, or is there a range in this map whose left is just Let's see if I am bigger than you and if I kill you then I will consider you as the ultimate. In the map, it will give me three. This will give me a pointer which will be pointing just to 3, not to three, it will be pointing to this entry. If it's okay then reduce it by one, let's write the name of this variable, just big, it's okay, just write the name of big, just big, okay, just big, we got it and just keep the one behind it, we can store it. If that also gets merged, then just know what will happen if you merge KB mines or you will get the one just behind also, JP means just behind, so we have got both these information. Okay, so now look, I have got this information. So now I will write it exactly the same way as I did when I tried to make the statement that I have got the value right, just after this I have got the one which is three come three and just before which I have also got the one which is Van Kama 1 Is it right, it's just after, it's just behind, okay, till now it's cleared, now look, pay attention here, this is the L of this range, this is the right of this range, this is the L of this range, the right of this range Okay, so the first and obvious thing is that I have to enter a new range. Since he has given me a tu, then he is expecting from me that I am in the range, one side is done. Okay, so what do I have to leave, one left has to come out and one Right has to be removed, which I don't have right now, I will see if it is merged then it is good, otherwise you will have to enter com. Okay, then let's see if the merge is happening, otherwise tell me one thing. First of all, what do I do? I come near just behind, okay, what I said is that the second member of just behind, i.e. the R, is the distance between that and the value just i.e. the R, is the distance between that and the value just i.e. the R, is the distance between that and the value just van, meaning if plus van is added to it or then you are minus. Okay, what does it mean that these two can be merged, okay, so the left, what will be the left start of the left part of the range, the left point will be this, it will start from here, okay, so I have understood the left, brother. Left is going to keep the van, right is going to keep the van. Well, this is clear, after this it is ok, it is left, it is known and now coming just the last 2 plus van is three, what does it mean that the one is right? The range is that, this can be three, so look, everything will match, then you are three again, what does it mean that the second element of just Bada will be my right range, so here it will be three, right range is just. I will have to delete the elder one, right? Because I merged with the van three times, you merged in the same one, so what will I do, I will just delete the elder one, okay and I will change the one who was just behind me. I will make this van to three, look at the range, what am I doing, this van was three to one, so here I made it to three from van, you have also got merged in between this van to three, it has merged, right? So now the thing is, I do n't need this time, so I will remove the entries from here. Is it clear from here or do you understand how I did the merge? Okay, so let's reduce this story by one. Let's try to convert it into, OK, first, what did I say that I have a function called add name, it will give me a value and will say, brother, add this value and show it, then I will add it, but I am adding it in the internal map. I am there every time and I will need left and right which I have to store in my map. Okay, no matter what I said, what I will do, just find a big one and show it, now I will apply the speak up board in my map. At whose place will I get the just big one, is it okay? And then what did I say that I will get behind the bus? If I know that, then what will I do? By assigning the just big one to JP, I will give mines to JP. Okay, so what will happen with this? That I will go to the back of the bus, by the way, when I have the bus big, then I will mince one mine from it, in this I am here, if I go to mine, then the pointer will go here, then what did I do? This thing is clear, you are okay, now let's move ahead, let's write with green pen, then what I said is that I am just behind, what I was asking is that the second value of just behind is the second value, right? Look, this is what I asked, right, is the value of the second right, is it equal? What is the value of value -1, is it What is the value of value -1, is it What is the value of value -1, is it equal? ​​If it is equal, then what I equal? ​​If it is equal, then what I equal? ​​If it is equal, then what I said is that I have come to know my left range, brother, what is that left? What did I say, this will happen on the left, it will start from here, that is, just behind the second, not the first element has been first, the first element has been cleared till here, what have we done, we have left our range now. Coming to the right was also very simple. Remember how simple the right also became equal to value plus van, equal to left, tu plus van three comes to be, okay so a became equal to plus van, so I have got my right range also, now that. What will be the right range? Just bada's sorry, first will not be second, here also I saw this, look, if you and Joe are 3, then what will be the range, what will be the ending of my range, will it be six, so I signed second here so that it is clear. Must have been simple maths, nothing else, if you want, you are doing merge inter, that is, we are sorry, we had to do one more thing in our map, that is, when we just updated the big hair, here it will be merged with JP, right here, it is of JP. Left and right, I will have to update as well and I will have to delete as well. Well, what will I do with that which was my map, I will raise which point is mine which is just the bigger one because now that point is deleted. I will have to do like I told here that I deleted the baby and what I said that for the JP, his left range is correct, but the right range is not there, we will have to update it, look here from the van. Made it three because you will merge into it. The left of MP is equal to what was my van. Look here, the right value is whatever the value will be. It will become three. Okay, so the left of MP is equal. So I will make it right. There is an entry in our map, there is an entry from van to three, right, and here remember there was an entry which we had deleted, just the big entry, no, we have deleted it, okay, it is cleared till now, this is ours. It's over, okay, and one more thing, when we are asked for an interval, we will attract it in our map because remember whatever entry we are making in the map, we are not merging it in the map smartly, whenever we are asked for an interval. If you ask, we will guarantee that all the intervals are absolutely correct. Our marriage is already ready, so we will simply traverse through the map and return all the intervals. Okay, now see how we will handle some corner cases and nothing else is fancy, no, it is very simple. Think for yourself, what did I tell you that just one elder will come out okay and one just behind will emerge just behind? Remember, like I take it, this is my map, right, just elder came here, so what will happen just behind, just this? This will be the one, now let's take just the first element is gone, so now we can't go back, there is nothing above, so we will check this every time, what is better then just Is it big? Is it equal to the beginning? Is there a beginning? So I will check this. Just big is not equal. The map is not equal to the beginning. So, if you pay attention to this thing, then I will write the code there. But I will tell you like a story, it's okay, another corner, what do I see that we want to go just bigger, whatever value is mine, I take the value, you are mine and in the map, I have to go just bigger than you, but in the map. There is no such value, I take it as zero, there was one, that's all, I would like to leave, since I did not get anything, then we should just point to the big end, only then we will be able to reduce it, when we are not even pointing to them. If we are pointing to them, then now it has become a corner case that there is no one who can grow faster than you. If the person we want to leave is not there, then we will check on him as well. Okay, if we give you a check then it will be obvious. The thing is, whenever you do the function of upper bond, lower bond, then you have to keep in mind that in the case of dot ending or dot big in case, you have to see that if the starting point is a singing point or the ending point. The one with point, you have to pay attention to these two whenever you do any sal, that is why I am stuck in upper bond many times in some question where I was not handling the brinjal and end, okay so these We will handle both of them, but my concern was that you need to understand this story more, so I had told here that the left and right exit was just big and just the back exit is fine and here did you check this, see to understand this. For this, make a diagram that we take main from six, here one is just bigger and here there is one just behind, just bigger and just behind, then when the merger happens, then this thing will be on the left and this will be on the right, when we will make whole chilli. When the merge happens, then it's okay, then let's code and tell the story. Okay, he doesn't have any tension, he will say sorry. Let's code and see. Okay, then let's solve our approach with you too. What did I say to this, we will take a map. Okay, whose name I am keeping as MP and why I have taken it in order because you can put it in the order map only, remember, you can put the immense man only in the sorted area, similarly in the audit map itself, you will be able to put the mode here, right. What will we do here? This is initialization, so let's clear it in the beginning. After this, whatever was less in the ad name itself, everything was less and the get interval is guaranteed. Brother, I have merged it in the map. If I have stored all the intervals then I will silently return then get in double first let's write ok the result will be what will I do will I maprate then auto end it and which will show my map, it has become simple less finish I will return the result because I guaranteed that whenever I was adding the interval in my map only after getting married, it has become good, okay, now I have less min, this is the function, so what did I say, I have to go left now. I don't know, okay, right now I don't know the left and the brick, sorry, let's keep the brick ride as well, right now I do n't know this left and this right, I have to find out right now, okay till now it is clear, now let's move ahead, what did I say? That I will take out just greater and one behind just, okay then let's make one less and you keep it i.e. then let's make one less and you keep it i.e. then let's make one less and you keep it i.e. what did you say just greater or just write bigger or just bigger aunties it sounds like mp dot upper bond Isn't it aparbound, whose exit is the value, I have got it very good and what I had said is that I just got the big one, you will go up, there is nothing above what I wanted you to read, so let's check one thing here that my just It is big, is n't that not equal, you are sorry, it is okay till now, it is clear, after that auto, see what I have said, you have to leave just behind, no, just underscore behind this equal, you first sign it, just take the value of the word. After that, we will make mines, just behind mines, we have cleared it till now, so now I have got two things, the one just behind and the one just behind, and so what I had said that brother, if the one just behind is his. Second is right, the second value which is just behind, if the value becomes equal to -1, then it is very simple, then what will happen just behind, it is clear till here and this is done, after that what I said that just greater which Is it just greater? I have to check the second one. Sorry, I have to check the first one and before that I should also check that the one that is just bigger is not equal to the end and is not equal to the MP Rind. Is it ok? And if it is not equal then it is ok, one more thing has to be checked that the one who is bigger and not the one who is first, nor is he equal to whom is the value plus van ok, so what I said is that I have got the right brother, is that ok? It would be just bada's second one and what I have to do is to remove it from the MP. Just bada one is not just bada one because it will be merged and a new range will be created. So I removed just bada one. It is clear from here till here and what did I say in the last that I have got left and right or not, so I will simply update that the one corresponding to the left is the right one, see, it is okay to pay attention. If he has grown up, why am I saying why am I returning? Look, pay attention that I take that the one just behind me is right and the one just after is my 8, earn 10, I take it like this, it is okay and My number is three, man, let's take the value of adding it is three, okay, so think for yourself friend, if it is 3, it is smaller than the second one just behind me, then it is equal, so now by the way, these three are definitely in this. It must have been kept inside, it must have been merged, so there is no need to put 3, nor must it have been in the middle, so we are silent, there is no need to do anything from here, so this is one thing, you can do the optimization team and put it right here also. It is necessary that the letters will be wrong, okay, so we have given this team, from here we are saved, these are the three corner cases, I did that and found out directly from the example, it did not come to my mind, do not take tension, we do not have that sharp mind, neither do I. It was spread, okay, there must be something wrong with me, then I came to know, okay, this one thing had to be paid attention to, then this one thing had to be paid attention to, and then one thing, this thing had to be paid attention to, how about three corners, so totally fine friend, if you have spread, then how about the corners. Now you learn, in the next time I always keep in mind that brother, if I want MP road beginner, I will always pay attention, so after making this mistake, learn, don't take tension about it, what are you doing, people, it is an offline operation and its time complexity. Here there is N, isn't it? If the size of the map is N, then look, we have done it very well. In the previous approach, those people were N, that is so, let's run, it should be done, okay, now it should be run, left and right. Great, submit it and let's see if it runs. Look, the video may have gone long but you had a lot to learn in this D, right? I wanted to see. Learning is quite optimal. This important video seems long, so you can watch it a bit. Run fast, big request, YouTube, go through H and every line, next video, thank you.
Data Stream as Disjoint Intervals
data-stream-as-disjoint-intervals
Given a data stream input of non-negative integers `a1, a2, ..., an`, summarize the numbers seen so far as a list of disjoint intervals. Implement the `SummaryRanges` class: * `SummaryRanges()` Initializes the object with an empty stream. * `void addNum(int value)` Adds the integer `value` to the stream. * `int[][] getIntervals()` Returns a summary of the integers in the stream currently as a list of disjoint intervals `[starti, endi]`. The answer should be sorted by `starti`. **Example 1:** **Input** \[ "SummaryRanges ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals "\] \[\[\], \[1\], \[\], \[3\], \[\], \[7\], \[\], \[2\], \[\], \[6\], \[\]\] **Output** \[null, null, \[\[1, 1\]\], null, \[\[1, 1\], \[3, 3\]\], null, \[\[1, 1\], \[3, 3\], \[7, 7\]\], null, \[\[1, 3\], \[7, 7\]\], null, \[\[1, 3\], \[6, 7\]\]\] **Explanation** SummaryRanges summaryRanges = new SummaryRanges(); summaryRanges.addNum(1); // arr = \[1\] summaryRanges.getIntervals(); // return \[\[1, 1\]\] summaryRanges.addNum(3); // arr = \[1, 3\] summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\]\] summaryRanges.addNum(7); // arr = \[1, 3, 7\] summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\], \[7, 7\]\] summaryRanges.addNum(2); // arr = \[1, 2, 3, 7\] summaryRanges.getIntervals(); // return \[\[1, 3\], \[7, 7\]\] summaryRanges.addNum(6); // arr = \[1, 2, 3, 6, 7\] summaryRanges.getIntervals(); // return \[\[1, 3\], \[6, 7\]\] **Constraints:** * `0 <= value <= 104` * At most `3 * 104` calls will be made to `addNum` and `getIntervals`. * At most `102` calls will be made to `getIntervals`. **Follow up:** What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?
null
Binary Search,Design,Ordered Set
Hard
228,436,715
72
hey everyone welcome back and let's write some more neat code today so today let's solve edit distance so this is a dynamic programming problem and this is very similar to the problem longest common subsequence which is a problem i've solved on this channel so this problem is basically an extension of that problem so we're given two strings word one and word two and our goal is to return the minimum number of operations required to take word one and convert it into word two and we only have three operations available to us inserting a character into word one right remember because we're trying to take word one and convert it into word two we can't change word two we can delete a character from word one because we can't change word two and we can replace a character in word one and so replacing a character is basically changing one character into another so in this case there's three operations it would take to take horse and turn it into this string of course we'd want to get rid of the h right but we would do that by replacing the h with an r so this is going to be an r and then we have two r's right so we'd get rid of this r so we can get rid of that and lastly we see we have r o s we have an extra e so we're going to get rid of the e as well so we did that in three operations so we can return three so first of all let's analyze some simple cases what if we had the case where word one and word two were both just empty strings how many operations does it take then to take word one and convert it into word two obviously zero right we don't have to do anything they're already the same similarly if word one was let's say abc and word two is also a b c we also don't have to do anything right we'd look at the first character see oh they're the same right since they're the same of course we don't have to consider them anymore right then all we have to do is compare the remainder of each string right but then we see again hey b is the same good c is also the same good and look perfectly timed there's no characters left in word one and there's no characters left in word two therefore zero operations were needed right what if word one was abc and word two was empty then what would we do is it even possible to take this word and then convert it into an empty of course it is in this problem it's always going to be possible to take word one and convert it into word two right because we can insert a character we can delete a character or we can replace a character so it's always going to be possible because in the worst case right this is what we could do we could take every single character in word one and just delete it delete that because none of these show up in word two just delete all of them if there was some character maybe there's a z over here then we could just copy every character after we've deleted these and then copy it over here right add that z but no we don't need to so my question to you is if word two is empty and word one is not empty then what's this is a base case how many operations is it gonna take is always going to take the length of word one whatever the length happens to be because we're gonna have to delete every single character right so that's one base case word two is empty what about the opposite case what if word two was abc and word one was empty is this possible is it possible to take word one and convert it to word two of course it is right because we're allowed to insert characters in here so basically we could just read character by character a add that here b add that here c add that here as well right so we can just copy every character so my question to you is in this case the opposite case where word two is non-empty but word one is empty how many non-empty but word one is empty how many non-empty but word one is empty how many operations is it gonna take well we're just gonna copy each character in here right so in this case it's gonna take the length of word two that's how many operations it's going to take right so basically what i'm getting at is if word one is empty and word two is non-empty non-empty non-empty then we're gonna return the length of this as the minimum number of operations if the opposite was true right maybe this is empty but this is not empty then we'd return the length of the non-empty we'd return the length of the non-empty we'd return the length of the non-empty one if one of them is empty we're going to return the length of the non-empty to return the length of the non-empty to return the length of the non-empty string that's going to be the minimum number of operations this is important because this is our base case so now let's try to brute force this how are we going to handle it well we're going to have two pointers right we're going to have one pointer pointing at a character in word one and a second pointer pointing at a character in word two we're going to compare character by character so the one case is what if they're exactly equal then what is the sub problem then right because we don't have to consider these characters anymore now we're dealing with the sub problem of the remainder of the of those strings so basically if i'm calling the pointer in word one i and i'm calling the pointer in word to j if these characters are equal that means we can basically say i plus one is the new problem and j plus one is the new problem in word two right so we're just shifting our pointers like that so basically to summarize if these characters are equal right at the i and j pointer basically what i'm saying the characters are equal then we're just going to increment i by 1 and increment j by 1. the number of operations we had to do was exactly zero right we didn't have to do anything they were already equal we didn't have to modify word one at all to the next character so our i pointer is going to be over here our j pointer is going to be here because we incremented both of them by one so now let's compare the characters c and b are not equal right so now our else condition is going to execute and we don't know we have three options we can insert a character delete a character or replace a character from word one but we don't know which one to do right so let's just try all three what happens if we insert a character what character are we gonna wanna insert over here obviously we'd wanna insert the character from word two we don't know if that's going to end up making word one exactly into word two in the minimum number of operations but let's just try it and see what happens right so what would we do if we inserted a c over here right we're not deleting a character all we're doing is inserting a c over here in that case our i pointer is still going to be pointing at this b right but since we inserted a c over here it's hard to read but let's say i inserted a c in between over here that means we took care of the c from word two right so basically we don't need to find a matching c for it anymore we do need to find a matching b somewhere over here right so we're gonna leave our i pointer where it is but we're gonna take our j pointer and then shift it to the next position in word two that's what we would do if we inserted a character so as you can see when we insert a character we are taking one operation right so we're gonna have to add a one to the number of operations we did but when we shift our pointers the i pointer stays the exact same but j is incremented by one so that's one possibility another possibility is we delete a character so we're allowed to delete characters from our word one right so what would happen if i just deleted this character what we're saying is okay i can't find a matching c in this position right and we don't have a b corresponding to that position so i'm just going to ignore this guy and hopefully the remainder of the strings can match up right so what i'm saying is i'm going to take our eye pointer and yes i am going to shift it to the next position because i just i want to pretend like this character never existed but it does take one operation to complete that but since we did not find a matching c yet right we have to leave our j pointer here right we have to keep searching until we find a matching c ultimately we want word one to match word two so in this case for the delete operation what we're saying is i is going to be shifted but j is going to stay the exact same so i plus 1 but j stays the same as you can see this is you know kind of a pattern we're starting to see a pattern right and the last thing that we can do is replace a character from word one that shows up in word two right obviously if we're replacing a character from word one right we're gonna want the character that's matching in word two right so what we'd wanna do is take this b and replace it with a c character right if we did that clearly these two characters match right we made them match we forced these characters to match so in that case we know that the c has a matching c up here so we can take this i pointer and shift it and we can take our j pointer and shift it to the next position right so the replace actually ends up doing the exact same thing as if the characters were equal and that makes sense because what we're doing is we're forcing them to be equal with the replace operation the difference between the replace and if they were already originally equal is that the replace does take a single operation if they were already equal the number of operations it takes is zero right so it does come with a cost even though replace is pretty powerful as i said with replace what we're going to do is increment i and increment j so let's just go with the replace operation because that's actually going to end up being the minimum solution so now we shifted our pointers to the next position we see d and d they match each other so this is the statement that's going to execute and we know that takes 0 operations right so we're going to increment both pointers by 1. j is going to be over here now i is going to be over here notice now how we have two empty strings remember the base case if both strings are empty we can return 0 because it takes zero operations to make them equal right they're already equal so we're done we return zero how many operations did it take by the way if we if you were counting we did have to execute a single replace operation that took one operation so the result is one so we are noticing that the sub problems are good to solve before we try to solve the original problem of comparing the entire lists let me reformat this into the dynamic programming explanation so you may have seen something like this before this is going to be a two-dimensional dynamic programming two-dimensional dynamic programming two-dimensional dynamic programming problem it's good to visualize it kind of like this so what we're doing here is we are comparing these two strings and for this position this is what we want to calculate in this position what we're going to do is we're going to store the basically the minimum number of operations for these two strings starting at this character for word two starting at this character for word one so basically the entire strings is going to be stored here what would be stored in this position basically corresponding to here so we're comparing these two basically the remainder of this string and from here the remainder of this string so in this position what we would store is the minimum number of operations it would take to make this sub problem these two sub strings how many minimum operations it would take to make them equal okay so that makes sense so far but then why do i have this extra layer over here the this portion is for our base case what would be over here right so clearly we see that there's an empty string over here what value should i put over here obviously zero right two empty strings take zero operations to make equal what about in this position what does this position tell us well we have an empty string from word two but over here we have the entire string from word one so how many minimum operations would that take remember we went over that at the beginning and it would just be the length of the non-empty string so here we can see the non-empty string so here we can see the non-empty string so here we can see the length of the non-empty string length of the non-empty string length of the non-empty string is three what about in this position similarly word two is empty word one has a length of two so we'd put two and basically continuing to one and then down to zero right so similarly over here we have an empty string from word one word two is completely full and the length of it is three so we're going to put three here and then continue just counting down three two one right so in what order are we going to solve this if we start at the beginning then we're going to notice something notice okay well we're comparing these two characters in this position right they're both equal right so then we're going to execute this statement right so we're going to take i plus 1 and j plus 1. what does that tell us that tells us that the result of this value depends on this value right so okay then let's take a look at this value well in this case they're not equal b and c are not equal so then what are we going to do remember if they're not equal we have to brute force it we have to take a look at all three operations and remember i corresponds to word one j corresponds to or two so in the insert operation what we're going to do is look in this spot in the delete operation what we're going to do increment i by 1 in this case so we're going to look in this spot and for the replace operation we're incrementing both of them so then we're going diagonal again from this since we have three values that we're looking at what we're going to do is we want to know which one of these three leads us to the minimum number of operations right so what in reality what we're going to do is since we're noticing that it depends on the lower values let's do this bottom up this is called bottom up dynamic programming we're going to start at the bottom compute this value and then so on and then work our way backwards until we finally get to the result and notice if we do start in this position we already have the values that it could possibly depend on because those are our base cases over here diagonally and below right and so notice d and d are equal so what we're going to do is from here we're going to look at the diagonal value right because this statement is going to execute we're going to see it's zero so that's what we're going to put over here and then eventually we would end we would compute these and then eventually we would get up over here right and we'd compute the value from that and then eventually we'd get all the way up here and we would compute the value from here you would see that we'd end up putting a 1 over here so what would the value over here end up being well let's look at the two characters d and c they're not equal so what we're going to do is we're going to look down we're going to look diagonal and we're going to look to the right which one of those values is minimum it's over here so that's 0 but we do have to add 1 because in this case we do need to do a single operation so we add 1 and similarly is what we would do for every single position you know we'd compare the characters and then we'd execute this statement or we'd execute this statement so i'm not going to run through that but i think this is simple enough that if you want to you can get a piece of paper out and then try it for yourself and you'll probably come to the same conclusion so that being said let's jump into the code this is exactly what i'm going to do with the code i'm going to have a two dimensional array and i'm going to execute these exact statements so i'm going to call our two-dimensional so i'm going to call our two-dimensional so i'm going to call our two-dimensional array our cache and so basically i'm going to initialize it to initial values of just max integer or float infinity in python and you can probably initialize this any way that you'd like in your own language there's probably a different ways that you'd want to do that but i'm going to use a list comprehension so basically i'm creating a list fl with float infinite as the value of length word two plus one remember because we do need to make our two dimensional array a little bit bigger to handle those base cases for this list i'm gonna have one of these lists basically for every character in the range of the length of word one so this probably looks confusing if you're not familiar with python but basically i'm just creating a two-dimensional array two-dimensional array two-dimensional array with these dimensions actually word one the length of board one plus one because remember we are worrying about the base case but basically yeah a two dimensional array so now i wanna fill up our bottom row of the two-dimensional our bottom row of the two-dimensional our bottom row of the two-dimensional grid so what i'm gonna do is for our cache i'm going to go to the bottom row what's the bottom row it's going to be the length of the word 1 and that's going to be the bottom row and we're going to go through every value of it so for every j of that remember where it's going to be basically in descending order so what i'm going to do is and it's going to initially start at the length of what word two happens to be because remember the base case is if one string is empty and the other string isn't so word two and it's going to basically be decrementing by one each time so what i can just do is just say length of word two dec subtracted by j and actually i keep forgetting the bottom row is actually not just going to be the length of word tube that's going to be length of word two plus one so i want to make sure to add that plus one and similarly what we're gonna do is and for that right most column what we're gonna do is go through every position in it so length of word one plus one and for every work every position in the last column and the last column can be found like this basically for every i in the last column which is going to be length of word 2 in this case and what we're going to do is similar to what we did up here take what the original length of word one is and each time subtract it by an additional value basically we can use i in this case so this might be a little bit confusing you can do this a bunch of different ways if this is confusing to you can probably find your own way to do it basically we're just initializing the base case of our two dimensional array but so now let's actually get into the dynamic programming portion so remember this is going to be bottom up so we're going to work our way backwards from the length of word one minus one and the reason we're minusing one is we know we already filled up our base case portion so now we actually want to get to the actual dimensions of our two strings and we're going to do this in decrementing order until we get to the beginning until we get to the zeroth index which is when this is going to end up stopping and similarly let's work our way backwards from the length of word to so we're going to start at the bottom row and work our way backwards and then keep doing that until we end up getting to the top row and remember we had two cases either word one at index i is equal to word two at index j basically with the characters that we're comparing are equal or they're not equal remember if they are equal then that's really easy for us right because then we can just say okay cache of position i j what we're doing here is computing what's the minimum number of operations it would take to get the sub string starting at i and the substring starting at j for these respective words compute the minimum number of operations so we can get that in this case since the characters are equal just by saying cache of i plus one cache of j plus one and the else case is where we have to check all three directions and then take the minimum of those so what i'm gonna do is say one plus the minimum of those three uh directions so cache of i plus 1 and leave j the same and also we want to take the minimum of cash of i left the same but j plus 1 and last but not least we want to take the minimum of cash of i plus 1 and j plus one so this is a long line but i'm going to leave it as it is but yeah basically this is taking care of insert delete as well as replace and it's taking the minimum of whatever those were adding one to it because we are having to do at least one operation whichever one of those it is and then storing that minimum here and once we have done that once we've filled up our entire two-dimensional array two-dimensional array two-dimensional array we want to return the value at index 0 of our cache because that tells us what's the minimum number of operations for the beginning of both strings so basically the entirety of both strings so this is definitely a doozy of a problem it's not a ton of code but it does take some thought to get to here and it's definitely an extension of longest common subsequence so i recommend solving that problem if you haven't already but i do hope that this was helpful it's a tough dynamic programming problem if it was helpful please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
Edit Distance
edit-distance
Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_. You have the following three operations permitted on a word: * Insert a character * Delete a character * Replace a character **Example 1:** **Input:** word1 = "horse ", word2 = "ros " **Output:** 3 **Explanation:** horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') **Example 2:** **Input:** word1 = "intention ", word2 = "execution " **Output:** 5 **Explanation:** intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') **Constraints:** * `0 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of lowercase English letters.
null
String,Dynamic Programming
Hard
161,583,712,1105,2311
31
hello everyone let's take a look at the code city one next permutation it's um it's a very plastic problem in the code and this program is um a little bit tricky since there are some good solutions and it would be best if we could remember so as solutions okay so let me go through some examples and let's enhance this problem together okay so the problem is to find the next permutation of the given array for example numbers is one two three so the next permutation is one through two for three two one the experimentation is one two three for one five how we find there can be duplicate numbers the next permutation is one factor one with certainly one number the next permutations itself okay let me take a new example two three six five four one we know the next permutation two three six five four is two four one three five six okay let's um take a look at how to find this solution okay first we need to find the valuation index what's the validation index we know like for the number after the violation that's in descending order so we need to search for another index and find the first index sets are in increasing order so this is the violation index it's in increasing order but all the numbers after it are in descending order so we find the first indexes in ascending order now we need to search for another index okay next we reverse all the numbers after it so six five four one becomes one four five six okay so it's one corner case for example if the input is three to one then values index is negative one after reversing it becomes 23 this is our answer so we can just return in this case otherwise we just swap the violating number with the first number larger than the evaluated number which is four we just swap them then two four one three five six is our answer okay let's see if they can handle duplicated numbers so this is well mission index and this is um a number like the first number larger than violated number then we swap them okay we can also get correct number so this is our implementation first we check some common cases then we use a for loop to find the evaluation index which takes oven time and we reverse it which also takes on average own time if violation next is negative 1 will return immediately otherwise we use final search to find the first number larger than the violated team number at last we swap them then we get scrap and answer okay that's it see you next time
Next Permutation
next-permutation
A **permutation** of an array of integers is an arrangement of its members into a sequence or linear order. * For example, for `arr = [1,2,3]`, the following are all the permutations of `arr`: `[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]`. The **next permutation** of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the **next permutation** of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). * For example, the next permutation of `arr = [1,2,3]` is `[1,3,2]`. * Similarly, the next permutation of `arr = [2,3,1]` is `[3,1,2]`. * While the next permutation of `arr = [3,2,1]` is `[1,2,3]` because `[3,2,1]` does not have a lexicographical larger rearrangement. Given an array of integers `nums`, _find the next permutation of_ `nums`. The replacement must be **[in place](http://en.wikipedia.org/wiki/In-place_algorithm)** and use only constant extra memory. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[1,3,2\] **Example 2:** **Input:** nums = \[3,2,1\] **Output:** \[1,2,3\] **Example 3:** **Input:** nums = \[1,1,5\] **Output:** \[1,5,1\] **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 100`
null
Array,Two Pointers
Medium
46,47,60,267,1978
1,219
this is RIT go to question number 20 19 pass with maximum cord this is medium question less guarantee in a coalmine grid of site m-by-n each cell in their grid of site m-by-n each cell in their grid of site m-by-n each cell in their mind as an integer representing amount of gold in a cell generally is empty little maximum amount of gold you can collect under the condition each time you are located in yourself you will collect all the gold in the cell from your petition you can work one step to the left right up or down you can visit the same cell more than once never visit us that with the G record you can start we'd start collecting called from any position in a grid that has some gold let's check with is everyone in this time maxi is nine digging to a digging to seven at the time we can collect 24 second is start from one ticking to ticking three ticking for taking five ticking six ticking seventh in this time the maximum sum is 28 how can I serve it yes we're gonna use backtracking we mm-hmm we're gonna use backtracking we mm-hmm we're gonna use backtracking we mm-hmm only the perfect rating is okay it breath so there are some obstacle why we implement it so we will check why we coding okay first we had max some valuable and then we need the recursion for backtracking so names helper argument is now column and this so that some initialized is 0 because every step we need to the song okay first because I have to prod first a Space Case and equation and the best case is if we and our so here 1000 danblank read em read plow and column must be P code until in this case we need a chance and then when you return we will update the maximum value max Safi now let's do a relationship first will be played a song some ad and we need to beat it Mac there are one idea to back in beat it I gonna multiply minus 1 to make value take a clip the reason is if we make the dishonest negative this will under this condition so backtracking to do not go in there German is better I think is not going to be cheated it is make sense and then we can get one more benefit minced after finish it will be lower back when it will be lower back we needed to reset the value to original at this time we can simply multiply my negative minus one and that it will be gap it is no better okay now the creature comes and then I will take it totally try to dig in for Direction one now - one Carlo - one and Direction one now - one Carlo - one and Direction one now - one Carlo - one and then after finish it and after finish one when we roll back I will listen to reach that value like this okay I think we finished recursion for backtracking then now is can the grid follow in range zero and there if Creek it's natural and then I don't need to like this song because I already initialize this chair oh okay looks good okay let's check the complexity it takes linear to scam and when you're digging it just doing on either one time so maximum it is sad beat it only two time so it should load it pick all to em so we can say it take linear time and then we use a system step 4 early creature at this time worst cases there are also value has a positive number at this time we can use the same amount of the length of set so we can say it take in your time within your space thank you
Path with Maximum Gold
longest-well-performing-interval
In a gold mine `grid` of size `m x n`, each cell in this mine has an integer representing the amount of gold in that cell, `0` if it is empty. Return the maximum amount of gold you can collect under the conditions: * Every time you are located in a cell you will collect all the gold in that cell. * From your position, you can walk one step to the left, right, up, or down. * You can't visit the same cell more than once. * Never visit a cell with `0` gold. * You can start and stop collecting gold from **any** position in the grid that has some gold. **Example 1:** **Input:** grid = \[\[0,6,0\],\[5,8,7\],\[0,9,0\]\] **Output:** 24 **Explanation:** \[\[0,6,0\], \[5,8,7\], \[0,9,0\]\] Path to get the maximum gold, 9 -> 8 -> 7. **Example 2:** **Input:** grid = \[\[1,0,7\],\[2,0,6\],\[3,4,5\],\[0,3,0\],\[9,0,20\]\] **Output:** 28 **Explanation:** \[\[1,0,7\], \[2,0,6\], \[3,4,5\], \[0,3,0\], \[9,0,20\]\] Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `0 <= grid[i][j] <= 100` * There are at most **25** cells containing gold.
Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].
Array,Hash Table,Stack,Monotonic Stack,Prefix Sum
Medium
null
56
hey hope you're doing good back to solving more problems on arrays and today's question is merge intervals it's quite a popular question and has an interesting solution as well you could pause the video and quickly go through the question we have a list of intervals where each interval has a start comma end index and we need to merge all the overlapping intervals and return the array of the resulting non-overlapping intervals resulting non-overlapping intervals resulting non-overlapping intervals so for the first example we have 1 comma 3 2 6 8 10 and 15 and 18. from this list we see that 1 3 2 6 are overlapping so we have 1 6 as the output we then have 8 10 and 15 18. let's visualize this example and see how we can try solving it here's a question with these intervals and we have a number line drawn below to visualize these inputs so we have four intervals and let's start plotting these on the line so we have the first one being one to three and let's use different colors so that it helps uh plot these on the graph the next interval is 2 to 6 so we have 2 to 6 and the next interval is 8 to 10. and the last one is 15 to 18. so if you have a look at these intervals from this graph it's quite evident that the first two overlap and the second two are unique by themselves and from this we can determine that the answer is going to be 1 through 6 8 to 10 and 11 sorry 15 to 18. it's quite evident when you have a look at this graph to try to group them or break them down into overlapping and non-overlapping intervals non-overlapping intervals non-overlapping intervals but the main problem here is to identify how we can solve this programmatically so that there's a process to determine which intervals are overlapping so the first thing we observe that it's really helpful to start with an interval that has a smaller start index so in the this example we started with 1 3 and then came across 2 6. this helped us identify that 2 6 falls within the end of one comma 3 and we could identify them as overlapping let's say we started with 2 comma 6 and then came across 1 comma 3. it's harder to identify because we're first starting with 2 and going through 6 then we have an interval that's coming earlier but still ends at 3. it might still be possible but it's quite hard to do it when there's no order to these intervals and once we go through a list it's possible that an overlapping interval can come in the future so from this graph and from what we discussed it's quite evident that sorting these intervals based on the start index is really helpful so in this case the list is already sorted where we have the starting indices which is 1 2 8 and 15. they're already in that order which is helping us identify or the group the overlapping intervals so we have the list sorted based on our start indices which are ordered as 1 2 8 and 15 and we start iterating in this order so we still first start with the interval 1 comma 3 and let's call our end index as current underscore end which is equal to 3. so we have 1 comma 3 and our current n is equal to 3 we then look at 2 comma 6. so in 2 6 we see that the start interval 2 is actually less than our current end which is 3. rexy needs to be less than or equal to so even if the new interval started from 3 it would still be considered overlapping so we group that together as 1 being the start index and the end being the max of current end and the end from the new interval so we have 3 comma 6 which means we treat it as 1 comma 6. so 1 comma 6 is our new overlapping interval we then have a look at the next one which is 8 comma 10 8 is the start index and our current end is at 6 so 8 is actually greater than 6 so it would be a new interval so we add it as a new interval called 8 comma 10 and our current end now points to 10. then we come across the last interval which is 15 comma 18. 15 is greater than our current n which is 10 so that's a new interval again and we have 15 to 18 being the third one this would be our final result where with these three intervals that solve the problem and um visualizing or plotting these intervals on a graph greatly helped understand how we can arrive at the solution all right let's write some pseudocode to see how this can be implemented so we have a function called merge which accepts intervals as the input so we first need to sort intervals based on start and then we can i trade over the list so the first condition we need to check is if um let's actually use another variable called result to store our merged intervals so the first condition can be to check if res is empty or the last interval in res is actually less than the new interval which would be interval of zero in this case it means that the interval is not overlapping and can be appended to the result in the else case it means that it's overlapping which means we need to update our current end and the current end can just be updated as the last element in result will just be the max of the last element in result or the new end interval that we're seeing so as we go through the entire list we have our new set of merged intervals in the result and we can just return result let's have a look at the space and time complexity for this so in terms of time we're first sorting the entire list based on the start element and then iterating over it once so the sort itself would be big of n log n and the iteration would be big of n so finally our time complexity is big o of n log n and with regards to space we are using a new list for storing the merged intervals and the worst case each of them would be a separate interval so the space complexity would be big of n all right let's go ahead and code the solution we have a function called merge with intervals as the input so as a first step we can check if intervals is empty or none and then we can just return we now need to sort intervals based on the start index so in python we could use the sort function and since we want to sort it based on the first element we need to pass in a function as a parameter here and the function must return what it needs to be sorted by which is the first index so since it's a simple function we could just pass in key is equal to lambda x being the input and we want to sort it by the first index that will be x of zero so lambda can be used to write simple functions or one line functions in place and then we want a result array to store the merge intervals and we can also have n which will be the length of the intervals and we might use it in multiple places we iterate over all the intervals the first thing we want to check is if result is empty or if the last element or the current end of result is less than the new interval so we do if not result or result of um in python we could do a result of -1 which refers to the result of -1 which refers to the result of -1 which refers to the last element in the array and then we want the end index which is at index one and we want to check if that is less than the start index of the next interval if in this case it means that they're not overlapping so we just append the interval to the result so for our given example where we had 1 3 and 2 6 in the first case result is not there so 1 3 would just be abandoned in the else case it means that it's overlapping so when we for example came across 2 6. so 1 3 this so this result of -1 comma 1 3 this so this result of -1 comma 1 3 this so this result of -1 comma 1 would refer to 3 and interval of 0 would be 2. so 3 is not less than 2 so it would come to the else and we need to expand our current interval so we can just update our end index or current end which is a result of minus 1 to the max of our current end and the end index for a new interval after we go through the entire list we have our merge intervals in result so we just return arias i think this looks about right let's run the code to see if it works for the given example looks like it does let's go ahead and submit the code to see if it works for all possible inputs yes it does so from this example we saw that visualizing or plotting the given problem on a number line or a graph greatly helps understand and simplify the problem and this was merge intervals but there's a lot of similar questions for this patterns like meeting rooms and other questions where we want to understand which intervals are merging and sorting based on the start index and i trading in that order greatly helps solve such questions hope this helped thank you
Merge Intervals
merge-intervals
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_. **Example 1:** **Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\] **Output:** \[\[1,6\],\[8,10\],\[15,18\]\] **Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\]. **Example 2:** **Input:** intervals = \[\[1,4\],\[4,5\]\] **Output:** \[\[1,5\]\] **Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping. **Constraints:** * `1 <= intervals.length <= 104` * `intervals[i].length == 2` * `0 <= starti <= endi <= 104`
null
Array,Sorting
Medium
57,252,253,495,616,715,761,768,1028,2297,2319
1,376
Hello everyone welcome to me channel's video number 'Tu karne raha hai', video number 'Tu karne raha hai', video number 'Tu karne raha hai', got a very good response on video number one, this playlist got more than 1500 views and more than 100 likes also say, so I hope this video is also richer than that. Do and help you ok read I have medium mark from Bansi but it is a very simple problem question only ok let's see what is the question the name of the question is time needed tu inform jo employ it is by amazon I noticed the story that Google has also asked this question, but I am not sir, that is why I have not mentioned it. Ok, let's look at the question and understand what is the question. In the question, I have given you the information of other employees, whose numbers have been numbered from zero to N. - 1 is right and the head of this employee is the N. - 1 is right and the head of this employee is the N. - 1 is right and the head of this employee is the head ID. Well, that means let's take N = 4. Well, that means let's take N = 4. Well, that means let's take N = 4. So how many total 4 employees are there. Zero one. You are right and you said that some one will be the head, let's take mom In this, if you are the head, then the question is one, the name of manager is ok, that too will be of size N because the total number of employees is zero one, you are three, so let's one, you are zero one, you are three, so let's say, the manager of zero is one, ok, you are the manager of one. If you are a manager yourself, then minus one will be there because you cannot be a manager, the information given in the question is correct, it means that brother, you are sorry, I am the manager of one, tell me whose manager you are, then let us see. So, what is the index that the manager has given you? You are seeing the relationship between the child and the manager. What is it? Brother, if there is a child, then take the employee's mother and who is her manager? The manager is clear till now, it is okay. So I understood that brother, you have given the relationship of employee to manager, let's go to the manager, it is okay, till now it is clear, now let's move ahead, relationship has a tree structure, understand what is meant by this, it is saying that the structure which you have. Didn't you tell me that he will definitely be a real tree, meaning if he is a manager, then what will be the tree sector like, its employees will be like this, its price is one, its employees and who is zero, who is the manager of 301, understand what it will look like. It will happen like this is also good, it has been cleared, this brother, it is going to be a tree structure, okay, this is the guy, once you inform, which is D Company Employees of Energy piece of news, it is a news, it has to give all its information, this is its just direct. Told to subordinates means this is you will tell one, you will tell zero, you will tell three and the rest who are employees, let's take care of others and who are the employees, let's take care of them, here is five, isn't it, the one who will be becoming the manager is six. Its mother is 7 and so on, when what will you do, will you tell at once to these three who are just below it, just so is the board net, after that these three who are right here, tell it to those below you and so on this Similarly, it will pass further, okay, now see, the bill is informed, the direction used to go down, everyone will know the information, now look, I think I need information time minute, then inform which of you directly, what does it mean that information time must have been given to you, information time It also has a size, it means that the one with 0 is the employee, he is taken here to pass the information on, it is okay, it takes one time to pass the information, he cannot pass the direct support net to anyone else. It takes time to pass on the instructions to one person and if one is fine then he must have given information time to all the employees as to how much time they can take to pass on the information to their subordinates. Needs information time in minutes. Tu inform jo of direct subordinates after information time start in de news means he is saying that you are here right, his jo direct support maa le 2, it takes 2 minutes to tell the bond from his direct, ok then obvious. Time will start from zero here, okay, it took you two minutes to tell all your points, so these are 15 and zero, after how many minutes these people must have come to know, after 2 minutes because it has been said that it takes two minutes to tell the information. It seems ok and so on, ok, you inform the employees about the earning news, you have to tell the number of minutes which you would need so that all the employees know the information, ok, zero here, one here, 3 times zero here. It would have started from zero and it would have taken 2 minutes to recognize till three and three. Mother, let's assume that it will take 2 minutes. Okay, so how much time has it taken till now, brother? It is taking maximum 2 minutes. It is okay to reach everyone and I had told you. It has been given in the question that in how many minutes each employee can pass on the information on his Just Born Net, so give two minutes, it has been given in the question that it takes 2 minutes to inform. Okay, so already information on this. If it came in zero minutes, then it is 0. And in counting this till zero, in counting this till one, in counting this till three, it is going to take 2 minutes. If it is given in the question, then 0 + 2 question, then 0 + 2 question, then 0 + 2 here, it will take two minutes to reach zero. 0 + 2 here. 2 minutes will be spent. 0 + 2 here. 2 minutes will be spent. 0 + 2 here. 2 minutes will be spent. Okay, now let's see how much of 013 has been given. Let's take zero. It takes one minute to get information up to one's support net. One takes 4 minutes to get information up to one's own interest. Three takes it to get information up to one's subordinates. It takes 3 minutes, okay, so let's move ahead, now let's take mother, when you had to deliver zero, you told the subordinate, okay, it takes 1 minute, extra 1 minute, it takes 1 minute to identify the news, okay, here we take mother, here it is four, here it is 5. Here, if there is a six, then pay attention to how many minutes it took to get the information at zero. At 0 + 2 how many minutes it took to get the information at zero. At 0 + 2 how many minutes it took to get the information at zero. At 0 + 2 minutes, it took 1 more minute. Here, to recognize till four, what is the total. 2 + 1 date, it + 1 date, it + 1 date, it took 3, so 3 minutes. To reach the tax, either write it in such a way that it took till zero plus tu, it took plus one minute to reach zero and it took 3 minutes to reach 4, the total is fine, now I will remove this and write here three. Okay, what will happen here also, it will take 4 minutes, so I have written down how much is the total, here it is six, where was the reach till three, it will take 3 extra to recognize the three till its six, so how much is five, okay five Now tell me one thing, brother, if I tell you that brother, it takes 3 minutes, now the entire news will reach all the employees, is it right or not, why is it right, because just look for 3 minutes, who can go to whom in 3 minutes. It already has news within 3 minutes. Look, it also has information within 3 minutes. Because look, it only takes three minutes to reach here. Okay, but look brother, it also has it within 3 minutes. Minutes because it took 2 minutes to reach here, it took 3 minutes to reach here too, the news did not reach it, brother, it took 6 minutes to reach here, it took 5 minutes to reach here, even here it took 3 minutes, this note gave the answer four. But it will not be able to reach because it needs 6 minutes, it will reach the information here for 5 minutes, it does not need till five, it will reach till five but it will go back after that i.e. what is our answer, if we after that i.e. what is our answer, if we after that i.e. what is our answer, if we see then what will be the maximum time or not what is the maximum time. That would be our answer. So it is clear cut that we will have to do traversal. Secondly, we will have to keep calculating how much time is being consumed. Look, we are passing on the time information. It took two minutes here, you plus one here, it took 3 minutes here. It took 2 minutes 2+4 6 minutes and so on, here. It took 2 minutes 2+4 6 minutes and so on, here. It took 2 minutes 2+4 6 minutes and so on, time information has to be switched on, ok and after that what I said, brother, if you want to do science trousers then do DFS either with BF, it is a simple tree, with BSF then DFS. Okay, and what will we do every time and keep track of the max sign, we will keep updating the max time, the maximum value will be my answer, it is clear till now to clear it better, see a small diagram here. Okay, the information given here is that brother, you are the manager of zero one and three. It is given in the question. Okay, so if I am making a small one, done and so 10 123 and so on, then it is old. In this, what would you have given in the question, this manager is A, who will be the manager of my one, who will be the manager of you, who will be the manager of three, who will be the manager of zero, the input given in the question is the relation between child and parent i.e. employee and manager. It is given but notice that the relation between child and parent i.e. employee and manager. It is given but notice that the relation between child and parent i.e. employee and manager. It is given but notice that the transmission we have to do here is that it is obvious to do parent to child because the information that is being passed on is from manager to employee, so we have to make a mapping from where to where is manager to whom simply. We will have to create such a mapping, so it is simple, we can create this very easily, we will create a small map, okay, it will be like a list, what will be the first element here, who is the manager, okay and this manager Which children can you reach through Okay, so there can be many children, so a manager has a vector of weights and remember this is actually a list from Adgesen which they always make in their graft reversal, so 3D in a way Is there a graph of Adjunctive? What will happen to you from this that you see, how will you store, you are my manager, who is his child, who is zero, one, three, so what will I do with you, wherever I can go, you will go there. How much time did it take to reach Zero? Okay, where can you go from? First you can go to Zero and how much time does it take for you to recognize the information in your board net, I will get it from here. Information is given in our input about time. Off tu, it takes so much time, so the information came to you in zero three minutes. From tu to zero, in how many minutes will the information go, zero plus tu, this tu wali, this wali is ok, similarly here, even at one, you will go at three too. But will go and so on, then from zero to wherever I can go, from zero to where I can go 4 5 6 Okay, I will keep passing on in time, you came here, right, then from zero, when I go to four I will go, okay then zero, I will see how much time does it take for zero to recognize the time in my subordinate. Okay, in how many minutes did the information come till zero, it came in two minutes. If it takes 1 minute to recognize 0 till four, then G 2. + takes 1 minute to recognize 0 till four, then G 2. + takes 1 minute to recognize 0 till four, then G 2. + 1 i.e. the information came in the third second or third minute till four, 1 i.e. the information came in the third second or third minute till four, 1 i.e. the information came in the third second or third minute till four, so this thing must have been clear to you, isn't it? And now if you make its diagram, then see this. If you solve it with this diagram, then it will be solved very easily. It will be done, okay, the information time has been given here, look at us, this information has been given in the time input, okay, then see who you are, zero one, how much time does it take to identify you in your subordinate, I am late but you are gone. How much time does it take? If it takes one minute, then it is okay. The time was zero in the beginning. It is okay and it will reach its board in the net in 1 minute. My time became 1 minute. Within 1 minute, the news has gone till 01 and 3. Now first. I have seen about Zero, how much time does Zero give in its support, it gives reach in 1 minute, when one goes to Zero, it gets made up, then in how many minutes did the information come on 0, in 1 minute and how much time does it take for Zero? It takes 1 minute to send it to your support, then OnePlus One Tu Ho Gaya will reach you all in 2 minutes. Similarly, now let's talk about this One, I went to One, it takes 2 minutes. Okay, on this, in how many minutes did these news come? 1 minute. It took 2 more minutes for OnePlus 2 to identify its subordinates. In 3 minutes the news will be sent to Seven. Now let's go to 7. If 7 takes 1 minute, then what will 7 do? It will deliver its information in one minute. But in how many minutes did it come? In 3 minutes, do three plus one and reach here also in a minute. Now come here on three. How much time does it take for three? Brother, it takes 1 minute. In how many minutes has the information come on three, it can reach you in 1 minute. What is the total time in minutes? 2 minutes is fine. If we look at it, we have traveled through all the notes and what is our maximum time. Look, 4, this will be my answer. Okay, so let us make it simple. What is the first step? Brother, the second thing we have to do is simple BFS or we have to kill BF, the third thing is to keep passing on the time, it is okay to grow bigger and one very important thing which generally people get confused about which note is already visited, if he has it then look here. It is not there again in any mode. Is it not created again from one? Okay, it is given in the question that you cannot visit the other note. Again, we check the widgetized ones whether it has been widgetized or not. It is not necessary. It is more simple, my code has become even simpler, it is simple to start, it is considered as BF and while passing on the time, try to cut the max time. Ok, story points are enough to solve our question, so this is the story. You have to convert the point into bus code, first of all list BFS or DFS from the list, calculate the time in BFS or DFS and calculate the maximum time, then let's start such a code and solve it with both BFS and BFS, then let's calculate its DFS. First of all, let's solve from, after that we will solve BSL, so first of all, what did I say, first step, what was our going to happen, first, what was the story point that we will make one of those sorry adjuncts like this, okay and comma vector off, okay DJ here, this is the first What is the element? The first element is the manager. Okay, what is the second element? How many employees are there in the manager? Employees, then the board, then you can say neighbors. Okay, so let's first of all, sorry Pandit, what will we do first, we will make this. So, all the managers are employed here, now I am the one who is going to become a DJ, among whom is he going to become the manager, who are the employees inside this manager, right here Pushpak has made it simple, the value of the manager himself. Must have been kept that mines one must have been given because there is no head manager, brother, so manager is right, so the note is equal to mine, this one has to be put, okay, so this is our first step of the story point, after that what I said brother. We have to do simple DFS tomorrow. OK, we will pass adjustments in DFS. We will also pass information time about how much time each employee is taking. To pass the information, we will start kissing the head, who is our friend, who is the head office. Information will start from there, what is the current time? is zero, remember in the diagram it was told that the current time is zero and there we know what we will do and keep updating the max time. Okay let's keep zero in max also and what we will do in DFS is update the max sign and back side Whatever value will be returned, I will return it. Okay, now what we have to do is simply write our BFS. We have written BFS many times, so now we should not face any problem. It is okay to write VFS and now I again. I am repeating that here we do not need to visit because we are actually traversing the tree and we do not visit any note in the tree again. Directed is a graph which moves towards the bottom download. It is okay and the head idea is now, let's start from there, who is the current employee, who is the head, so I name the current employee here, write it here, how much is the current time is zero, so in the beginning, it is okay, what did I say? That all the time I will keep updating it, Max of Max time and whatever current time, now I have a value. Okay, now what we had to do from here is that brother, wherever you can go, see the note and name it Employee. Okay, interview employee as a current employee. Okay, what will the current employee do? Who will he inform his subordinates and who will support him? Okay, he will also send the inform time. It is also understood who will be the current employee. This time it will happen now, right? Current employee: This employee will be it will happen now, right? Current employee: This employee will be it will happen now, right? Current employee: This employee will be done right. Now see what will happen here. Look, who is the current employee? This is the current employee, at what time did the information come on this, it came at the time of current time plus this is the current employee, how much time does it take? I know myself, I will get him out of here, he will go in this time, we will go to him, it is clear, it is very simple, yes, they have passed holidays, the question is very simple, it is very important from DFS and interview point of view because it gives R checking if you are aware of BFS and DFS and if you are able to derive it brother how to do traversal is ok so let's convert this into BFS so see let's write BF separately here so let us remove DFS here. I will write it down here as BFS and here also BFS will do this part from the starting point. Okay, you will have to send information about who is the manager, who is the head, from where the information is starting. The current time is zero but the current time is there. We will take it in BF, okay, there is no need to pass the current time here, I will take the current time here itself, okay, so this is BF, now let's delete it and write BF. What used to be done first in BSF was to define our Okay, I told you to remember what happened in each DFS. Yesterday I went to G Note. I used to know that in how many time minutes the note information came. Okay, so I am here. Not only the note can make noise, along with the note one more inquiry will have to be taken in which I will ask how much time has been played in this note, is the make sense ok and what will I do in starting, remember what is the dot push starting from? Which is the head ID? Here I write the head ID here. Okay, this is the head ID. Remember what was the starting time? It was zero because the information is starting from the head ID itself. Starting time will be zero. Okay, now your old one. The same dirty VFS code that we have to write all the time till the time it was not done and time is equal to you dot front is fine and net foot will come neither foot off and commerce dot second is clear till here and every time I did what Told that I will keep updating in maxi, max of max time and current time is clear till now, so far it is done, I have taken it out from K, now we will have to pop it also, so let's do K dot bob here, okay now it is the same. What they were doing in DFS is that brothers go to its never, the intention is also fine, without looking, they name it employee but the look will be absolutely fine, but by what time will the information reach, it was the current time, it reached in this time plus. Who is this current employee, how much time will it take, I will get the information from here. Time is ok, current time, whose is it, current time plus information is quite simple, this is also a copy of DFS, but it is completely looped and I repeat again. I am doing this, I have not even checked the widget here because I will never go into details because this is a tweet data structure, I will always go below, let's see by submitting, let's say farewell, you pass the date, how to use it, BF. After that let's see the time complexity, its a great way to solve this question using BFS also and time compressor is very simple which is normal BF and DFS is exactly the same now look at each note we are visiting only once ok And also visiting each egg only once then linear time complexity is there its ok story is not quadratic but linear time complexity is there so i hope i was able to help you any doubt is resident in d common area and try tu help see you gas next video thank you
Time Needed to Inform All Employees
time-needed-to-inform-all-employees
A company has `n` employees with a unique ID for each employee from `0` to `n - 1`. The head of the company is the one with `headID`. Each employee has one direct manager given in the `manager` array where `manager[i]` is the direct manager of the `i-th` employee, `manager[headID] = -1`. Also, it is guaranteed that the subordination relationships have a tree structure. The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news. The `i-th` employee needs `informTime[i]` minutes to inform all of his direct subordinates (i.e., After informTime\[i\] minutes, all his direct subordinates can start spreading the news). Return _the number of minutes_ needed to inform all the employees about the urgent news. **Example 1:** **Input:** n = 1, headID = 0, manager = \[-1\], informTime = \[0\] **Output:** 0 **Explanation:** The head of the company is the only employee in the company. **Example 2:** **Input:** n = 6, headID = 2, manager = \[2,2,-1,2,2,2\], informTime = \[0,0,1,0,0,0\] **Output:** 1 **Explanation:** The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all. The tree structure of the employees in the company is shown. **Constraints:** * `1 <= n <= 105` * `0 <= headID < n` * `manager.length == n` * `0 <= manager[i] < n` * `manager[headID] == -1` * `informTime.length == n` * `0 <= informTime[i] <= 1000` * `informTime[i] == 0` if employee `i` has no subordinates. * It is **guaranteed** that all the employees can be informed.
null
null
Medium
null
135
hello everyone so today we're going to we are going to solve a question candy this is of lead code and a difficulty level for this problem is hard so in the question we have been given as there are n children standing in a line each children is assigned a rating value given in the rating integer array ratings so we have been given an integer array rating and that describes the rating of ayat children now what we have to do is we have to give candies to these children subjective to the following requirements each children must have at least one candy and children with a higher rating get more candies than their neighbors now if we look at now we have to like find the minimum number of candies that we have to distribute to uh to the children now let's look at examples so these are the ratings of three children one zero two so first children will get more candy than the second children so initially we give a second children one candy then first children is going to get more candies than the second children because it has more rating so the first children gets to candy and the last children will also get more candies than the second children so it also gets to two candies so we only have to take care about the neighboring children not any other children so this too does not take care that how many candies one got it only cares how many candies its neighbor got look let's look at the second example so in this we have been given one two so we have distributed the candies as such that we have given one candy to the first person two candies to the second person because uh it should get more candies than uh it's neighboring less rating children and the last will get only one candy so this last does not care because it's neighbor got this same amount of rating as he got so he might take less candies and he will take less candy so uh that's not a big deal so like this is uh so this is like the sample uh input now let's first talk about some few things that we must take care while dealing with this question so first thing is that let's say we have been given and rating uh like a children rating like this so in this the optimalist thing of optimus thing we can do is we can distribute one candies to the first one two candies here three candies here and four candies here so this would be our answer we just have to find the total sum of this array and this would be our answer now let's talk about another thing so let's say we have again something like this tan 5 3 1. again we will distribute one candies here two candies here three and this year and four candies here okay so thing is that in this what we did was we distributed candies in increasing order from left to right but in this we are decreasing candies uh in like a decreasing order okay so why i'm talking about this because like this observations are going to help us solving the question so let us notice another thing let's say i have 1 2 10 and not 10 let's take another integer 15 after this i have 4 and 3 so you might think what should be the answer for this so i'm telling you the answer so this will get one candy this will get two candy this will get three candy this will get four candy this is going to get one candy and this is going to get two candy okay so this is one variation another variation could be uh 1 2 10 15 uh 10 4 3 2 1 okay so in this first person we add one candy second is going to get two candy third person is going to get three candy then one two three four five and six candy okay six candy so this is an increasing array but this person is not getting four candies it is getting six candies because of this decreasing array okay so like thing is that this uh this element is colliding with an increasing array and in decreasing array that's why uh it is getting maximum of 15 comma six uh candies okay so this is it now uh let's talk about a good example a big example and see what we can do so my uh my first thing would be to like uh think of yourself write this array and copy and think with uh think of with yourself that what should be the answer for this so try to form an answer and try to like form answer in like a sequence so the sequence would be first try to distribute candies from left to right then try to distribute candies from right to left so in this in the second distribution we would see that ones who have like with a decreasing uh who whose ratings are in a decreasing order uh those requirements will be satisfied when we are going from right to left okay let's just now solve this question and this the first person is going to get one candy second is going to add two three four and this is now going to get one two this is going to get one and we are going to give him so now this is an decreasing array so we're going to give this person one this person to this person three this person has a four this person has one and then this person will get again two candies okay so this is like the optimal distribution so how we have got this distribution like can you see any sequence in this distribution so let's first talk about uh going from left to right okay so going from left to right we only care that so we will distribute one candy to the first person because minimum amount of candy should be one now if the second person is have a higher rating than the first person we are going to give him one more candy than the previous person similarly here now we can see that this person has a lower rating than the previous person let's distribute only one candy to it to this person again this person has a higher rating so he will get more candy this person has an equal rating so again he will get only one candy this person has uh like a lesser rating so he will get one candy this person equal ratings he will get one candy uh one candy similarly here one candy here so currently we have travels from uh left to right and we have only taken care of the persons who are having more candies who are having more rating okay so we are only taking care of this situation here talking about the situation in which a case could be something like this what we are going to do is now we are going to update it so we will traverse from right to left so this is have this have one candy so that is fine this is one candy this is fine so this should have more candies than its previous person right because this has a lower rating so what we are going to do is we are going to decide that it will either have one or two so maximum of one comma two so this will become uh two again this will become two this is going to become 2 as well and this is going to stay as 1 only because we don't care about the equal elements and 15 should have more candies than 10 so 15 should become 2. so this is our answer and one more thing could have been possible that let's say this 15 was so i'm not talking about let's just forgot this side let's say this 15 was initially 5 so due to this one we are trying to make this 5 as 2 we are trying to change the value of this 5 s 2 so we cannot we should not directly change the value of this 5 we should write it should be maximum of 5 comma 2 okay 5 comma 2 and initially this was only one value so we will write maximum of 1 comma 2 so that will grant a value of 2 to this 15 okay now we have done this now let's try to solve this question uh for the same array for this same array uh in vs code first so i have taken input of the array now let's just try to solve it so what we have to do is first we have to make a vector in answer of size n so let's take the size n as well in tan equals to a dot size so we have taken uh our size now we will declare the first element to be uh one okay so rest of the elements can be zero we don't care about them but we will declare the first element to be as one so a answer of 0 is equals to 1 now we are going to travel from firstly we are going to travel from uh left to right table from left to right so we're going to run a loop from int i equals to 1 i should be less than uh n and plus i so why i equals to 1 because we will see that whether 3 is greater than 1 or not then we are going to see that whether 5 is greater than 3 or not ok but we cannot compare one to its previous value because it does not have a previous value that's why we have given the zeroth index children as a value one because that is like the minimum possible candies he should have and also that will become a reference point to the further coming students so i will see that if a of i is greater than a of i minus 1 in this case answer of i will be one more value than its previous person so if you look at this so 3 is greater than 1 so how many candidates 1 have got 3 will get one more similarly in here how many candies three have got five for the children five will get one more candy now if a of i is less than or equals to a of i minus one in this case we are just going to give that person the minimum amount of candy that he should get so we have traveled from left to right now we are going to travel from uh right to left travel from right to left okay so just to be sure what we can do is we can print this array so for auto i in answer c out i with a space with an angle okay so let's just try to print it and see what is our array after first iteration we only have to make two iterations to our array so i guess yeah it just printed so you can see that we can see this is like an increasing array so one two three four after then one and 15 is an increasing array so we have got one and two candies after that this is whole a decreasing array so all persons are going to get one candy initially so we have done that only now we are now whenever we are trying to like travel from right to left we are going to take care of uh the persons who have like greater rating than the next person so what we are going to do is for in i equals to n minus 2 so we are looking at this person is going to look at previous person so we cannot start from the last person because last person does not have any other person to look upon so this person is going to look on uh the next person so i should be greater than equals to 0 minus i and what we're going to do is if let's say if a of i is greater than a of i plus 1 so if this is the case answer of i would also be uh will always be answer of i plus 1 so this person has more rating than the next person then this person will definitely get more candies than the next person okay so we have done this after this what we're going to do is we have to write another condition if a of i is lesser than or equals to a of i plus 1 so if this person is like uh so a case like in this case right so if this person is lesser than or equals to the previous person so in this case we are just directly going to continue why is that because uh we only we already have taken care of that cases in like the previous array so if there are some changes made by this iteration we don't want to change it here that's why we are just directly continuing it and even though like if we have not written this statement that would have been fine as well let's just again try to print this array so you can see that this is now the final array and if you try to compare it one two three two one two three uh so wait a minute this should get more candies than that so i guess we have done some kind of error let us check up on that one two three four we have changed it okay so what we have to do is we have to write here maximum of a of i plus one uh comma answer of i okay so i guess now we should not cause any trouble we uh i've already talked about this that we should write this maximum statement so you can see that uh when like we have not written the maximum statement it have changed the value this value and changing this value will cause us trouble because you can see that this is an increasing area and we have changed the last value so that's why we have to always write this maximum statement here now that we have done it i guess this is it now our last step is to accumulate uh all of the values uh or to take some of this array so in c plus there is a function called accumulate through which we can take the sum of our whole array so let us copy this statement let's make let us comment this as well so let us copy it and let's go to lead code we have pasted it let me do this as well and at the end we are going to return accumulate answer dot begin comma answer dot and comma zero so i guess this is it so this is running fine and for our given array as well this is giving us the correct output the x at the accepted output now if you try to submit this it will also get accepted so it is getting accepted and uh like whatever like we don't care about this thing we only care about the overall time complexity and overall time complexity would have been only big go of n also if you look at the description so constrain was uh this is 2 into 10 to the power 4 so we are doing it under uh 2 into 10 to the power 4 we go of 10 to the power n that is fine so this is it if you have any other doubt please feel free to ask it in the comments okay so thank you
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
1,373
hi friends welcome back today we are going to solve one of the hard coding interview problem on lead code which is frequently asked by big fan companies it's on lead code 1373 maximum some bst in binary tree so this is a hard coding problem related to binary tree so if you are preparing for coding interviews make sure you watch this video until the end so that you will completely understand the logic to solve this problem because this is a very important uh problem from inter coding interview perspective uh so we will go through the problem statement will understand the problem with a few examples and i'll explain you the logic how we will uh solve this problem using java and we'll discuss the java solution in today's session uh before we start looking the problem details i want to mention that my channel is dedicated to help people in their java j2 and coding interviews on my channel you will find lots of helpful videos that can help you in your java and coding interview preparation such as there are over 400 different varieties of solved problems which are coding interview questions previously asked by google facebook amazon apple microsoft yahoo and many other big tech companies and those are selective problems to constitute important coding questions for ids such as bfs dfs matrix problems craft problems binary search term related coding interview questions as well as questions uh related to linked list strings optimization problems using priority queues and lots of logical questions so if you are preparing for coding interviews or java interviews this channel can definitely help you in your preparation so please subscribe to this channel now so let's start with this lead code 1373 hard problem maximum some bst in binary tree so as you can see from like dislike ratio this is a very likable problem and very interesting problem as well so let's start so given a binary tree root return maximum sum of all keys of any subtree which is also a binary search tree vst right as soon as bst is defined as follows the left subtree of a node contains only nodes with key less than the nodes key right like less than the node's key right subtree will contain only nodes which are greater than the nodes key right and both left and right subtrees must also be binary search trees correct both has to be binary search tree then only that can be a binary search tree right so they have already told us what all the properties important properties of a bst and then they have given us this uh two three examples and let's just look at the constraint and we'll discuss the examples on whiteboard so number of nodes in the tree is in the range of 1 to 4 into 10 raised to 4 so if you consider this range 4 into 10 raised to 4 can be really a big tree right so we have to implement some efficient solution and the value of each node can be between minus 4 into 10 raise to 4 and 4 into 10 raise to 4 inclusive right so these are the values that the node can have so let us take this first example here so we will understand what the problem is uh what is the problem basically that we are trying to solve will discuss here so this is the binary this is the tree basically this is the binary tree that is given to us and we have to identify uh such a binary search tree in this tree so that it can have the maximum sum right maximum sum so for example if you look at this tree right this subtree for example right this is a binary search tree right this is one subtree how much is the sum for this subtree uh it is 15 right 15 is the sum for this subtree then if we uh consider instead if we consider this whole tree now whole subtree now right so how much is the um sum for this is the binary search right three and left subtree is two so it is less than three and right subtree all the values are more than three right four five six so this is also a binary search tree what is the sum 15 plus 2 is 17 plus 320 right 20 is the sum for this subtree now if we consider this uh subtree right this is also this is not a binary search tree right because uh their property that they are saying is the key should be greater on the right side right so now here the 4 is not greater right here the root is 4 this 4 is not greater than this 4 right so this cannot be a binary search tree basically so which means that the largest sum that we can have here is 20 correct 20 can be the largest sum so as you can see the first example they are saying the maximum sum is 20 right that's how the sum is calculated so first they identified the uh binary search tree and then they calculated the sum and this is the maximum sum binary search tree right so ah so we have just visually uh solved this problem by looking at the tree right so one other thing also i wanted to mention is any single node also can be a binary search tree for example this six this itself is a bst basically right this itself is a binary search tree if you just consider single node is a bsd right this is also bst this is also a bsd right this is also obviously this also bst so these nodes are bst these are leaf nodes right so those can be considered as a subtree which is a binary search tree right so um let's now discuss how we can solve this problem right so um we will be using a recursive approach to solve this problem and how our recursion will work uh so i'll tell you uh so before we go and look into that details i also wanted to tell you one other property that they already mentioned here right they already mentioned that both left and right subtrees must also be binary search tree right so for example this if we want this con this whole sub tree to be a binary search tree it means that its left subtree which is this and its right subtree which is this they both has to be by like binary search tree then only this whole subtree can be a binary search tree right if left or right subtree is not a binary search tree it is not possible that this subtree can be a binary search tree right for example if we change this 2 to 20 here let's say right then this cannot be a binary search tree right because 20 is bigger than 3 right it cannot be bigger than 3 right it has to be smaller right like this or for example if we make this uh 4 into 1 right let's say this is 1 then this right part is also not a binary search tree right because 1 is less than 3 right so it cannot be a by bsd right because these values 5 1 6 these all three values should be more than 3 then only it can be a binary search tree right otherwise it cannot be a binary search tree so that is one important property to understand so now we will go and we will discuss how we can solve these problems so basically to solve this problem um we will need always three things right as i just explained you what are those three things we will need uh three val like we will need the minimum value of the subtree that we have seen we will need a maximum value of the subtree that we have seen and we will need some of the subtree correct some of the subtree if it is a binary search tree correct otherwise the sum will be zero right for example so we will use a array so that we will bubble up from bottom to top right we will go like this and we will keep calculating the minimum and maximum of every sub tree and some if it is a bst right so in the beginning we will just say minimum will be uh like integer dot mean value right and maximum will be integer dot max value right and sum will be zero so how it will work let's see now so now for example if we are at this four right so in this case the minimum value is four the maximum value is four and this itself is about bst right four is a bst and sum will be four correct some will be four now when we evaluate for six the minimum value for this binary search tree is six maximum is six sum is also six correct for that node now let's go uh here now right so when we reach here we wanted to first uh we have we know the left values right we know this is the left subtree for 5 right this is the right subtree for y5 so we know the minimum and maximum value for the um left and right subtree correct so we will check if this is this a bst so we will check the 5 with minimum value in the left right so this minimum value so this is less than 5 right so it is fine which can be like which is a possibility in bst now we will check maximum value of right side so maximum value is 6 right so sorry so minimum value we will check is 6 here so minimum value is more than 5 right so it is fine and maximum value of left side is 4 which is less than 5 right so it means that this can be a binary search tree basically right this assures us this minimum and maximum values that this is a binary search tree right because the left maximum value of the left subtree of 5 is 4 which is less than 5 and max and minimum value of right subtree of 5 is 6 which is more than 5 so it is guaranteed that this is a binary search tree right so once we know that it is a binary search tree we are just going to again do the min max for this subtree so what is the mean for this subtree the mean will be four correct the mean will be four and max will be six correct for this subtree how much is the total we will get so we will get four from this side six flow from this side and we have to add 5 for this root right of the subtree so total will be 15 now some correct sum is 15 now for this subtree right so similarly when we are looking at this 2 now correct let's say we are looking at this 2 i am just changing the color so now this 2 itself is a binary search to write only single node leaf node so again we will capture the mean value for that is 2 max value for that is 2 and sum for that is 2 correct now we will try to evaluate for this whole subtree right whole subtree we will try to evaluate correct and we wanted to check if this subtree can be a binary search tree or not right so now how we can sure that the left subtree value we will check now the left sub tree is this one right so this is the maximum value of this is 2 which is less than 3 right 2 is the maximum value which is less than 3 which is fine for a bst now we will check the minimum value of the right side tree so minimum value of the right side 3 is 4 right 4 which is more than 3 which guarantees that this is a binary search tree correct it guarantees that this part this subtree that we are looking is a binary search tree now right now uh since it is a binary search tree we will get to calculate the sum so now as a 5 we know that 15 is the sum 2 we know the 2 is the sum right so 15 plus 2 is 17 plus 3 is 20 right so 20 is the sum as of now right the minimum of this will be 2 here the maximum in this tree is 6 correct 6 is maximum now when we are now looking at this part this is not a binary search tree correct because this 4 is not greater than this 4 so it will just give you give us 0 as a sum right 0 and here it means that left subtree is not a binary search tree it means that this whole sum will bubble up here now right the 20 sum we got here for one itself is zero we will add right zero plus 20 which is equal to 20 correct so 20 is the maximum sum of a bst in this binary search tree correct so as you can see that's how the 20 sum comes here right so i think you got the idea how we can implement the recursive solution so we will use three like we will use integer array to capture this mean max and some values right and always our recursive solution will bubble up from bottom up right bottom up so we will keep calculating uh the maximum sum of bst right that way so um this is the way we will be solving this problem so um i think we'll just go ahead and we'll take a look at the java solution now the recursive solution that we have so first we'll just define our result it is the integer dot mean value right result is actually we are going to return at the end tree node root is given to us and we will just call our helper function right this is recursive function we are going to call and now as i mentioned you there are three things we wanted to keep track always right for every valid binary search tree what is the three things we wanted to keep track of minimum value in that subtree maximum value in that subtree and some of that subtree right so these three things so let's go ahead and take a look so first if root is equal to null right if root is null for example if we come here right this left side and right side is null right so in this case what we will get we will just get integer max value here integer min value and 0 because this will give us 0 as a sum right this is 0 sum basically 0 sum here right because 4 itself just 4 is a leaf and it is a binary search tree itself right so that is a binary search tree so this way we will keep track of this first thing is the minimum value we will this first is minimum value the second is maximum value of the subtree and this is the sum right so let's keep going so you will get more clarification as we look uh details so now here we will call recursively our helper function on the left side of the root right here will calling it on the left side of the root we get the integer array here right integer array is a left and we'll call it on the right side of the route we will get integer array right now three things we will get always right as i shown you here four means minimum maximum and sum for that subtree right three things we will get now once we get these three things first thing we wanted to check if is it like a valid binary search tree or not right how we will know if it is a valid binary search tree we will compare the root value with the maximum of left sub tree if maximum of left subtree is greater than the root value it cannot be a binary search tree right it has to be less than that value of root right or if the minimum of right subtree if it is less than the root value then it cannot be binary search because right subtree of that root should have all the values should be more than the root right if it is less then it cannot be a bst or binary surgery write if that is the case then we will uh just directly written here integer dot mean value integer dot max value and 0 as the sum correct 0 as the sum so you got this point right because it is not a valid binary search tree right after that if we reach here then it means that we found a valid binary search tree so we have to add the sum of left subtree sum of right subtree and root value correct that's what we are doing here right so sum of left sub 3 for example 4 here then 6 here and then 5 here right so total is for this subtree 15 correct so that's what we are doing here this sum we will calculate here and we will take the maximum between result and sum because we wanted to capture the maximum sum of the bst right so that's how we will keep track of maximum sum we have seen so far in the result variable here and after that one is done uh we will just return math.min of uh we will just return math.min of uh we will just return math.min of root.value and left of 0 correct left of root.value and left of 0 correct left of root.value and left of 0 correct left of 0 and root.value we will return that is 0 and root.value we will return that is 0 and root.value we will return that is the minimum right and maximum will be root dot value and right one means it is the maximum value left zero is minimum value right so uh this way we will get the minimum value of the subtree this is the minimum value of the subtree and this is the maximum value of the subtree right the right subtree right maximum value of the subtree and sum here basically right so minimum value of the subtree maximum value of the subtree correct and the sum here that we will bubble up basically right so uh that's how the like the recursive function will work and at the end here we have to just check if we result is less than zero because we assigned it less than zero right integer dot mean value then we'll just simply return zero otherwise we'll return the result as the maximum sum bst correct so um i think uh i explained it in details about the solution how we can use the three elements in the array mean max and sum uh and the logic to uh solve this maximum summary bst in a binary search tree in a binary tree sorry so let's go ahead and execute this code snippet the first this example that we have seen so let's just run this code so i'm just printing some to show you how the sum will come bubble up right so far first this two is there right so first uh two sum is coming right four sum is coming so two and four it is getting added as six here right so this is two correct this is four then this one has the sum six right so total sum here this left sorry right subtree five four six sum is fifteen and total this highlighted blue subtree will come to twenty correct sum is twenty so maximum sum uh binary search tree is 20 here so we are getting correct answer here so um i just created another uh test case to show you one uh one other uh example here so this is the test case we will run now in this case as you can see this is this cannot be a binary search tree right because 400 is more than 200 so this is not a binary search tree right this one is the binary search tree right because 50 20 and 80. so this is a valid binary search tree if you calculate the total sum of this uh subtree it is 80 plus 50 130 plus 20 is 150 is the total sum but we have to remember here that 150 is not the maximum bst here because every leaf node is a binary search tree so in this case 800 is the maximum sum of a binary search tree and not 150 right not 150. because 800 is more than 150 right so we will just take ah take this example and make sure our example also works and passes our test case so this is one of the cases right where the leaf node itself is more value right than other sub trees so as you can see it calculates the sum 150 here also other sum is 400 for this node right but maximum is 800 right so 800 we are getting correct answer it is accepted so let us just go ahead and uh execute there all test cases and we will just comment out our system out so that we can submit our solution so 22 and 0 which we are getting correct answer for all the test cases we can just go ahead and submit our solution now so our solution got accepted by lead code it is 18 faster than other submissions and 25 faster on memory usage uh so this is a quite hard problem to solve um so that's why it's in the heart category and a lot of times asked by big tech companies uh so i just thought that it's worthwhile to create a video so people can watch the solution and get you know benefit from the video they can understand how we can implement the java solution for this problem using recursion and with the help of the logic that i explained you with the help of these three array elements min max and sum right uh so um if you are new to my channel there is a dedicated playlist on my channel called as lead code and lean code solutions uh it has over 250 varieties of solved problems taken from previously asked coding questions by google facebook amazon apple microsoft yahoo and many other big tech companies so if you are preparing for coding rounds of interviews please go through those videos that will definitely boost your confidence those are uh videos shown in like a white boarding sessions for your easier grasping and understanding and varieties of problems are taken there for your uh that can definitely help you in your interview preparation if you still want to practice more problems there are three other playlists on my channel namely code forces code chef and add coder so all and all you will get more than 400 different varieties of problems those problems includes bs bfs dfas matrix problems graph problems binary search related coding questions related to optimization using priority queues linked list strings as well as lots of logical problems so um if you like this video if this video help you in understanding this problem in an easier and better way using this white boarding session then please give it a thumbs up or give it a like to the video subscribe to the channel your subscription to the channel is really important for the channel because that is the way the videos can reach to more people who need help in solving coding problems one of the main goal of the channel is to help as many people as possible in their coding problem solving by demonstrating and showing them how different varieties of problems can be solved using different techniques and using different data structures and java so if you like this video give it a like share it uh with as many people as possible who can benefit from these videos if you have any questions related to the video put your questions below the description section the java solution that we have implemented for this hard problem this solution i am going to put this solution in my github project and give you the link in the description where you can check it out and play with the code with different test cases for your better understanding also if you like my java solutions please consider giving it a start to my github project that would be great uh to become more and more confident with different uh like uh in your coding interviews try to solve different varieties of problems that will uh give you more exposure to different varieties of problems and will boost your confidence also one simple tip is when you are implementing the solutions try to use like white boarding and try to use the uh like try to handwrite the code instead of using ides that will definitely boost your confidence in real interviews and in your coding and like whiteboarding interviews also comment back on the video so i will get the uh i'll get to know uh you know how my videos are helping you because it's important to know if how my videos are helping the audience so please comment about the video and give it a like if you like this video uh share this video with your friends and colleagues and keep watching videos keep learning java and different varieties of problem solving and thanks for watching this video
Maximum Sum BST in Binary Tree
maximum-sum-bst-in-binary-tree
Given a **binary tree** `root`, return _the maximum sum of all keys of **any** sub-tree which is also a Binary Search Tree (BST)_. Assume a BST is defined as follows: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The right subtree of a node contains only nodes with keys **greater than** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[1,4,3,2,4,2,5,null,null,null,null,null,null,4,6\] **Output:** 20 **Explanation:** Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3. **Example 2:** **Input:** root = \[4,3,null,1,2\] **Output:** 2 **Explanation:** Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2. **Example 3:** **Input:** root = \[-4,-2,-5\] **Output:** 0 **Explanation:** All values are negatives. Return an empty BST. **Constraints:** * The number of nodes in the tree is in the range `[1, 4 * 104]`. * `-4 * 104 <= Node.val <= 4 * 104`
null
null
Hard
null
1,269
hey welcome back today we're discussing problem number 1269 number of ways to stay in the same place after some steps we are given two integers steps and array length we need to uh calculate the number of ways possible so that uh you will end up being at the same place where you started after taking the given number of steps so we are given an array of length n and we need to take Step at each place so that after end steps we end up being at the same place right uh same given uh starting point we will always start at the zero index so in this example uh so this is of array of length two so initially you'll start at this point so after three steps you should come back to this point so we need to calculate the number of ways possible so at each step you can uh stay in this place only or you can move towards right one step or you can move towards left one step so for this the possible number of ways given us four let see how so one possible way is at each step for all three you'll stay at the same place stay so that if you don't move then after three steps also you'll end up at the same place so that is one possible solution and the second possible solution will be you can move right side moov on right side here so you have taken one step so you need to take uh two steps more so that uh you can uh stay at the same place so now your still at the one index you can move left right so this is the second possibility and the SEC third possibility will be move right side move left side and you can stay at the same place right so and the fourth possibility will be first step you will stay there only and you will move right side and you'll move left side so these are the four possible ways so that you'll reach the same starting point after end steps so I mean if you take any other possibility and if you go right if you go left and if you go right then you'll end up at this position which is not the starting position so similarly you can take uh you can move left but it is going index out of bound so you cannot move a left side because you are at extreme starting of this position so you can move right you can stay andan you cannot move right from this place because the maximum length is of two only so you can stay there only this is the third step Still we are end uping uh we end up at uh first Index this is not uh the answer we want so we not we don't consider these cases so similarly we have I mean many states where we end up at one index so those States we don't consider so these are the only four states where uh you end up being at the zero index after performing insts so if You observe this so if you uh take the uh recursive formula for this so this is a recursive solution so if You observe the formula will be so at every St you need to uh reduce one step right so number of steps minus one so steps minus one and then you can move right or you can stay there or you can move left so at every place you'll be having three possible ways right so yeah when uh when you reach I mean when you're are out of steps when these steps equal to zero when you have taken all the steps and when you at the index zero this is when you got the answer right so this is where you will return this return one step so this will be the base case that we will search for and we will write this request so let me uh write this pseudo code and then so we will uh start at index0 and calulate for given steps right so we will call a recursive function like with call helper function with zero index and remaining steps as steps so we need we so right now we're at I mean anyhow the starting point is zero only and we need to take these many steps right so in this function if so let me write a recursive formula first and then we can check for the base cases so helper at uh from I index if you have to take 10 steps the possibilities are three possibilities right equal to help for it so you can move forward and you can reduce the steps plus the second possibility is you can move rightwards and yeah you can you need to reduce the steps and the third possibility is you'll stay at the same place and you'll reduce the steps right so you need to add all these values mean these are the three possible ways and yeah this should be our answer so what is the base case if we found the answer if we have completed all the steps and if steps equal to zero right and steps is equal to zero and then I is equal to zero also I mean I being the index that we read so then only uh we have achieved our Target right then we will return one so there this is one way you can achieve this right so apart from this if you go out of the bounds I mean if you go left side if I is less than zero then there is no answer so we can return zero right so yeah similarly uh or if I is greater than or equal to length also we will uh return the same right so this is the so apart from this so there is one more Bas Cas that we need right so if here we are reducing the steps right steps are negative if we have taken all the steps if steps are less than zero then also we need to return zero so this will be uh the sudo code but uh See since we are calling the same helper function uh and there is a possibility of repetition so we can memorize the states so I'll explain it how we do it in the while writing code so we can memorize the STS so that we can reuse it without calculating again so here let me call helper function with we are starting at zero with index and we need to take these many steps with array of length this one so before that uh there is one more thing so here if you see uh the number of steps are in range 500 and array length is of 10^ 6 range 500 and array length is of 10^ 6 range 500 and array length is of 10^ 6 so let's say if we need to take 500 steps and if the given length is 51 so mean if we go to 51 then we have already completed uh 500 steps so there is no point going back right so at Max we can go is for mean is to number of steps only so even though if we have array of length so let me annotate once so let's say we have array of length 10 and we need to take steps five so even uh so yeah even though we have a array of length 10 if you see half mean if you uh take only right you'll come till here then the steps will be become zero so you cannot go back from here also right so these you know need to consider because anyhow uh at Max you can take number of steps only so yeah so we can update this uh array length at the starting itself so that we don't need to uh consider the extra array that they have given because it would be anyhow uh I mean take so much space and add to our time complexity right so anyhow we know that at Max we can reach till this position only to cons I mean to be one of our answers so yeah so let so we will update this array length value to the minimum of so array length will be math do minimum of steps comma ARR length right so I hope you are clear on these steps why we have taken minimum of these two so let us uh write this help function which will take the I index call it I only steps and AR and so this case will be if I is less than zero or I is greater than or equal to eror then we return zero right so if the second one will be if steps are less than zero then also can return zero because we have already crossed the number of steps if we found the answer if we found one way if we have reach the first index and number of steps are equal so we can return one now our answer will be we will call this function helper function again and right now we write the same index and let's increase Let's uh decrease the number of steps we have already taken one step we are staying at the same place and let's this and this is one possibility and the second possibility will be answer plus helper of we'll move right side minus one of so this is one possible answer and also the last possibility is answer equal to answer plus of we will move towards left side and let's repas the steps so these are the three possible States so the question they have given that we need to take modulo because the answer might be very high so at every step take mod I'll Define that mod this mod will be equal to they saying 10^ 9 + 7 of 10^ to they saying 10^ 9 + 7 of 10^ to they saying 10^ 9 + 7 of 10^ 9 + 7 so this will be it we need to return on the answer so this is the recursive solution let me run this okay there is where L is not defin capital letter let me see where okay so I mean here it should be and right and we need to reach the first index and steps also need to be zero so by mistake I've written over so I guess that's the mistake that we have done yeah so now uh me I definitely it will not get accepted if we submited because in here we have so many repetitive so let me uh show you so initially we started at zero come on let's take uh ns5 right number of steps say so we will uh do same zero and 4 and 1 and four and Min - one and four so these are four and Min - one and four so these are four and Min - one and four so these are the four possible uh B we'll call this recursion and then from 04 we will call 03 or 13 or Min - one and 3 so here we'll call or Min - one and 3 so here we'll call or Min - one and 3 so here we'll call 1 3 2 3 or 03 when you move left side so if you see uh there are so many repetitive calls that we are doing one three also is getting repeated so if we extend it further there will be so many calls right this is the recursion tree so this is Rec so yeah if we solve this so Let Us store it in some memorization so that we can reuse it further so I mean when you'll understand this DP problems using memorization and DP once you solve it first through recursively and then go doing it in memorization and then uh apply DP so here for memorization array let me take it here I'll take 2D array to store uh number of steps and length so this will be our and let us initialize this do memorization equal to new in of uh we need to take steps plus one because we need to are each still steps and then array length why we have taken plus one because we need to uh reach to that step right we should not I mean if we take this only we have an index of steps right so I'm just giving some negative value I minus one value so that we will identify which value we have calculated or so I ++ arrays dot ++ arrays dot ++ arrays dot fill memorization of I with minus one so fill all the arrays with minus one and here if you have already calculated this value if memorization at steps and I if this is not equal to minus one then we have calculated this value earlier so we can return memorization steps this one so before returning we will car we put this in our memorization Matrix at I index equal to our answer quickly run this there are any issues no let's quickly submit so yeah so got accepted but uh I mean the memory we can do better uh by using DP and avoiding these recursions so for DP uh if we want to convert this memorization solution into DP right so what you need to do so you understand uh here um we returning a helper from zero to the number of steps right so this will be I'll just give you a DP formula you can calculate it yourself so the DP formula will be at the zero index and you need to return the number of steps so this will be the DP solution and DP at I comma J will be equal to so dp8 I and J minus one plus DP at I and DP at I + one and J minus one and also DP I + one and J minus one and also DP I + one and J minus one and also DP at I minus one and J minus one so base case will be uh I mean if you're at a zero step and zero index so that is one possibility right so this is the base case and with using this you can fill this so try it yourself uh the solution but also this memorization solution also should get accepted should be okay for in your interview also because both time complexity and this complexity are same but yeah try doing this solution also yourself yeah thanks for watching see you in the next video
Number of Ways to Stay in the Same Place After Some Steps
market-analysis-ii
You have a pointer at index `0` in an array of size `arrLen`. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time). Given two integers `steps` and `arrLen`, return the number of ways such that your pointer is still at index `0` after **exactly** `steps` steps. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** steps = 3, arrLen = 2 **Output:** 4 **Explanation:** There are 4 differents ways to stay at index 0 after 3 steps. Right, Left, Stay Stay, Right, Left Right, Stay, Left Stay, Stay, Stay **Example 2:** **Input:** steps = 2, arrLen = 4 **Output:** 2 **Explanation:** There are 2 differents ways to stay at index 0 after 2 steps Right, Left Stay, Stay **Example 3:** **Input:** steps = 4, arrLen = 2 **Output:** 8 **Constraints:** * `1 <= steps <= 500` * `1 <= arrLen <= 106`
null
Database
Hard
null
32
Loot gayi welcome back to my channel and you were going to year longest white paint is so is this voucher mein giving kya hai that aapse ek team de rakah aur us add tyother in the self less hai aapko yahan par karna kya hai find karna hai dil length Of the longest valid value from different this substance ok fennel september palace you will see illegal something what is this your open retrospective its time kitna hai to hai then you are going to get cancer now in mechanic sambal you will see here this pin of yours back to back superhit black and For closure, you have to submit total, this is how light it is, the answer is small, this is an exam, it is a busy day, it is okay, so after the first service, it is not just used, it cannot be so what we are going to see here is for Solution: Those tabs are going to be see here is for Solution: Those tabs are going to be see here is for Solution: Those tabs are going to be ours, so let's see how we can use them, what should we do now, these tax collectors are okay, for this we are in this set which is going to be the value supporting point air tight, okay so. Initial sarcasm - I will leave my hands, now we Initial sarcasm - I will leave my hands, now we will see why we start with minus one. So, what is the application that we are using here, whenever you have a close bracket, then remove the top element below it, okay then check. Do what is the stand, what if it is empty then in that condition you will store the index at which this element is at whose index. If your ant is not there then after topping then you will point your maximum length and whenever you have to open If you get like it, what will you do in that condition? You will be on this index. Play that index. You will leave it here. Okay, it is possible that you will get what is in the initial itself. If you get close here, then what will you do? You will do it to the top element. So the top element here will be something otherwise what will we do here - what will we do here we will what will we do here - what will we do here we will what will we do here - what will we do here we will store it so I stayed 202 man let's start we will chat tower chana here this 0123 450 this is ok so what will you do this You have to click on here maximum here how to do this so that - 2 - 02 till now here - 02 till now here - 02 till now here then you will try to remove it so that it will give quota in the topic and check. There is no entry because whatever is yours then what will you do in this condition on which the index will be for - top element 1000 or I will be for - top element 1000 or I will be for - top element 1000 or I thought then why are you better like this then the maximum is going to be yours then after that we will move ahead here. Here is your close that top level has this entry of removing something then what is it will leave its index here, after that do you have an element, otherwise what is the maximum till now, what will be your fold then 4G is your answer. Okay, so let's look at it and let's see what Saurabh is doing, we are taking the extract here, initially we took the step minus one share, set it here, then this is the maximum length of yours which will track the maximum blackberry, we have taken it here now. What we will do is we will travel through each element and check if it is already open by using the number and paint, then ask in the set and have done that index. If it is not there, then what can we do by pausing the laptop element and then check what? Is there an exception to this? If it is empty, then give the injection inside. Otherwise, if there is no entry, finalize the maximum length. If we bury it, then what will we do here. If we do a school here, then this is our 1 inch. Now we are going to come to the second approach, okay let's see that also and what we are going to do in that is we are going to use it on the two barriers, okay so what we will do here is once we will rice from the left side, once what we will do from the right side. We will rice where we get the maximum, if we get the maximum length, the person in front of us will see what is going to happen in this, the mother and approach, what will we do here, we will do the place and open practice, we will account here and will rice from the left side. When we do rice from the side, what will we do? We will update the cord here, okay, after updating, we will see that whenever there is equal, we will multiply it by two as per our night account, that will be our maximum light till now, okay There is as much account as there can be, whenever both become equal, if not equal, if in any case, yours is closed, yours is more. See, when you walk from this side, you will always keep in mind that if we open first, we get the light, then we will have more in our account. That is right, it is normal, but the arts tree of the class, if the account is more, then it is not normal. It is fine from the left side, so we will keep in mind that if the close is more, then what will we do? Treat both of them or use the stairs. Like use Damini in a corner, you will get more, what will you do with open, it is okay with the pairs of likes of both, so come here, what is a glass on you, close will open here and yours is still zero, okay So what is open here? Follow is too much, again you will do 2010. Here, the one who drops zero will move ahead. What is open here? Open will be your one. Then what is yours here? What is yours here? It is done. The class is done, okay, it is closed here, so what will happen after crushing here, both have become equal, the light has become equal, so what should I do now, come here and multiply the murder time by the hours, the same account is still there. So it's done, okay then it's going to move forward here, you're going to move forward here, so now what's going to happen is yours, it's going to break and what's going to happen here, it's going to be yours, close button, it's going to be two, okay, so what are you going to do here. You will multiply your account, what will happen to you, it will become fore, light phone is about to be launched, till then you have got the work actor, then you will come here, so is this your close, please, if you have got too much, then we What will we do by which we will launch the missile, otherwise we will not check if there is an element ahead, now we will see from here, once we will do rice from the right side also, the tower will be born from the right side, then we will keep in mind that what is considered open is not much. It should be open, we do n't want more than this side of ours, this plan should be launched, if it is more, then it is right that it should not be open, if what will you do here, what will we do with both of them, again we will slice it to 0, okay then half from now, please what about us? It is, it is, and open, we are busy here, no problem, time is broken here, play, open, what is ours, it will be open, we are here, we are going to move from this side also, then what do we do, so here, what did I do here? If you do then please like and share. So here's what we will do. Close the plus. Are we going to subscribe or Ajay has a semi? Then the account that will be here will be started here in the maximum lines. The maximum light which both of them had earlier. Whichever of the two will be maximum, that will be the final location. If the close is your statutory world open, then in that condition, you will sacrifice the open, make it zero and close it, do that. I am fine, follow the people of the districts, they will make it of these sizes, this is ours, this is done. From the side, now for the right side, number those watching on the right side. Let's start the open and take out the then who is going to watch like going to watch, then who is going to watch like open will get open plus but what will we do then like and feel you What will we do? What is the maximum light till now? If you open, if we are moving from the right side, then it should not be inside us. If we get a grate on the right, then we will do it because of . We will open CL here. then we will do it because of . We will open CL here. then we will do it because of . We will open CL here. Okay, this is our fabric. What will happen to you in this? Space complexity is not a problem, it is just wasting your time. If you are a city woman, then what was there in the entry? You were also using the same style as you. You have written less space for this. Why was it in this and the problem of saving time is also that it is your device. If you look after time complexity then what is both the semi's then you have been selected thank you.
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
993
Hello hello guys welcome back two years in this video will see the present in every problem which date of the match of the problem 9099 half plus one note subscribe must be unique and different return true values ​​will find weather to give one unique and different return true values ​​will find weather to give one unique and different return true values ​​will find weather to give one official subscribe The Channel And subscribe The Amazing After 30 Minutes From Root And Night Images From Lives In This Is The Best Wishes To 9 To 12 12232 notes38 subscribe The Channel Please subscribe and Share and subscribe the Channel को subscribe and subscribe the Channel को subscribe and subscribe the Channel को subscribe The Video then subscribe to The Amazing Different Ki And Should They Are Not Against Her [ __ ] [ __ ] Ki And Should They Are Not Against Her [ __ ] [ __ ] Ki And Should They Are Not Against Her [ __ ] [ __ ] Mom Six Patience Have Different Parents But They Are A Different Way Also Know No Fruit Is Equal To Towards Parents Variable And They Will Also Give Proper Height Will Not Take Away Electronic Option Will Decide On Birthday Wish Pass Reference Okay So Wherever I Find This Point In Its President Will Start At This Root Will Not Discussed With Just One Example Will Start From Root Which gives the true value subscribe to the Page if you liked The Video then subscribe kare super top axis one know and where reduced to know what is this to equal to and actor will now you can dare I will make different in single app will Update the journey to the present will be no veer the main function will subscribe and subscribe the Channel that porn updating first flight will be 0share height will be positive way Single phase will not want to this site will know again it will be 2 and this point ok this point 494 will return 12218 is not 2 and have returned from this left will check return value 200 syndicate that is the value subscribe to the Page if you liked The Video then subscribe to the Page Receive All The Best Value Solid Will Be Received To And Use This Parents Reference And You Can Withdraw Support You To Which Is The Scientific Information Required For This Way You Will Repeat 10 Ways Subscribe So Way Can Make A Call From This Cream And They Will Not Find A Way Will Celebrate 1020 From Left To Right Side Subscribe Now To Go For Boys Play 209 This Country One Is Receiving Zero From Left Call It Know That We Have Not Found And Value In the factory at will make a call to the tree to make a call to three not three vikram 2069 solar will make a call from 60 to avoid making this will be adding one to the 12th part plus 2 and you will be returned from subscribe school Will Stop This Is To Subscribe 9 Spider Man Function They Have The Information Which Will Require Parent Of Actions And The Height Of Experiment After Values ​​Of Why Height Of Experiment After Values ​​Of Why Height Of Experiment After Values ​​Of Why Not Shown How The Parents Getting Updated But Actually Before Making Their Equal Parents Will Get Updated With The Current Value From Parents Will Come To Know Who Will Just Compare The Same Special Subscribe To This And Different Subscribe Vaccine More Time Complexity After Front Of You Need To Travel Tours And United Against Eve Kunwar Singh Price 100 Time Complexity They Mode Of And Know Latest Look At The Code In Order To Get A Better Understanding So In This Code You Can See But Vir Value Subject Must Subscribe Like Share And Will Make A Call To The Element Subscribe Do Subscribe - Will Return Of The Day Subscribe - Will Return Of The Day Subscribe - Will Return Of The Day In A Pan After Finding Both Variables Will Check and return appropriate value Selective look at the received call 100 This is the developed call as you can see in Desh Ke Is Veer Will Be Constructed As A Parent subscribe to the Page if you liked The Video then subscribe to 200 ft do not mind element and will make different elements of parent because the elements to be defined as its president below the current president will be co current month will now let me love you can see plus One will increase after returning from this is Vivek subscribe The Video then subscribe to the Page if you liked The Video then subscribe Kare Quote Understanding Now IF YOU HAVE ANY OTHER APPROACH OR SOLUTION IN DIFFERENT LANGUAGES PLEASE COMMENT BELOW SHOWS THAT Everyone Can Take Benefit From Its Like Share and Video subscribe our Channel thanks for watching this Video not MLA
Cousins in Binary Tree
tallest-billboard
Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._ Two nodes of a binary tree are **cousins** if they have the same depth with different parents. Note that in a binary tree, the root node is at the depth `0`, and children of each depth `k` node are at the depth `k + 1`. **Example 1:** **Input:** root = \[1,2,3,4\], x = 4, y = 3 **Output:** false **Example 2:** **Input:** root = \[1,2,3,null,4,null,5\], x = 5, y = 4 **Output:** true **Example 3:** **Input:** root = \[1,2,3,null,4\], x = 2, y = 3 **Output:** false **Constraints:** * The number of nodes in the tree is in the range `[2, 100]`. * `1 <= Node.val <= 100` * Each node has a **unique** value. * `x != y` * `x` and `y` are exist in the tree.
null
Array,Dynamic Programming
Hard
2162
875
Hello Hi Everyone Welcome To My Channel And We Are Going To Solve Very Important Interview Problem Making Meeting So Let's Move With His Problems Very Important Co * Move With His Problems Very Important Co * Move With His Problems Very Important Co * Company Subscribe Important Meeting Is Company Subscribe Problem Solve Problems subscribe and subscribe the Video then subscribe to the Page Meeting This Is That Was Very Important So Let's Go Through This Problem And Subscribe Our Channel To The Solution Subscribe Welcome Back Side Meeting Speed Subscribe C Institute And Will Not Done During Every Work Will Decide K Subscribe Like This Cheating All The Banana Swift Lump System So This is Gold Time Portal City Wants Slowly and Slowly Coins in the Morning to Find the Minimum Valley of Truth Dad Can Feel His All the Bananas from All the 550 Ward Switch to Front Minimum Balance How to Solve This Placement Let's understand in this for example so we need to find out the value of vikshad which is the meaning of value one of the solution what we can do will start from chronic and keep going and win for recording parts of values ​​in this amazon Amazon River Pure Co Play Valuation Atm At That Time Power Of Which Can Withdraw Kerala Loop From 125 Vid U Will Take Time To Buffer Like Share And Subscribe Like Subscribe Now To Do Subscribe To 123 Miles Pilot I-Next Minus One 123 Miles Pilot I-Next Minus One 123 Miles Pilot I-Next Minus One Divide Person Plus one sonth is chole nu service three nuvve to a plus vve subscribe to subscribe will take for subscribe and subscribe the Video then subscribe to subscribe Peeth fans can this all the banana in it thoda twitter ne suicide kar lungi three and started lifted from which was Very first time taken from subscribe and subscribe but think in the draft late evening Roman Reigns Wave Awesome's Scott Missal What is the meaning of what to expect 400 10th plus total time will give this time starting from one to two times in condition in it Share after but no time which includes subscribe channel subscribe like and subscribe to the work murder note noise what is the reason already crossed the interior or diet on Thursday noida will not do any thing for competition subscribe to reserve for your friend Nota Ballet Dancer Saunf Adding Duminy To Convert Back To Read Jab Nishphal Hi Start With A Slight C Yes These Deals And Is After Not Great That Aapke Some Incidents Like A Good Time Cross Ho Android And Condition Like Share Is Our Ifin Cry Is Stronger Subscribe Main Soya Nuggets What Like It Is Pair Crossing All Odds And There Is No Need For Debate Show This Is Not One Of The Extras Continue To Edit Festival Timed As Being Aware Of How To Optimize For Me To Find The Value Of Which Is The Rain From It will start from power will find a which is made for 10 minutes to check weather it is the time will be that time taken by using in the country instead of acid can avoid taking to cash withdrawal from 100 to 100 that difficult to give a speed subscribe 2nd ID Plus One Side's To-Do List Start Writing for the Phone 's Music Device Alerts for Boys 's Music Device Alerts for Boys 's Music Device Alerts for Boys Define BLOS 101 and Allied Stay in Power Notes of Life and You Find No When Used Oil Lakshmi Take This Code Number to Now Isko Dinner Some Basic Elements of Bald Acid Possible Solar System Is Possible That And Her Will Keep It Up Your Self And Value Of Eyes And Person Wear Thinking Current K Swarnim That Case Will Find The Total Time See Benefit Everything Is Point Effective And Insisted Of A Given Point And its dry is award given in this point will not mean that you are from it's possible to you will find first make as that low plus is high - people this is for basic taken is high - people this is for basic taken is high - people this is for basic taken world in danger overflow nonveg sacrifice possible wife watching this pile apnd Mez Tak Possible And Updated On This Is Backed Duration Current Made It's Not Possible Dandruff Data 102 Slow Plus One And You Will Dance Remedy Absolute Compiling All Details You Can See What Is The Time Say This Is The Capital D Its Do Take Off But For Every During the year subscribe The Channel and subscribe the Channel Please subscribe and subscribe amazon shift solution edelweiss boys subscribe my channel radhe-radhe mode my channel radhe-radhe mode my channel radhe-radhe mode problems which they can write the name of the first comment thank you
Koko Eating Bananas
longest-mountain-in-array
Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours. Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k` bananas, she eats all of them instead and will not eat any more bananas during this hour. Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. Return _the minimum integer_ `k` _such that she can eat all the bananas within_ `h` _hours_. **Example 1:** **Input:** piles = \[3,6,7,11\], h = 8 **Output:** 4 **Example 2:** **Input:** piles = \[30,11,23,4,20\], h = 5 **Output:** 30 **Example 3:** **Input:** piles = \[30,11,23,4,20\], h = 6 **Output:** 23 **Constraints:** * `1 <= piles.length <= 104` * `piles.length <= h <= 109` * `1 <= piles[i] <= 109`
null
Array,Two Pointers,Dynamic Programming,Enumeration
Medium
1766,2205
1,575
hello everybody in today's video we are going to be looking at lead code problem number one five seven five count all possible routes so the problem description says you are given an array of distinct positive integers where the locations at each index represent the position of a city at that index we're also given three integers start finish and fuel representing the starting city the ending city and the initial amount of fuel we have so at each step we can pick any city that is not the current city we're at and then we can go there when we go to that city we reduce the amount of fuel we have by the absolute value of those respective cities and then they want us to know that the fuel cannot become negative at any point in time and we are allowed to visit each city more than once if we want and then finally what the problem is really asking is to return the number of possible routes from start to finish and the answer might be large so we want to return it mod 10 to the ninth plus seven let's take a look at how this problem works so in this first example i've drawn it out for you i'd like to just go over how we can read this problem so we're given an array and i it's called cities here in this first example it's 2 3 6 8 4. and i've drawn in yellow the indices that represent these and then our start is index 1 our end is index 3 and we have five units of fuel to start out with so what we're really interested in is starting at this index one right here and ending at index three so we want to go from this three to eight this gap right here but we have five units of fuel to do it we wanna know how many ways can we do that and the answer ends up being four why well i'll just show you the possible ways we can do it we could go from one to three directly that ends up using five units of fuel see one to three it uses five units of fuel because the absolute difference the absolute value between three and eight is five we could also go from one to two to three so if we went from one to two that's going from three to six that uses three units of fuel and then from two to three that uses two units of fuel the difference between six and eight is two another way we can do this is from going from one to four to three going from one to four uses one unit of fuel because the difference between three and four is one and going from four to three this is remember index four to three uses four units of fuel so we've used five now total and then the last way to do this is going from one to four to two to three we already saw going from one to four uses one unit of fuel going from four to two uses two units of fuel and going from two to three also uses two units of fuel so you might notice here that the starting number in these chains here is always one and the ending is always three and that should be the case because we have to start at one and we wanna end at three the question it was asking us how many ways can we get from one to three without going under on our fuel and the answer was four here are all four ways let's look at another example now so in this next example the cities are two one and five and i've again written the index below each city our starting and ending point are both index zero and we have three units of fuel so what are the possible ways we can do it here so i'll write down the path and how much fuel it uses to do that path so one way to do this is just to do zero if i start and end at zero well i got to where i wanted to go and i got there starting where i need to start from and i've used zero gas zero fuel to do that another way i can do this is going from zero to one to zero and how much fuel does that use well going from zero to one uses one unit of fuel and going from one to zero uses another unit of fuel for two units of fuel notice how i didn't use all my fuel i still have one left over and that's okay because i was able to get from where i had to start from where i needed to go use using less than the amount of fuel i needed to and that's okay i don't need to use all my fuel i just can't use more than i'm given so let's look at the algorithm a little more closely now how this works in a more general case if my cities are some c1 to cn and my indices are from zero to n minus one i have a start point of a and end point of b and i have f units of fuel well what i want to do is i want to choose a city so i'll choose a city and i don't really have much of an option for the first one and then i'll go there when i go there i have to update my fuel so there's two cases case one i'm out of fuel if i'm out of fuel that means there's no solution that would mean i tried traveling from say zero to one and in the process my fuel became negative if that happens i can't go there that's not a legal path another thing that could happen case two is i could be at my ending city i could have a riot i could arrive where i want to be if that's the case then i have one more solution and if i'm in case two as long as i'm not in case one then i want to continue going even if i've arrived at my destination i want to keep going because i still might have more fuel so i wanna from here now with my updated fuel is travel to every remaining city except myself i don't want to go back to myself let's look at this algorithm in action now so in this example here my start is zero my end is three and i have ten units of fuel i don't really have any choices for where i can start so i have to start at zero when i do that i have three choices from where to go i can go to one two or three and at each of these states i'm actually i'm gonna write zero comma ten so i'm at city zero with ten units of fuel when i go to city one how many units of fuel do i have well i would have nine because going from zero to one burns one unit of fuel going from zero to two i also have nine units of fuel and going from zero to three i would have two units of fuel left now from here each of these problems can be broken up into its own problem so for example what if i said the start was 1 the end was still 3. and the fuel was nine well that's the problem i'm solving when i go to city one first so let's look at that if i go if i'm at city one i can go to city zero and then i would have eight units of fuel i can go to city number two if i burn two units of fuel so i'd have seven after that going from one to three i would have that would be nine that would burn nine units of fuel so i would be at three with zero left and then likewise each of these problems can be broken down just for an example i'll look at this last one three zero this is saying starting at city three i have to get to city three using zero fuel so i'll just write that start it's three end is three and fuel is zero this is a pretty easy problem i'm i need to start at some city but i need to end at that same city and i can't use fuel so obviously there's only one way i can do that so when i'm at the 3-0 state i would so when i'm at the 3-0 state i would so when i'm at the 3-0 state i would return one back to whoever asked me for that answer does this tree can end up having repeated sub problems in it and because of that it's a popular technique what we can do is we can memoize the answers so every time i compute an answer after i've done this 1 9 tree traversal i'll just store the answer will be maybe something like we'll just call it x and then i know if any of these other subproblems ever gives me a one nine state i can just return the x let's take a look at how this might look in code the first thing i'm going to do when i code this is write my own dfs algorithm i need to know the locations my current location my goal location and how much fuel i have the first case we talked about was if our fuel ever drops below zero if that's the case i'll just return zero because there's no solution and i'll make a result variable to hold on to the answer if the current city i'm at is equal to where i need to go then i have one more solution and then finally i need to visit every other city so i will do for and i equals zero to the length of the array if the city i'm planning to visit is the current one i'm in i'm just going to skip that and move on to the next city but i'm going to calculate the cost of how much it costs to go to that city and i can do that with the absolute value of this locations at my current location and then take the difference between that and the location i want to go to and then i'm actually going to go there i'll call this next trip and i'm just going to call the algorithm again but instead of being at the current city i'm going to start from city i my goal city is going to stay the same and my fuel is going to go down by the cost that i just calculated that's going to give me some answer so i'll add it to my result and then i can at the end return that result but i missed something and that was the mod so i'm going to create a mod variable up here because the answers can be large i have to remember to mod out by this it was 10 to the ninth plus seven as my mod so every time i add to my result i'll also mod by the appropriate value so then all i need to do is just call my algorithm and let it do the work locations from the start to the finish using that much fuel so if we run this we should get the right answer for the test case yep but the problem is if i were to submit it wouldn't be fast enough so i'm going to create a caching variable a two-dimensional a caching variable a two-dimensional a caching variable a two-dimensional array and inside of the constructor i'll instantiate it to a new integer array but what are the sizes of these well i have n location so locations.length that sounds about right locations.length that sounds about right locations.length that sounds about right to me that i can go to and how much fuel can i have fuel is going to be some positive number let's say it's six i would want to have six plus one i want to have seven possible states for fuel to be in because i can have zero as a possible state so however much fuel i have plus one and the plus one is because i have the zero state as well and what i'm going to quickly do here is instantiate everything to negative one i can do that using this method called arrays.fill i can pass arrays.fill i can pass arrays.fill i can pass it an array and a value and it sets every value in that array to whatever i want so now when i'm in my depth first search algorithm after i've checked if it's a bad state if i have a legitimate amount of fuel i can check to see if i've computed this before so if the current city i'm in and the fuel with the amount of fuel i'm in is not negative 1 that means i've calculated this answer before and i can just return it if not i need to actually do the computation and but then i want to remember the answer so i will say at that current city with this amount of fuel i will be that result and let's just double check that this algorithm still works like i spelled locations incorrectly let's try this again yeah that looked to work okay i'll try submitting it and see if we get the right answer yep we end up getting a successful run by cashing these answers we're able to save a lot on the computation time and the reason we are doing the locations and the fuel is because those are the only two variables changing the city i'm in the current city and the amount of fuel are the two variables that change and it's locations.length because i if and it's locations.length because i if and it's locations.length because i if locations.length say is 10 then i if locations.length say is 10 then i if locations.length say is 10 then i have 10 possible cities to go in to and then it fuel plus 1 because i have however much fuel they give me but i also have the zero state so i add one to include that zero state let's talk about the time complexity real quick so for time and let's do the space first i actually think i want to do the space first how much extra space am i using well i'm creating a new int array and it's n for the number of locations times the number of fuel so it would be o of n times f but how long does this algorithm take now what's the time complexity and i know that inside of this depth for search algorithm i have this two dimensional ray array of size n by f so i can expect depth first search to be called n times f times and within each depth for search call i have an n for loop i have a for loop going from 0 to n so it's o of n times f for the number of depth first search calls i make times an extra n because each call has an iterative for loop which is really just o of n squared times f thank you for watching this video if you have any questions please comment and i'll be happy to help or if you have any video suggestions also please let me know
Count All Possible Routes
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
You are given an array of **distinct** positive integers locations where `locations[i]` represents the position of city `i`. You are also given integers `start`, `finish` and `fuel` representing the starting city, ending city, and the initial amount of fuel you have, respectively. At each step, if you are at city `i`, you can pick any city `j` such that `j != i` and `0 <= j < locations.length` and move to city `j`. Moving from city `i` to city `j` reduces the amount of fuel you have by `|locations[i] - locations[j]|`. Please notice that `|x|` denotes the absolute value of `x`. Notice that `fuel` **cannot** become negative at any point in time, and that you are **allowed** to visit any city more than once (including `start` and `finish`). Return _the count of all possible routes from_ `start` _to_ `finish`. Since the answer may be too large, return it modulo `109 + 7`. **Example 1:** **Input:** locations = \[2,3,6,8,4\], start = 1, finish = 3, fuel = 5 **Output:** 4 **Explanation:** The following are all possible routes, each uses 5 units of fuel: 1 -> 3 1 -> 2 -> 3 1 -> 4 -> 3 1 -> 4 -> 2 -> 3 **Example 2:** **Input:** locations = \[4,3,1\], start = 1, finish = 0, fuel = 6 **Output:** 5 **Explanation:** The following are all possible routes: 1 -> 0, used fuel = 1 1 -> 2 -> 0, used fuel = 5 1 -> 2 -> 1 -> 0, used fuel = 5 1 -> 0 -> 1 -> 0, used fuel = 3 1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5 **Example 3:** **Input:** locations = \[5,2,1\], start = 0, finish = 2, fuel = 3 **Output:** 0 **Explanation:** It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel. **Constraints:** * `2 <= locations.length <= 100` * `1 <= locations[i] <= 109` * All integers in `locations` are **distinct**. * `0 <= start, finish < locations.length` * `1 <= fuel <= 200`
Sort the arrays, then compute the maximum difference between two consecutive elements for horizontal cuts and vertical cuts. The answer is the product of these maximum values in horizontal cuts and vertical cuts.
Array,Greedy,Sorting
Medium
null
115
hello everybody Isabelle and today I'm gonna teach you how to solve the summer left Leafs problem find the sum of all left leaves in a given binary tree as an example they give you this binary tree so the output is 24 because there are two left leaves so because there are two you add them up so 9 plus 15 equals 24 how can we solve this problem well the essence of this problem is tree traversal we want to traverse the binary tree and find the left leaves and then add the values so we can do this using recursion or we can do it using iteration in this video I'll teach you how to do it recursively in the next video I'll teach you how to do it iteratively so without further ado I'm gonna show you how to write the code first I have the base case if the tree is empty if root equals no return zero because there are no nodes so the sum equals zero now if I'm here I can examine if there's a left node so I can say if root that left is not equal to no that means that from here for example I can check there's a left node if it is not equal to no that means that there's a left no here and root that left equals no so it has no left child and root that left the right equals no and this left no has no right child that means that this is a left leaf so what I can do is return the value return fruit that left that value return the value of this left leaf and then after that I add what I get from the right recursion to the right plus sum of left Leafs roots that right so as you can see first I check that I have a left leaf from above and if I have one then I check that the left child is not there and the right child is not there so that's a leaf and then I just return the value in this case nine plus what I get after recursing from the right I mean recursion to the right so this value and then i recurse to the right that means that I have to continue traversing the tree to the right because I found a left leaf it has no children so I just recurs to the right to continue the traversal if this condition is not true if these conditions are not true they would have to do is just recurs to the left and recurse the right for the traversal of the tree because I haven't found a left leaf so worse I will say return sum of left Leafs root that left plus sum of left Leafs fruit that right I'm around the curve okay I'm gonna submit my solution this is working perfectly so the time complexity of this solution is Big O of n where n is the number of nodes in the tree the space complexity is Big O of H where H is the height of the tree because that's the maximum depth of the function call stack if you liked this video please press the like button in the next video I'll teach you how to solve it iteratively please don't forget to subscribe and see you next time
Distinct Subsequences
distinct-subsequences
Given two strings `s` and `t`, return _the number of distinct_ **_subsequences_** _of_ `s` _which equals_ `t`. The test cases are generated so that the answer fits on a 32-bit signed integer. **Example 1:** **Input:** s = "rabbbit ", t = "rabbit " **Output:** 3 **Explanation:** As shown below, there are 3 ways you can generate "rabbit " from s. `**rabb**b**it**` `**ra**b**bbit**` `**rab**b**bit**` **Example 2:** **Input:** s = "babgbag ", t = "bag " **Output:** 5 **Explanation:** As shown below, there are 5 ways you can generate "bag " from s. `**ba**b**g**bag` `**ba**bgba**g**` `**b**abgb**ag**` `ba**b**gb**ag**` `babg**bag**` **Constraints:** * `1 <= s.length, t.length <= 1000` * `s` and `t` consist of English letters.
null
String,Dynamic Programming
Hard
2115
451
hey everyone today we'll be solving lead problem number 451 sort characters by frequency in this problem we will be given a string s and we have to sort in the decreasing order based on the frequency of each character and the frequency of character is the number of times it is appearing the string and we have to return the sorted string okay let's have a look on this example uh here the string is given to us is tree and what we have to return is we have to sort all of the characters based on the frequency so here first of all let's capture the frequency T is coming one time R is coming one time e is coming two time now what we have to do is we have to sort this character based on the frequency if we sort it based on the frequency it will become e t r e is coming two times both are coming one times and now if I try to form a string over it will be e t or RT whatever you one to form so this we have to return and this will be my answer and returning it in the sync form okay I hope the prr statement is clear to you and this question has been asked in Facebook Adobe Apple Microsoft Amazon and here we'll be using a technique hash table let's try over another example let's say we have this as a string our s and we have to form a result of this that we have to return so what we are going to do is we will be going as per the problem statement that we have to sort it out based on the frequency of each character so first of all we have to know the frequency of each character after that what we have to do is now we have the frequency of each character and now we will be sorting those character based on the frequencies and once we have sorted characters based on the frequency we can direct ly return result by appending those character in the same order so let's have a dry run on this example here first of all we have to get the frequency of each character so here in my map I will be having c three times and a is also three times let's say we have a b as well in the end and we'll be having B one time as we have captured the frequency what we are going to do is we will be sorting what values sorting these character based on the frequency so for that what we can do is to store uh these values what I can have is I can take a map of character int character is my specific character from the string and int is the frequency of that character and now we have to sort these character only so first of all what we can do is we can get a key set out of this map and then sort the key set based on the values sorting based on the value if I sort it based on the value it will be the same order because we have 33 3 when the same order so it will be c a b okay now what we have to do is now we have the keys in the sorted form and we have to form the result out of these keys so let's say uh I have taken a let's say resultant string in the resultant string firstly I have to append C how many times the same number of times it is appearing in the source string and C has the maximum frequency so c will be appended three times c and then I have to append a A's frequency is three so a will be appended three times and we have to append B one time so this is going to be my resultant string okay I hope you understood the approach capturing the frequency sorting the character based on the frequency and then appending it to the resultant string so what is the time complexity here first of all we iterated over this string in the order of end time and then we stored it in the map and then sorted it out let's say we have K unique characters so K entries will be in there in the map and we are sorting those ke characters let's say in the worst case it is order of n so it will be n for uh getting it done getting the iteration and get storing in the map plus and Logan because we are doing the Sorting here sorting over the keys so in general it will be order of n log n so this is the time complexity for our approach and what is the space complexity here space complexity will go in the order of n because we are storing the elements in the m in a map and in the worst case let's say we have a string like a b c d e we have a end L string and the N elements will be added to the map so this is the time and space complexity for our approach let's scode this out here first of all we have to take a map where I will be storing frequency of each character so map should be of character and integer let's say I call it counts it is equal to new hash map now we have to store the frequency of each character CH s do2 character array counts do putut against CH here first of all I need to see whether I'm doing the first entry so counts. get or default CH otherwise zero + 1 as we have default CH otherwise zero + 1 as we have default CH otherwise zero + 1 as we have captured the frequency now this map is having key set as the character from my string and values as the frequency so I only need to sort the characters so I will get the key set so list of character or you can say car is equal to new array list not the map counts do key set now I have got the key now I will sort it in the decreasing order collection collections do sort what we have to sort G I have to sort it in the decreasing order so I will be using a Lambda for that a comma B we have two values if B is greater than a it means we have to do the swapping so counts dot get B minus counts Dot get a okay so let's say uh in my term I'm getting 4 5 6 let's say we have to compare these five and six the value of six is greater than five it means so count of count get B minus counts get B will be a positive number if it is a positive number it means that we have to do the swap it means in the resulted saying six should come before five so in this way this uh sorting function works okay now it will sort the key set in the decreasing order now we have the characters in which in the order I going to add in the resultant string let's form a resultant string Builders SP is equal to new string Builder okay let's use four character C in the Char CS let's capture the frequency C frequency of each character counts do get C now this frequen this number of time I have to add this character in The resultant string while n minus- greater than string while n minus- greater than string while n minus- greater than 0 okay uh as uh these characters are already in the sorted form let's say as per tree example e is coming one in the first then T then R so e is the first character and the cap frequency I'm going to get from the map so the frequency number of times I'm going to add it in the resultant string Builder do append C and in the end string builder. two string Let's test over sample test cases on the sample test Cas it is working fine submitting the problem got submitted successfully hope you understood the problem thank you guys
Sort Characters By Frequency
sort-characters-by-frequency
Given a string `s`, sort it in **decreasing order** based on the **frequency** of the characters. The **frequency** of a character is the number of times it appears in the string. Return _the sorted string_. If there are multiple answers, return _any of them_. **Example 1:** **Input:** s = "tree " **Output:** "eert " **Explanation:** 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr " is also a valid answer. **Example 2:** **Input:** s = "cccaaa " **Output:** "aaaccc " **Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa " and "aaaccc " are valid answers. Note that "cacaca " is incorrect, as the same characters must be together. **Example 3:** **Input:** s = "Aabb " **Output:** "bbAa " **Explanation:** "bbaA " is also a valid answer, but "Aabb " is incorrect. Note that 'A' and 'a' are treated as two different characters. **Constraints:** * `1 <= s.length <= 5 * 105` * `s` consists of uppercase and lowercase English letters and digits.
null
Hash Table,String,Sorting,Heap (Priority Queue),Bucket Sort,Counting
Medium
347,387,1741
62
so hello everyone i am straight i am a software development engineer so we are starting with this lead code premium top interview problem series we will be discussing each and every problem which are mentioned on the lead code top interviews and also this will help you to crack your next coding interview in the top notch product based company so let's start with the problem we'll look at this problem from lead code top interview questions that is unique path so it is basically a dp problem but it can also be solved using maths so today we look at the recursion and how we can optimize the recursion be using memoization so let's look at the problem statement so it says that there is a robot on a matrix the it is initially on the top left corner on the zero comma zero index and it tries to move in the bottom right manner he can only move either down or right at any point of time so we have been given these two integers and we need to find the possible unique paths and the test case generated says it is uh 20 to 10 to the power 9 so it is mentioned that we cannot use recursion directly so it will give us a tle kind of thing okay so let's try to visualize this problem what it says so basically we have been given this sort of grid and there is a source there is a destination and we need to reach this place and we have only these two moves we can either move in this direction or in this direction so what are the total number of ways total unique paths so let's try to visualize it for a smaller problem so we have our robot is present there and he wants to reach this b position so let's say in moving the total number of ways it by via this path is a and this path is b so what will be the total number of ways so the total number of phase will be a plus b okay this is true so what if this function give us the answer so we can just pass solve 0 comma 1 as this is 0 1 okay and this will be 1 0 so this expression will give us the answer for this problem so let's draw the recursive tree for that how the things will take place so initially we are at zero comma zero so from zero comma zero we can either move to zero comma one or one comma zero okay from zero comma one we can either move to zero comma two or one comma one from one comma zero we can either move to uh one comma two or one comma one so likewise the recursive tree will go so what we'll do we'll just add the answer that will be given to us by these two recursion branches okay so let's try to code this once and uh we'll try to get what uh how actually the problem flow will go so um we'll have a obviously before using memoization we'll have a dp array okay so this dp array will be made as per our constraints so it is mentioned that it is 100 so we can use 101 okay so now we'll also define two variables i and j is equal to 0 and let's say now we'll first write the boundary cases so what will happen if i is greater than equal to m or j is greater than equal to n so we'll just return zero okay the second case is if i is equal to i m minus 1 or j and this will be and so we have reached that goal so we will just return our answer we'll just return one uh and if uh bp of i and j exist in which we are storing all our answers then we'll just return this okay else what we'll do we'll just return dp i j is equal to okay you need paths oh you need parts uh what we'll do we'll first look for the we have two options either down or right side okay so here it will be i and j plus 1 so this will be our final result so we just took care of the boundary cases and uh this case will be because we are already so getting to that position will return one only and if we already have a path we have stored it the path value and also if it's not the case we have traverse the both the sides so let's try to run this one okay just a spacing issue so it got accepted and the overall time complexity will be a big o of m into n that is n squared kind of time complexity and the space complexity will be same because we have initialized this dpi okay so i hope you guys have understood this one try to submit this and we'll meet you in the next session you
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,094
I always Calvin here so today we will discuss about a problem called carpooling from weekly contents 142 so let's start so this problem we are given an array so this array is a number of passenger that the first thing that is the number of passenger that take a ride on our car and start position and punch it and position like when the passengers start to write our car get off from our car actually have a capacity so we can only pickups that many passenger and the question is asking us like are we able to finish the all the trips or not return a true and false in such case so yeah this is basically a very normal 3d type of problem so we just need to sort our trip to start from the step we start we sorted based on the stud location and then when we made any location we decrease the such number of people from our car we just make sure it's lower than capacity for until the end of all three and basically we can finish this question already so let's directly jump to the code here you see that I have at run the transport lock so I have two times the actual trip size this is to make like B so when the user enter this is the number of passenger goes in as a positive number and the start time and when the passenger got off I will still use the trans the transport lock as a negative number of passenger so we can decrease our passenger at that time this is the time of the passenger get off so you see here I try to sort the array and based on the time so we're soft at time that's admit so this is the time of getting in and this is the time of getting off we try this at the same time so we sorted from the smallest one until the biggest one right and if it has the same time then we need to sort based on the passenger through so if we met at the same time we will put off our existing passenger before we get the new one in so in that way we make sure that our capacity didn't exceed the same time so here after we started then basically we looked through all of it and if the current capacity plus our current transaction passenger capacity is still smaller than capacity it means we add up the current capacity with that many passenger and this value have a negative also when the passenger get off so this also has to decrease the current capacity if the condition here doesn't being fulfilled it means more percent I want to get in but the capacity is already fooled and we immediately return a false otherwise we just return true at the end yeah that's it for the carpooling problem from the we click on test one hundred and forty two and see you on the next we click on tests
Car Pooling
matrix-cells-in-distance-order
There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them up and drop them off are `fromi` and `toi` respectively. The locations are given as the number of kilometers due east from the car's initial location. Return `true` _if it is possible to pick up and drop off all passengers for all the given trips, or_ `false` _otherwise_. **Example 1:** **Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 4 **Output:** false **Example 2:** **Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 5 **Output:** true **Constraints:** * `1 <= trips.length <= 1000` * `trips[i].length == 3` * `1 <= numPassengersi <= 100` * `0 <= fromi < toi <= 1000` * `1 <= capacity <= 105`
null
Array,Math,Geometry,Sorting,Matrix
Easy
2304
1,751
Hello everyone, welcome to me, we are going to channel 44 and you must know that I also have a separate playlist of DP concession questions, you can read it. To understand DP from scratch, just like, we had once made a playlist of questions on graphs and concepts. Okay. And our page is available separately on Facebook, Instagram and Twitter with this name. On leading on Facebook and Instagram with this name on Twitter, it is 1751. But when I will solve it, you will find this question very easy because it is very simple. Rickson 's question is very simple, okay, the 's question is very simple, okay, the 's question is very simple, okay, the name of the question is Maximum Number of Events Dates Can Be Attended Part 2 Okay and there is a very similar question, to a great extent, the question is Liquid Number One, Three Five, so after making this, you can make that also. Yes, it is a very simple question that you have given a field named Events, there will be three things in it, start giving India, till now clear present D maximum, okay and now if you are doing events, then you will have to complete it completely, okay and Tell me one very important thing that these give it inclusive, what does it mean, do you know what happened like mother takes an event starts at 1:00 o'clock happened like mother takes an event starts at 1:00 o'clock happened like mother takes an event starts at 1:00 o'clock or a sorry starts on one date and ends on the second 3rd, then you go on 3rd. Ca n't start any other event, you have to start like this on date or fifth day is Monday. Next and ok this is what it is saying note date D Indian you events where one of them starters and D other and D se give ok maximum You can do 100 events but the value you will get is the maximum. Let us understand from the example. I have taken the example as very simple. The first example of Let Ku is the point. The second event is the third event. It is not sorted in any order. It starts on a date. It happens that it ends on the 2nd and you get tax rupees. Start on the 3rd and end on the 3rd. You get three rupees. Start on the 2nd and end on the 3rd. You get one rupee. Now the maximum is only two and if you can, then take Maa. If you did event one, it started on the 1st and ended on the 2nd. Now the event comes to you. Now you can do the event. Can you do it? Yes, you can turn off the event. Why, because you did the event, because look, whatever your event is, it is two. It will end on the third day and you started on the third day, so now look after this there is no intersection there is three more and now we are talking about the event three. Look, it started on the second day only, this is a matter of paste, this is this. So it started on 2nd date, so why don't we sort it by the starting time so that there is no problem in processing, I am saying that if you sort the dog on the basis of the start time, then there will be no problem, given a general interview. Isn't it, I have a separate repo on 1 to 2 3 4 interval base question, you will go to me and it is inside this, generally we have to do sorting in it is okay to do the asana according to your starting point. What will happen, I am shorting it now, okay, if I short it, then first of all, what will go, this will go to A, 124, okay, after that, this will go to A, its starting point is you, right? 2 3 1 3 4 3 Okay, what is the benefit of sorting? This event is one, this event was three, remember which event is 2, what is the number, it does not matter, you can only do maximum two more, okay now mother, if you have taken this event, then start on one date. It happened and ended on the 2nd, after that pay attention that this is an event which is starting on the 2nd, so you cannot take it. It is said in the question that the event happens on the 2nd and there is no one on the 2nd. When the second event starts, you ca n't do that either, so you won't be able to take it right because we had taken it, okay if you don't take it then we could have taken it, right, so you must be getting a little hint here and there. Took once and skipped once. If I took it then you will start it on the 1st day, how many rupees will you get on the 2nd day, you got ₹4, you will ₹4, you will ₹4, you will not be able to take it is starting on the 2nd only, it is ok, so you can't take it, now you can take it, see my It is out of the index of the first event, it has started, so here three, from here, I got three rupees in this, total how many rupees I got, 3 + 7, I got it, total how many rupees I got, 3 + 7, I got it, total how many rupees I got, 3 + 7, I got it, okay now mother, if you had not taken this, if you had taken this, then when would it start? What is happening is, let's see, it is starting on the 2nd and ending on the 3rd, so I get only ₹ 1 and ending on the 3rd, so I get only ₹ 1 and ending on the 3rd, so I get only ₹ 1 and look at this, it is starting on the 3rd, okay and it was ending on the 3rd. First event, now if you are not able to take it then you will get only ₹ 1, it is get only ₹ 1, it is get only ₹ 1, it is not a good option, I have chosen maximum, so how much was the maximum value, 7 is my answer, its answer is 7, ok, many things have become clear from the example and You should understand this completely, forget everything, write the code from the diagram made, if we start with three diagrams, then we will come to the tree diagram, but before that, some things which we have come to know till now, first of all we should do sorting based on The start time is fine, sorting is done, after that one thing is very important that here I can see a clear cut that we will reduce the take and skip ones, I follow and one more thing which is very important if you take someone, mother. Let's take this, okay, so see when its in date is, if it is two, then you know what it means, which is the next event you can take the next event which comes after this in date i.e. two. What comes after ' i.e. two. What comes after ' i.e. two. What comes after ' three' or 'kar' means the people attending the event whose three' or 'kar' means the people attending the event whose three' or 'kar' means the people attending the event whose starting time is equal to this India time. This is quite a logical thing. Okay, so we will take care of that thing. Okay, first of all, if you don't want to do sorting, then do sorting. Giving 1 2 4 2 3 1 3 4 3 12 31 343 You must have created the question by now by pausing your video because the only thing we had to crack was to make it from tray diagram but one important thing, now we will understand, look carefully let's take the mother Right now I am here, I am on index number I. Okay, so I have two options, I will take it or not. If I am late, I took it. If I am not late, I skipped it. If I take it is okay. If I take it, how many rupees will I get? You will get rupees after tax, this is its value but now which next event will I be able to take, the starting time of which is the ending time of my current one which I have taken, it is ok now see, what is the ending time of the 81 I have taken. If you give the ending, then now I will take the next event whose starting is given. It has come after my current ending, so what is more than two? If it is three, then look at its starting date. If it is two, then we cannot take it. If its starting is three, then You will have to find this here and there you can apply liner search to find it, I have found that we can take this next, then my next time will go there i.e. it was 124, you were three one and It i.e. it was 124, you were three one and It i.e. it was 124, you were three one and It was 343, so no, this time I came here because I can't take it, so it's okay and I had taken it last time, so after valuing it in rupees, I took it here, okay, now here also I have two options. Whether I should take it or not, if I am late in taking it, I will get ₹ 3, late in taking it, I will get ₹ 3, late in taking it, I will get ₹ 3, this is its value, it is ok and if I don't take it, I will skip it, okay, if I take it, then which event will I be able to take in the next event? Give starting then give ending and then start like this and when is it happening, I can take it from 5th onwards. Okay, whatever date comes after the tax date, if there is any start, I can take it. After this, if I want to move ahead in I then further out of is closed then there is no benefit in further life, okay, here my I will be auto bound, so I got ₹ 3 from here, so I got ₹ 3 from here, so I got ₹ 3 from here, okay and here if I just skip. If I do, then okay, what will happen? Anyway, I was not out of it, I was just pointing it out, so how many zeros will I get from here, okay, so the maximum that I will get out of the two is three and what is the maximum among zeros is three, so now If you return three here then do plus three that is how much I got from this thing 7 If I had taken the first one, if I had skipped the first one then see what happens if you skip then there is no problem 1243 What is the meaning of doing this? You did not take it. Meaning, which next event would you like to take? You have two options on this too. Took this one, Skip this one, If you take this one, what will you get? If you get ₹ 1, this one, what will you get? If you get ₹ 1, this one, what will you get? If you get ₹ 1, then here. I write ₹ 1, then here. I write ₹ 1, then here. I write ₹ 1, ok, but which event will you be able to take next? When it gives my current, which one I have taken, current event, give its ending, is it three, then I will take the event which starts after three, then these are three. It's just starting, it's just three or two starts, if you can't take it then it has n't even come forward and something, it will be auto bound, it came here and my answer will become zero from here, one plus zero, one came from here, if you take it. Okay and if you skip this, then from now onwards I will go here 343 Okay, you will go ahead, scan this trick will give you the answer. Okay, so now look, it is the same thing from here, the answer will come from the right and from the left. The answer that will come from Take and Skip will be maximum, you will choose this one. Okay, we had to pay attention to Taken Skip, but one thing that had to be kept in mind is that whenever you tag any event, you will not take any event. If you take an eye then it has a start and an egg and its value is If you get it right then the next event will be which one of you guys will be the next eye whose start is more than this end so that This should not happen or overlap, it starts on two dates and ends on the tax date, then it is an obvious thing that you do not organize any such event which starts on the tax day or starts any time before the tax, okay now the matter. I have come here, let's take mother and by the way, I have sorted it according to the starting time, so if this is two, then the one after this will be more than two, it can be three, it can be two, it can be one or not. If there is only one, then it comes first here because what I have done is to sort it is okay to always sort it according to the starting time. There is also a question, okay, so this is a very simple question, which can be explained quickly by request. The story has actually been written using the tree diagram itself. The story has to be written quickly. You have to quickly convert it into code and write it. But pay attention. There is a liner search here, so you can clearly see that you have two options near each index. Liner. You are searching just how, in which off and n will be used, then it is known that actually this is a very slow approach of yours, if you even memorize it then you take it as a dog mother, you have memorized it, okay then look, I am going to fascinate you. What will you do? Two things are going to change as soon as the cake ends because you have to pay attention to that thing that you can only take a maximum of two events and if it becomes zero then it means you cannot take any more events. The return has to be done, it is okay, we will keep decreasing, we have mixed the cake also, keep decreasing, if we write the code, it will be cleared very well, okay, so two things will be changing, if you see the story here, I am in the story here. But let me tell you that as soon as I write the solve, I will start the index number from zero. Okay, and in the beginning, I have not taken even one event. In my beginning, look at its function, how will I write, it is very simple, the index has come. And I am sending if I give greater equal, you have become that I have skipped. If you want to skip then it is very simple, okay you just solve it and the cake will remain the same because you have taken the event and did not attend it, okay if you have If you tagged it then you will fix it, in the next I can take this one event and will send K minus one. Okay, here I hit liner search. Okay, so now you can also apply binary search in it because it is sorted on the basis of starting time, so we We will also do binary search on this but first let us solve it with linear search and check the memory by doing this because if we do this on memory then see two things are changing, one is the index is changing and one is becoming three, okay. So when we do memories, we will take them of two dimensions, okay, here N is of size, N + 1 and here K + 1, so N + 1 and here K + 1, so N + 1 and here K + 1, so how many maximum states will it have, or you can say this, you will visit each state once and If you are hitting linear search once in every state, then it will be N, the time complexity will be so big, you are fine, if you use binary search, then what will happen is N + 1 and if you are hitting binary search once in every state, then If the time taken by people will be complete then you must have understood the question has also become very simple, we will solve it quickly first in the liner section, after that we will see how to do binary search. Okay, so let's code it quickly and finish it. First of all, review. We will make it through memorization. Okay, first of all, what did I tell you that you have to do short, start of events and end of events, so what will it do by default, which is the first element, that is, the one that gives the start to every entry. It will sort in ascending order on the basis of that which is what I want, okay, we have done this shortening and I define outside this equal tu events dot size and N, okay and what I will do with simple is return solve. Will give Now I have the value of current means I can do in current okay and solve first of all what am I sending vector of events okay inter which am I in the index currently what is the current value if id axis give greater equal You have become N or K = 0. We will K = 0. We will K = 0. We will return zero because I cannot attend any more event. Okay, now the current event has started. Let's take out the index of the current event and also take out the value. Start this. End is done, what has happened to zero, this will become one, this will become you, isn't this done, the value is clear till now, it must be going very simple till here, now look, I had two options, one of them I will skip, if I skip If given, I will not get anything right, then I will go to Simply Events and I Plus One. If I find the skip, I am late for the next event. If I am late for the current event, then I will be late. Now I am handling the take. If I take the skip, then next and Which one will I be able to take? Starting date, if it is bigger than my current event, E is bigger, ending date means one is fine, that is, I can take this one in life, next time is fine, so I remove the solve events, which events can I take next? I will be able to take it and I will have to do mine one because I have taken it in this event, so I have got this much money. Okay, last memory turn is maximum of skip and take return. Okay, so it is very simple, the code is also very basic. This is the explanation, isn't it? People who have tried my other questions will understand how basic it is. There will be DS here, it was a normal skip question and nothing else and it will give time out because we have not memorized it here. Let's see, first an example, there is a different video, okay look, the time limit has been reduced to one seat, okay, I am late here, I have taken the name vector of T in which what will I do, I will do memories, okay, I will initialize it. First of all, I resize it, I have resized it and plus one vector of these, I have made it clear till now, before proceeding further, check that the value of current idea If it is not equal to one, then toffee ds is returned for comma. Okay, if it is not so, then for t of id I have done the liner search here. Okay, so look at the binary search that we have done. Let's find it through binary search. Let's just take it. Now my idea is here and I have taken it, so see, it is starting on the 3rd. This is mine starting on 3rd and ending on 6th, so now if you find an event which starts after 6th, whose start date is more than 6th then you hit the liner search, its start date is not more than 6th. Its start date is not more than six, its standard is more than six, so you would have chosen this, otherwise you have searched linearly, but now we know what we will do a normal binary search, we will do a normal search and we will see which such element is there. Whose starting time is greater than 6, if you hit binary search here, then you can write your own, which I always suggest, write your own binary search, but we can do it directly here, what does it give? We have to write upper bound like this. events.in events.in This is the whole of what I have about events, it has three elements in it, every element has three elements in every index, right but what do you want to extract, if you are saying starting on 6th April then you are saying giving starting. Yes, you are okay, then you will also have to give three elements, whatever it is, three elements are required in it, the second element is from you, if you do not care, then you give infinity, okay, then from infinity. Otherwise, both of these will not be considered. Okay, but what do I mean by this? By right 6 I mean I need 6 to 10 big elements. Okay, so you will write like this. Okay, when you did memories, you took N + 1. when you did memories, you took N + 1. when you did memories, you took N + 1. Well, the totals will be this much, so this is my improvement a little and this will also be accepted. In the next video, we will make it from the bottom up. Okay, this is only the top dr. We wrote the code through a one liner search and a binary search. So let's go. Quickly replace the liner search with upper bound and submit and finish the question. Last time we had to find the tech through liner search. Which element do we have to take next? What will we do this time? Binani search instead of liner search. Okay, so I will remove it. If we apply binary, then what did I tell you that we will find the index by applying binary search. Now the bound is fine. events.in events.in used to tell here that events.in used to tell here that events.in used to tell here that from which element you want just bigger bound. Science, which is our vector, is not an element here, we also have to tell it in the vector here, okay, then I will write the vector separately, vector of temp, okay, now look, you have to find such a person whose starting days is my current ending. If it is bigger than de then when is the ending of the current de and is neither then I will say just big starting from and should have been given ok and if you add internet to the rest then there are three elements in ours okay so the rest I have added internet and This input is given, find that band and bring it. Okay, so here I enter tempo and it returns. If I want the index, then there is no need to mine, I will find it from the subsequent elements, otherwise it will be plus ID of X + 1. In the latter, I have to plus ID of X + 1. In the latter, I have to plus ID of X + 1. In the latter, I have to search here, I will find it, I have tried running it, the example is ok, it is done here, now we submit it, which are the cases using binary search, think also, if there is any doubt, please read in comment area tree. Tu Help See You Gas Video Thank You
Maximum Number of Events That Can Be Attended II
slowest-key
You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the **entire** event. Note that the end day is **inclusive**: that is, you cannot attend two events where one of them starts and the other ends on the same day. Return _the **maximum sum** of values that you can receive by attending events._ **Example 1:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,1\]\], k = 2 **Output:** 7 **Explanation:** Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. **Example 2:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,10\]\], k = 2 **Output:** 10 **Explanation:** Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap, and that you do **not** have to attend k events. **Example 3:** **Input:** events = \[\[1,1,1\],\[2,2,2\],\[3,3,3\],\[4,4,4\]\], k = 3 **Output:** 9 **Explanation:** Although the events do not overlap, you can only attend 3 events. Pick the highest valued three. **Constraints:** * `1 <= k <= events.length` * `1 <= k * events.length <= 106` * `1 <= startDayi <= endDayi <= 109` * `1 <= valuei <= 106`
Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.
Array,String
Easy
null
778
hello everyone welcome to kodus camp we are at 20th day of june liquid challenge and the problem we are going to cover in this video is when in rising water so this is another interesting problem where the input given here is a two dimensional array grid and we have to return the amount of time we take to reach from the very first cell to the bottom right cell so here this numbers in grid array represent the elevation in the land and the problem statement says at time t the depth of the water everywhere is t and we can travel four directionally adjacent square if and only if the elevation of both squares individually or at most t so let's understand this problem with an example so here is our given first example in the problem statement consider these grid is a land and the values given are the elevations so at the first square there is no elevation and in the second square consider the land is elevated up to some to level two and in the grid two it is up to level one and in grid four up to level three so we are allowed to swim between the grid to grid and when we can swim only if the water level is above or equal to elevation that is if the level of elevation is 2 here then the water must be up to 2 or above 2 so that we can swim same way if the elevation here in the grid 1 comma 0 1 comma 1 is one here so the water must be at level one and or more than level one so that we can swim from zero comma zero to one comma one so at first we don't have water here they said it starts raining and for every t the water level will be t that is at zero time there will be zero water at all the grids at same way at time one consider this may be for one minute or one hour they did not mention the measurement of the time but one unit at one unit the level of water at all the goods will be one so consider the same example at time one you have water one at zero comma zero and water uh level one at one comma one so that you can swim from zero comma zero to one comma one as the elevation is covered by water but you cannot travel to the other two cells because the water level will be at one but the elevation is at two which means there is a land above water level so in that case you cannot swim you still have to wait till it reaches the level of land so that you can swim so yes understanding all this let's get into the solution part so now we are going to start from the cell 0 comma 0 at time 0 so now you have two options to travel that is from 0 comma 0 you can travel to 0 comma 1 or 1 comma 0 since you can travel only 4 directionally and this is the left most cell you have only two options left so out of this if you want to travel to zero comma one then you must wait for two seconds and if you want to travel to one comma zero you must wait for one time unit because at time one the level of water will be one so you can travel to this cell alone so consider at time one we are traveling to this cell so now right now we travel from zero comma zero to one comma zero where the level of water is one so you have to reach one comma one where the level of water is three so at time two all the grits will be having the water level to two so in that case from one comma zero you have only one option left to travel that is one comma one because you cannot visit to the cell again that is go back to zero comma zero so but you cannot travel to one comma one as well because the water level is at two at time two you still have to wait one more second to reach your three comma three so we are waiting for one more second and the time is three so at time three the water level will come to three so you can now swim from one comma zero to one come out so the maximum time it took for us to travel from zero comma zero to one comma one is three so that is what is our output so to understand this problem better we are going to see one more example so this is the second example given the problem statement as usual we are going to start from the cell zero comma zero so you have options to travel to either this cell with water level one or this cell with elevation twenty four at time 0 you cannot swim to any other cell at time 1 you can swim to the cell with value 1 as the elevation is 1 at time 1 the water level will be 1 at all the cells and you can reach here consider you travel to that cell and from here at the time 2 you are traveling to the next cell and at time 3 you are traveling to the next neighboring cell and at time 4 you reached here time 5 you reached here so from five you have two options either to reach the level with 21 or the elevation level with 16. so to travel to 21 you must wait till the 21st time or to travel to 16 you must wait till the 16th time so considerably 16 is the lesser time so we are waiting till 16 and we are still roaming around somewhere in 5 till we reach the 16th time and at 16th time we are reaching 16 so now from 16 you have again two options either to swim to 20 or to 15. so if you have to wait to travel to 20 you have to wait till 20th second and straight away from 20th second you can travel to or swim to six as six is having the lower elevation it will be already filled with more water so you can directly swim from twenty to six so that is one option for that you have to wait till 20th second or 20th time so from 16 you are planning to travel or swim to 15 because 15 is lesser elevation compared to 16 then it must be having water more than 15 level so you are traveling to 15 at the same time on the 16 second itself because you don't have to really wait for the water to fill up again from 15 to 14 to 13 to 12 as these things are indicating the elevations they must be having water already higher than the elevation at the 16th time so we don't really have to wait we can simply travel to 11 to 10 again goes to 9 8 7 and 6. so you have reached your last cell at the 16th time itself so that is the minimum time you can take to reach the last cell and that is going to be our output so by now you must have understood how are we going to approach this is a very simple bfs technique as usual we are going to implement a bfs which is going to track all the neighbors and add them to our queue and explore further its neighbors and whichever reach at the earlier time we are going to return that time as our output but here instead of using a normal cube we are going to implement a priority q y because we are going to pick the lesser elevation once first and then travel through that because from the two options we had from the very first cell where either to travel to one or twenty four we picked one same way from five we had two options to travel to 21 or 16 we picked 16 same way from 16 we had options to travel to 15 and 20 but we picked 15 so that we arrived at our solution earlier so in order to arrive at a solution earlier we need to pick the lesser elevation ones first and then move to the higher ones so instead of a normal queue we are going to maintain a priority queue so in our priority queue we are going to add an integer array which consists of three elements where i j and value i and j are nothing but the cells coordinates and value is nothing but the elevation value inside it so every time we explore it for example first time we are going to add 0 comma 0 as we are going to start from the 0 comma 0 cell with elevation 0 and next we are going to pick the neighboring cell and update zero comma one so here one is not the elevation but the time it takes to reach that particular grid again zero comma twenty four is another option where we have to wait till 24th second to reach here same way we are going to explore its neighbors and we update the time accordingly so here the time is nothing but this value in the array we pull from the queue so this value is nothing but the time we took to reach the cell so this is going to be max of the new grid we reach come on the current grid vr so if suppose you are at the cell with 16 so in that case even if you travel to 15 14 or 13 you must have waited till 16th time to reach that 16th grade so how much ever cells you travel 16 is going to be the time so in that case if you calculate the neighbor it is going to be 16 comma 15 and 16 comma 14 and 16 comma 7 and 16 comma 6 every time 16 is going to be assigned to our time so yes hope you're understanding this solution this is going to take big o of n square into log n time complexity so let's go to the code now so yes first let's declare the basics as i said we need a priority queue and in comparator we are checking the values or putting in the values based on the third value in the array in ascending order and first we are going to add our 0 comma 0 which is nothing but the value at the very first cell so once we added that we are going to maintain another array which is visited which is going to keep track of already visited grids in our grid so first we are going to start from the first cell so we are updating it to true and we are going to iterate until our cube becomes empty and we are going to explore and add all possible neighboring cells four directionally so that we have a array direction and we are going to iterate that array so that we create new four coordinates x comma y will be the new neighboring coordinate and we are checking for the base basic conditions h conditions if none of the calculated new neighbor cells coordinates or age condition we are going to skip it then we are checking if it is not already visited then we are going to visit it so we update the boolean array to true and we calculate the time as i said the max of new neighboring cells elevation comma the current elevation whichever is the max that will be the time being updated and if we reach the right most bottom cell then we return whatever the time calculated so far if not we are going to add its neighbor so finally return time and let's run and try finally return 0. yes so let's submit yes the solution is accepted so thanks for watching the video hope i made it clear if you like the video hit like subscribe and let me know in comments thank you
Swim in Rising Water
reorganize-string
You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`. The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most `t`. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim. Return _the least time until you can reach the bottom right square_ `(n - 1, n - 1)` _if you start at the top left square_ `(0, 0)`. **Example 1:** **Input:** grid = \[\[0,2\],\[1,3\]\] **Output:** 3 Explanation: At time 0, you are in grid location (0, 0). You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. You cannot reach point (1, 1) until time 3. When the depth of water is 3, we can swim anywhere inside the grid. **Example 2:** **Input:** grid = \[\[0,1,2,3,4\],\[24,23,22,21,5\],\[12,13,14,15,16\],\[11,17,18,19,20\],\[10,9,8,7,6\]\] **Output:** 16 **Explanation:** The final route is shown. We need to wait until time 16 so that (0, 0) and (4, 4) are connected. **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] < n2` * Each value `grid[i][j]` is **unique**.
Alternate placing the most common letters.
Hash Table,String,Greedy,Sorting,Heap (Priority Queue),Counting
Medium
358,621,1304
1,816
e Hello everyone, we are together again with another question, today we are together again with this last picture trunk and sandals A sound given to you String Friends it is given as a sentence mind keijiro Everyone English letters and it is stated that it is just white-space It is stated that there is no dress at the beginning stated that it is just white-space It is stated that there is no dress at the beginning stated that it is just white-space It is stated that there is no dress at the beginning or end here For example hellogold hello It is stated that all of these are without you in the form of hello Mortal. This, friends, is stated in the question as s plus and interturk Ah crushed and it does not want you to return the first word in its set, that is, there are one or more words in our silence. If we look at it, we are asked to return the number of Strings back. If we look at it, the input String is given like this, but when 4 is given, is it possible to return the first four words here to the data like this? This is the third one. If you look at it, friends, there are 1 2 3 4 5 words here and it is stated that K is equal to 5. Here again, we are asked to turn it into the skin, just like the whole citrine itself. That's why, friends, here is the part. Actually, the main part we need to do is this. E, the silence between us both. Since there is no Space at the beginning or end, and there is no space character, we can actually call the end of each word a Space. If we see a space, we can make a judgment that it means a word has passed until that moment. Then, actually, when By doing a little searching in the set, you can actually create information such as "I have seen Kadet Space" by doing a search in the string from the beginning. If I have seen it, we have returned all the strings up to 10. For this, can actually create information such as "I have seen Kadet Space" by doing a search in the string from the beginning. If I have seen it, we have returned all the strings up to 10. For this, can actually create information such as "I have seen Kadet Space" by doing a search in the string from the beginning. If I have seen it, we have returned all the strings up to 10. For this, Friends, first of all, I will create 2 variables. First, I will start scanning from the beginning of this string. In fact, every I will keep an index Elif in a character. And friends, what is westbound et, I will keep this variable, how many Vices we have seen, it will keep this, and then as long as the length of the baer index and set is small and I stayed in Espace, as long as it is small, I will continue to iterate in it like you did it. Whenever I see a beautiful bright space with equal index to each other, I will increase it like that here. Is it Space County? And apart from that, we will increase the friends index by one. Since I start from scratch each time, I will continue to scan as long as the Space presentation is smaller than the paper given to me that day. When For example, I found a third head Face. This means that I have passed three words to it. Maybe I will pick it up later. If after leaving this honey, I have come to the end of the index. There is no other character I can go to. This is the police. I will go out or here it is really spacecom Kaya is equal to pay when it is equal that I have found K words it is labor coming out of here After leaving here friends If really my skyscan is the same equal vegetable really in the meat set so many k I have become what does it mean Therefore here at the bottom handle stronglifts Starting from the zero stitch until nexi one, it's always up to that moment because the last one will now be my space. How long did I go to the game support? Actually, when I get the length of the index up to one, I found that many words, never friends. This means that I have K in my entire string. What does it mean that I couldn't reach the Space? Here, it will be enough to return our Halo existing string back. 21 10, I put our code here too, it exists in another way, now our code exists in a different way, I can Ahmet, I read it successfully, in 88 milliseconds, Yes, conditioned in Percentage. It was wrong faster than sixty-three, Percentage. It was wrong faster than sixty-three, Percentage. It was wrong faster than sixty-three, but as I said, friends, we did not use any extra spss here, it is just a white-space inside the existing String, that is, it has the number of spaces. white-space inside the existing String, that is, it has the number of spaces. white-space inside the existing String, that is, it has the number of spaces. If it can actually reach a space as big as ours, then it is inside the Sak String. You are pure in the system, take the ones with index from zero to one, like minus one. Actually, it is zero at the end. Sorry, we get this because Ice gave up at the end. Yes, it means that I found K words in this set. That 's why I 's why I 's why I was patient. If it is not equal, friends. This means that it is like my style. There are no words. When it is given to me, then it is enough to turn my string into a solid again. Yes, friends, I did this question wrong, that's all, bye to see you in the next video.
Truncate Sentence
lowest-common-ancestor-of-a-binary-tree-iv
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation). * For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences. You are given a sentence `s`​​​​​​ and an integer `k`​​​​​​. You want to **truncate** `s`​​​​​​ such that it contains only the **first** `k`​​​​​​ words. Return `s`​​​​_​​ after **truncating** it._ **Example 1:** **Input:** s = "Hello how are you Contestant ", k = 4 **Output:** "Hello how are you " **Explanation:** The words in s are \[ "Hello ", "how " "are ", "you ", "Contestant "\]. The first 4 words are \[ "Hello ", "how ", "are ", "you "\]. Hence, you should return "Hello how are you ". **Example 2:** **Input:** s = "What is the solution to this problem ", k = 4 **Output:** "What is the solution " **Explanation:** The words in s are \[ "What ", "is " "the ", "solution ", "to ", "this ", "problem "\]. The first 4 words are \[ "What ", "is ", "the ", "solution "\]. Hence, you should return "What is the solution ". **Example 3:** **Input:** s = "chopper is not a tanuki ", k = 5 **Output:** "chopper is not a tanuki " **Constraints:** * `1 <= s.length <= 500` * `k` is in the range `[1, the number of words in s]`. * `s` consist of only lowercase and uppercase English letters and spaces. * The words in `s` are separated by a single space. * There are no leading or trailing spaces.
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
Tree,Depth-First Search,Binary Tree
Medium
235,236,1218,1780,1790,1816
28
find the index of the first occurrence inside of a string we need an INT H is equal to hashtag.length and n is equal to hashtag.length and n is equal to hashtag.length and n is equal to needle dot length an end to n index is equal to zero or end I is equals zero I is less than H and I plus if Haystack dot Char I is equal to needle dot chart in index plus otherwise I is equal to I minus an index and index is equal to zero outside the if else we'll say if in index is equal to n return I minus n plus one and outside the for Loop return negative one type out this should be minus not equal and there you have it a zero millisecond run time which will be 100 it even beats 64 of memory complexity as always I'm not really that concerned about the memory complexity if you do want to see a full breakdown and walk through this problem check out the latest video here on my channel link down below and that is how we can solve problem number 28.
Find the Index of the First Occurrence in a String
implement-strstr
Given two strings `needle` and `haystack`, return the index of the first occurrence of `needle` in `haystack`, or `-1` if `needle` is not part of `haystack`. **Example 1:** **Input:** haystack = "sadbutsad ", needle = "sad " **Output:** 0 **Explanation:** "sad " occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. **Example 2:** **Input:** haystack = "leetcode ", needle = "leeto " **Output:** -1 **Explanation:** "leeto " did not occur in "leetcode ", so we return -1. **Constraints:** * `1 <= haystack.length, needle.length <= 104` * `haystack` and `needle` consist of only lowercase English characters.
null
Two Pointers,String,String Matching
Easy
214,459
463
Island perimeter so you're given a matter of grid rows into columns representing a map where bit of I comma J equal to 1 if it's representing that and the get rid of I comma J will be 0 if it is representing water so if it is land then one if it is water then it is zero so grid cells are connected horizontally or vertically but not diagonally and the grid is completely surrounded by water and there is exactly one eye line so in the given Matrix there are exactly one Island and they are connected horizontal or whatever but not diagonal the diagonal they are not connected so Island doesn't have legs meaning the water inside isn't connected to water so around the island so one cell is a square with side length of one and a three days rectangular uh width and height doesn't exit 100 determine the perimeter of the element so what the mean is they have given the Matrix and some columns are representing but some columns are representing Zero The Columns which are representing one or nothing but the recipient columns representing zero are representing the water so they have said there will not be any column like uh water surrounded by lamb that will lead right the quarter is around the balance that is so in this case perimeter will be one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen so sixteen is a perimeter of the island and it is filtering 16. so you could say zero one zero in the first row second column next second row all the first three columns it is land then third row second column is a land fourth root first two columns are the left so that is a representative now how do we calculate the perimeter so we know so this is 0 1 0 then 0 1 0 so class one zero so how do you calculate the perimeter of the element so we will have a variable called count to calculate the parameter or count equal to zero initial so now we check uh we have to assume in Matrix using we have to run for Loops so M representing rows row zero length it will be 4 here and N represent the column length so that will also be 4. so for I equal to 0 till I lesser than M then for J equal to 0 KJ is n and J plus I plus that is normal for two follows so this is 0 1 2 3 and 0 1 2 3. now essentially what we will do is see this is representing whether we will check whether or the grid of by comma J if it is equal to 1 the grid of I comma J is equal to 1 here it is equal to one no but here yes it is then you increment count by four so count plus equals to 4. why 4 is the perimeter 1 2 3 4. simple increment the count by four you know this is sharing this one year perimeter but that we will consider it later but for now let's say the count is equal to 4 that is four sides of the uh given box that is next this will be 0 this won't be counter because grid is not equal to one here when you come here again greater will be equal to one so this is 4 and this is also 4. okay next coming to here when you come here count every also four but you could see these two are sharing right these two are sharing now we will want to know we will subtract this how do we subtract this so for that we have to check first grid of I comma J is equal to one if it is equal to one you increment the count by four next we check whether the column present about to the given column so this is the column present about that is this and the row present left to this is if these are representing land if these are representing one so column present to this means it will be J minus 1. so great off I comma J minus 1 and the row one row back to that bit of I minus 1 comma J if it is equal to 1 and for this to happen what if the column is here J minus 1 is present here no so here you have to say J should be greater than 0. is greater than zero I should be greater than 0 and here also J should be greater than 0. so here J should be greater than 0 here I should be greater than zero see if I is equal to 0 is present what if you do J minus 1 they are one second so this is I this is J here means this is J because L bring J minus 1 here it should be I see if J is already 0 you cannot go back one column back here so J should be greater than zero if I is already zero then you cannot move one row above okay if this is greater than zero if it is equal to 1 you need to count minus equals to here also count determined by two so I'll just erase all this so if these two are the columns we consider so here we have count as four here also you have count of four now so once you go here you come is there any column about this a row about to this there is a column here Beyond to this but there is no row by upon to this so this won't happen if there is a column Beyond to this but this column doesn't have equal to this is representing zero this is what so it doesn't matter you don't have to check this so okay if this perimeter is considered and this is but when you come to this column here you could see uh the row about to this I minus 1 is equal to 1 that is one right I is greater than zero of course so this please share it we have to supply this so we will determine by one so one perimeter counting for this mother perimeter contact for this sorry because we have incremented it by 4 right for each two so here it is 4. this will have one fourth perimeter this is one format perimeter and we have to cut down this now means this has to be taken out this has been taken that will be a total count of two so that's why we are subtracting it by two same thing happens for the if this is a column this will be four and this will be 4. this is sharing we do not require this so this will be cut down this should be cut down because here while taking into counter four this is decorate account here also in the four this is all taken so subtracting 2 that is so first you have to check whether the given column is one or not if it is one this side again this column will be this box will take a little okay here the above column above is land so you here also you supply milk to the result that works so even given a box is like then you increment by four then check for the neighboring column right column is before column like the end if it is this will check for this and this so that is how you solve the problem if this is array then deleted this for this so all the columns and rows are taken into account m equal to grid dot length then int n will be equal to the column so that will let's say grid of 0 dot left so next are the fall for in I equal to 0 I lesser than m i plus again for in J equal to 0 lesser than n and J plus if grid of I comma J equal to one then you do count plus equals to that's equals to 4 and we will have it code here perimeter so again you have to check for neighboring things so if I greater than 0 and grid of I minus 1 comma J equal to 1 then count third is the prime minister count minus equals to 2 so subtract value again so for the minus equals to yeah so at last we will submit this okay one thing yeah we have missed over here this if condition we have to do only if this becomes true if this is true then only we check for the neighboring cells so here and inside that we have to paste the code got it that's why it was showing the Romans if this is a lag only then we'll check for the neighboring lights otherwise you won't be checking for the neighboring lines okay this column I haven't given it correctly okay now we'll take this over here yes yeah successful is applicable if you understood the problem please do like the video and subscribe to the channel you'll come up with other videos
Island Perimeter
island-perimeter
You are given `row x col` `grid` representing a map where `grid[i][j] = 1` represents land and `grid[i][j] = 0` represents water. Grid cells are connected **horizontally/vertically** (not diagonally). The `grid` is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes ", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. **Example 1:** **Input:** grid = \[\[0,1,0,0\],\[1,1,1,0\],\[0,1,0,0\],\[1,1,0,0\]\] **Output:** 16 **Explanation:** The perimeter is the 16 yellow stripes in the image above. **Example 2:** **Input:** grid = \[\[1\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0\]\] **Output:** 4 **Constraints:** * `row == grid.length` * `col == grid[i].length` * `1 <= row, col <= 100` * `grid[i][j]` is `0` or `1`. * There is exactly one island in `grid`.
null
Array,Depth-First Search,Breadth-First Search,Matrix
Easy
695,733,1104
926
hey everyone welcome back and let's write some more neat code today so today let's solve the problem flip string to monotonic increasing so we're given a binary string and it's defined as being monotonic increasing if it consists of some zeros or possibly none and some ones possibly none but all of the zeros are on the left side and all of the ones are on the right side basically the zeros and ones have been partitioned in this way zeros on the left and ones on the right now it's possible that these could all be zeros that would be fine it's possible that these could all be ones that's fine as well but we can't mix and match like something like this we can't have a zero one zero and we can't have zero one zero and Etc we can't mix these together and we're given a string where we could have them mixed together like these two examples but our goal is to make it monotonic increasing and we want to do so in the minimum number of flips so just by brainstorming you might think that it's possible to solve this with two pointers we could initialize a left pointer and we could initialize a right pointer and maybe do something intelligent but the problem is that we don't have enough information on the left and right side we need to know what's in the middle to be able to intelligently come up with the minimum number of flips so in a sense we do have to brute force it at least that's one way to do it which is basically to say we go digit by digit let's take this example actually I'm going to take the second one because it's a bit more interesting but for every single digit we have two choices we start with a zero we can leave it as is or we can flip it to a one and we can make this choice for every single digit in the input string but there's one little catch so we can keep going like this zero one but what about on this right side if we took this zero and flipped it to a one then we can't just go to this second digit and say well it could either be we could either swap it to a zero or swap it to a one or you know depending on what it is it'll be remaining as a one or maybe if it was Zero it'll be remaining as a zero but we can definitely not have zeros come after a one value so we have to make sure if we either flipped a zero into a one we can only have ones that come after it or if we were just given a one like maybe the first value here was a one and we left it as is then we have to make sure that everything that comes after it is also a one because remember we want this to be monoton increasing we're not just looking for every possibility so this is one way to do it and by doing it this way we'll end up with two variables one is going to be the index it's going to help us iterate through this and we're going to do so recursively as you can see with this tree it's going to be a recursive backtracking tree but there's going to be a second parameter that second parameter is going to be a Boolean to indicate whether r our string is monotonic increasing so far or a better way to say it would be so far we have only zeros on the left hand side because remember what happens as soon as we encounter a one that we don't change then everything after that has to also be a one so we kind of run out of choices at that point here we would not be able to make this second choice and here as we see ones we would leave the ones as they are but if we ever saw a zero we would have to flip it so we'd have a second parameter but it's a Boolean so with these two parameters we can take this backtracking solution and add a dynamic programming technique called caching to it and the dimensions of these parameters I mean what are all possibilities I could be there's n possibilities one for each position of the length of the input string and the second is a Boolean so there's two possibilities for it so the total number of possibilities for these input parameters is 2 times n so if we cache this then the overall time complexity will also be Big O of n I'm going to quickly show you the code for that but since we are caching the size of our cache is also going to be 2 times n so we're going to need extra memory and there is a more efficient way to do so which I'll show you in just a moment but first let's take a look at the code for this solution so this is what the code would look like it might be a bit confusing but let's focus on these four cases here it is recursive and I have this a second Boolean parameter called Mono it could have had a better name but I hope you kind of understand what it means the base case here is that if we run into an input option that we've already seen and cached in our DP cache before and in that case we would immediately return it and we wouldn't have to go through the recursive case you can see there's actually another base case if our eye pointer is out of bounds then we would want to return zero and I've kind of done that up above I've added those two base case cases to our cache itself so that basically allows us to not have to write out this if statement so if I is equal to length s then return 0 I've basically reduced the need to do that but that's a small point and you wouldn't really have to know or understand that but these four cases are the important part if we have all zeros up until now and the value we see right now is a zero then we have two possibilities we can either take this zero and swap it that's this case over here where we're taking mono it was originally true we've seen all zeros but then we change it to become false and of course we increment I to one that's we're going to increment I to one in all of these cases because we want to move to the next character regardless but if we take the zero and swap it to a one then we're gonna say one plus the result of whatever the recursive call is the other option is we leave the zero as is that's this case up down here where I'm not adding the plus one I'm passing I plus 1 and I'm leaving mono as it is it's originally true and we leave it as true now we don't know which one of these is going to produce the minimum result that's why we're taking the minimum of both of these and assigning it to our DP cache the second case here is that we've seen all zeros up until now but now we encounter a one if that's the case we can choose to swap this one to a zero and that's this down here so we're making a swap so we have the plus one and we're also calling our DFS our backtracking and we pass in mono as it is we know it's still monotonically increasing or rather we know there's all zeros still up until now because we swapped the one to a zero but the other case is where we leave this one as it is in that case we don't add a plus one because we're not doing a swap but then we have to say mono is no longer true now it's set to false we can't say that we've seen all zeros up until now because we saw this one and we left it as it is these two cases are little bit more straightforward because we know up until now we don't have all zeros we've seen some ones before and that means every value that comes next also has to be a one so if the character we see is a one then that's good because we don't have to add plus one we just call DFS on I plus one leaving mono as it is which is false in the last case since there's only four total possibilities we just say else but we know that mono is going to be false or actually I just realized I have these comments in opposite order I'm going to take this and move it here sorry for the confusion so this case means since up above we had the character is one down here we know the character is going to be zero if it's zero unfortunately we do have to make a swap because we have to make sure that now every character is a one so we say plus one and we pass an i plus one and leave mono as it is it's false and that's all we care about and then we just take that value and then return it that value that we have cached and outside we are just calling our DFS function initially passing in zero that's the index that we're going to start at in our string and initially passing in true we're basically saying that we've seen all zeros up until now because we haven't even seen any characters so we can pretty much say it's monotonically increasing and running this code you can see the runtime isn't super efficient but the overall time complexity actually is about as good as you can get but I'll show you a more efficient and pretty tricky way to solve this problem I'll show you the linear time solution that does not take any extra space and we're going to use the same example so let's try to understand the solution we're going to start at the first character it's a zero so we don't really have to do anything then we get to the next character it's a one the main problem we have here is that we don't know what is going to produce the string that takes the minimum number of flips to create we don't know if that means this should be a zero or it should be a one so we still have to consider both possibilities but how can we do that without doing it recursively with two branches well one way to do it is we know that no matter at what point we get in the string as long as we count the number of ones we can always say we can get to the end of the string and say okay we had a three ones total well let's just decide we wanted to flip all of them to zeros so one thing we're going to do is keep track of the ones it's better to keep track of the ones instead of keeping track of the zeros we could do that if we wanted to but remember the zeros have to be on the left side and the ones have to be on the right side and we're iterating from left to right so we're going to be keeping track of the ones because we can retroactively flip them if we later decide to so that's what we're gonna do anytime we see a one we're going to keep track of it so count one is going to be one at this point when we get here and then we're gonna go to the next position notice how up until now our string is monotonically increasing but now we get to a zero and we do have that choice to make do we want to flip this to a one or do we want to leave it as a zero the good thing is we can make both choices and figure out which one leads to the minimum you want to know how because we have the number of ones that we previously saw in the string if we decide to leave this as a zero we can say let's just flip all of those ones to a zero how many were there just a single one so let's leave this as a zero that's one possibility how many flips would it take to make this string monotonically increasing in that case just one we just have to flip this one bit otherwise we can say let's just take this guy and flip it to a one how many flips is that going to take well in this case just a single flip so what's the minimum of those two well it's gonna be one because we're basically taking the minimum of one and one so that's going to be one so far so that basically tells us that if we want to make this string monotonically increasing it just takes a single flip notice how it doesn't tell us though what the string looks like it could have looked like this zero one or it could have looked like this zero the good thing is as we continue going through the string we can fall back on either of those but another variable I haven't mentioned yet is the result variable that of course we're going to need to keep track of and this is going to keep track of how many flips we need to make and so far at this point it is one to make this monotonic increasing now let's go to the next character here we see a one what are we gonna do we're just gonna take our count one and increment it now to be two well hold on I thought every time we go through the string we have to guarantee that this is monotonic increasing how do we know it's only going to take a single bit flip to make that happen well remember we saw a one right now and we guaranteed that it only takes one flip to make this monotonic increasing but the question you might have is we don't know if that means the string looks like zero or it looks like zero one my answer to you would be does it matter look at this one this would be monotonic increasing and the other possibility zero one is also monotonic increasing that's the tricky part that you don't really realize until you actually start looking at a bunch of examples and start playing around with it and this the rest of this algorithm will hold let me kind of run through it very quickly we see another one we don't have to increment our result at all we just take our count one and change it to now three we've seen three ones so far now we finally see the last zero so we have a choice do we want to take all the ones we've seen so far and flip them that would take obviously three flips or we have another choice We Know It took one flip just a single flip to make this monotonic increasing we don't know again if it looks like zero one something or if it was all zeros but either way if we're gonna flip this guy it wouldn't matter if we had zero one or if we had zero one and then one here it doesn't matter so what I'm saying is the choice we have is the minimum of three which is how many ones we'd have to flip or just flip this guy plus however many bit flips it took to do all previous stuff so one plus one from here and which one of these two is the minimum it's two of course I know this is pretty tricky but I hope that it's starting to make sense for you so now let's code it up notice how we didn't need any complex data structure so the memory complexity for this is constant okay the good thing about this solution is it's pretty easy to code up but not super easy to come up with the result we are going to initialize as zero we're going to initialize the count one also as zero we're going to go through every character in the input string if the character is equal to one remember what are we going to do just increment R count one by one otherwise the other cases we see a zero then we want to take the minimum of whatever the result is so far plus one initially it's going to be zero which makes sense or we're going to take the minimum of count one which is also initially going to be zero and say that this is the number of bit flips it would take to make string monotonic increasing up until this point and that's what we're going to assign the result to and after all that is done we're just going to go ahead and return the result I know that looks really easy but don't feel bad if you weren't able to come up with this but let's run it to make sure that it works and as you can see yes it does and it is pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io it has a ton of free neatcode.io it has a ton of free neatcode.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
Flip String to Monotone Increasing
find-and-replace-pattern
A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none). You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1` to `0`. Return _the minimum number of flips to make_ `s` _monotone increasing_. **Example 1:** **Input:** s = "00110 " **Output:** 1 **Explanation:** We flip the last digit to get 00111. **Example 2:** **Input:** s = "010110 " **Output:** 2 **Explanation:** We flip to get 011111, or alternatively 000111. **Example 3:** **Input:** s = "00011000 " **Output:** 2 **Explanation:** We flip to get 00000000. **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'0'` or `'1'`.
null
Array,Hash Table,String
Medium
null
410
hey everybody this is larry this is me doing the oh the last day of march hit the like button hit the subscribe button join me on discord let me know what you think it's been a whole month uh congratulate yourself you made it this far and if you haven't that's okay too i mean uh sometimes you go at your own pace and sometimes that means a streak sometimes it means not a streak but that's okay just do as much as you can do as much as you want and you know pace yourself uh it's a long journey it doesn't have to be a sprint it could be a slower jog if you will uh only you matter uh okay so today's problem is split away largest sum i actually took a great nap so hopefully today i'm a little bit better i've been a little bit uh rough around the edges lately so um with implementation so we'll see how that goes because i feel like i've always known the algorithms uh or the problem-solving the algorithms uh or the problem-solving the algorithms uh or the problem-solving part i'm okay uh but not the programming part which is something that for some reason used to be my uh it used that part is out to some reason but uh something that used to be my strength but definitely has been a little bit weaker lately okay all of that being said let's look at today's problem split away largest sums given the numbers consists of non-negative integers and consists of non-negative integers and consists of non-negative integers and integer m split away into m non empty contiguous sub arrays minimize the largest sum around these m sub arrays okay so this is um this is what i used to call the bookshelf problem but i think um i don't know the actual name but uh yeah but it has a couple of different ways to go about it um the way that i do it uh and this is why i actually don't like the way it is set up right now where every week has a team week i get what they're going for and i understand what they're trying to do uh but they already have like what's it called x4 or whatever it is that is a section for this right the problem is that it gives you a hint right like without like for me at least the way that i like to think about it is that the challenge is you know especially if you're in the beginning or you know uh lead code is a little bit on you know if you're doing competitive lead code is a little bit on the simpler side or maybe not simpler side but like more fundamentally based so basically you have maybe like i don't know 10 to 15 algorithms um and you have to try to figure out which one to use right and for hardware maybe which two to use but that said and if you're already given a hint about what category it is it really takes the difficulty out of it uh i mean this one it actually didn't matter because i know it anyway but um but i think that's my main complaint right now about these themed weeks um i mean it's not a big deal obviously it's fine but it is something that i would um it's just a comment um that said yeah i used to i think the first time i've seen this prom and it's uh it's been two decades uh is that it used to be a bookshelf problem the way that i always think about it is um you have uh you have books of the couple variation of this of course actually um but your books of certain heights um in some variation it could have a certain riff as well but um and you can only fit you know uh a certain total rift per uh per row and then you're trying to um trying to see if you could fit in a bookshelf or something like that right and then the idea here is um greedy and binary search is the way that i would do it there's also a dynamic programming solution which depends on n you can do or you cannot do um yeah but given that n is a thousand so you can actually do a dynamic programming solution um yeah so you can definitely do that your dynamic programming solution so i think even though technically for this particular problem the binary search is going to be faster because you look at the cons constraints actually i missed this part but um so you look at the constraints and so forth but uh but i would also urge to uh observe using dynamic programming just so that you could practice dynamic programming especially this week where or this month maybe the last couple of weeks where everything is deemed and you don't really uh get to exercise that categorization angle if you will um i mean it's great if you're in the beginning and you're starting out and you just want to practice the same type of problems like you know for you know in the beginning i think that the best way to learn is practice the same type of problem if you haven't exp been exposed to it and you're just doing binary search problems for the first time for example and you would do like 20 of them that's fine but for these things i feel like it's a little bit awkward when half the scale or maybe not half but some portion of the skill is identifying what kind of problem it is right so uh so anyway so all that being said let's just go for it so the idea for this one is greedy and binary search um the idea the greedy idea is that okay you can just guess right let's say the largest sum on these sub arrays let's just guess a number x and given that number x how many sub arrays do you come up with meaning does it fit if you will in a bookshelf if you want to still use the bookshelf analogy um and if it fits then you have a binary true and if you don't fit then you have a binary force and from that you can construct a binary search solution right because now if you look at this i really need to get my binary search video out so i don't have to explain it or at least i don't have to like go over the very basics um but yeah but this is going to be if you use a small number so what happens right so and this is the way that i think about it where i want to see if this is this or this and of course uh you know you could invert them anyway but and this is just phosphorus four is true and or this is the reverse and the way that i see it is that okay if you have say um the sum is one what happens well it just won't be possible so you would have uh too many sub arrays in that case maybe i'll just set infinity so infinity it's going to be too much it's going to be false i mean this is true so then we have this kind say and then now we can get started right so let's check the constraints to each numbers is i tends 10 to the sixth uh you have at most 50 arrays um so the most sum you can have is going to be what is it right so the sum of the entire uh array is gonna be 10 to the six times a thousand which is ten to the nine and ten to the nine over fifty is going to be is it over 15 all over or less than 50 maybe so anyway 10 to the nine movie the upper bound i think that's a safe upper bound so let's get started there so left we want the way that i always set it up is again bring inclusive bounce because it makes sense for me a little bit more here we do the right it's going to be some of the numbs and i think that should be good um yeah and then now you know this is i write this the same way the reason why i like inclusive banks is that this state when this one when this statement is forced it means that left is equal to right and when levels you go to right that means that your inclusive bound of one element and that's why i like it that way um your mileage may vary but yeah uh yeah so now we go if good admit then okay so what is good right i name it good you can name it something else i think good is actually maybe a terrible name but um but yeah so this is the target sum so then we greedily let's say um yeah so what is this what does we want to return right given um given the max sum of a sub array is target how many sub arrays are there right so that's basically the idea we want to do um and is that number smaller than m smaller than or equal to so that's basically what we want to do so here this is going to be good if the number of sub arrays is going to be m or smaller meaning that we fit again you can change around how you define these things it will just determine your answer and that's all basically we um uh let me think about that okay so yeah let's get started on the this implementation of this part so we have count zero for x in uh nums uh oh if we have the current so then if x is greater than target that means that it doesn't fit then we return infinity and we have infinity then the number is not smaller than m so this is going to be false um okay otherwise current add to x um oh i guess count is always one because you have at least one thing okay so if current is now greater than or uh greater than uh target then current is equal to x because that means that this went over and you have to increment count and then now at the way n as we said we see if count is less than or greater than m uh way easy to have off by once by the way so definitely slow down if you um and really go through it but uh okay so now if this is good what happens if this is if this is good right and it's possible that i messed this up to be honest so let's think about this very slowly this is good what does that mean right if the mid is good meaning that if the sum is good we want it to have a smaller sum um because we know that mid is going to be good so we want it to be have a smaller sum so we said right is equal to mid else left is equal to mid plus 1 because mid is too small so we need a bigger uh sum so that means that we want to bound the range to the right and also that mid is not a possib possible answer so yeah and then now we all we have to do is just return left um i want to make sure that i phrase this one right i think that's what i'm struggling with so yeah it should be okay let's give it a spin okay so that looks okay um we have to consider some edge cases of course um what is a good edge case okay i'm a little bit lazy so let's just give it a submit maybe i would get the oh no that is the edge case that i was worried about oh hmm for some reason oh okay that's uh for some reason i thought that the lower bound is going to be one because yeah i just i didn't i think i saw this to be honest um and this is something that you have to be really careful about i've definitely made this mistake before um the thing to notice is that because i saw this as equal to one but i actually looked at here and then because you have to um consider the total range of these things and in this case is it is this pretty much i mean this is zero so we should have had because here um in an inclusive bound from one to the sum is going to be the possible answer but actually what we should have done is here um yeah i was a little bit sloppy because i didn't look at the balance here and this the range is of course going to be zero but yeah uh yeah so now this should be fixed at least for this one uh i wonder if i did the same thing there um yeah so uh i'm just curious about i did that previously oh this is a different end oh i had an infinity so i did this a different way actually um okay i did it to cheesy binary search i'm not going to go over that part uh i have a video coming out that explains it but i did mess this up because i for some reason actually i don't know why i started at one but i didn't revisit it that is something that uh i'm i need to remember to revisit but uh but yeah but left basically the answer could be zero and if i start at one then bring an inclusive brown zero is not a possible answer and that's why you know i didn't i messed up on that one um that is how to be honest that is like a uh a big portion of my mistakes on discount problems just that i actually i skipped over this part because i focus on this part and then i forgot to go back and make sure that this is right and here you can easily see that this is zero because zero times a thousand is zero or whatever um and the other side is bigger um cool uh yeah this is going to be as you know this loop for example is going to be log of the range and the range is going to be 10 to the 6 times a thousand which is 10 to the nine right so this is going to be what like thirty is ish dirty ish um and so that's the number of iterations here and of course the good function is gonna be of n so this is in total o of n log r um and that's how you do a binary search and of course in space this is just over one because we only have uh where constants also yeah this is a linear thing but that's fine um cool that's all i have with this one let me know what you think uh if you have done every problem this month congratulate yourself a lot if not that's okay you know next month is uh it's enough next month is another opportunity for you to uh do well so you know that's up to you anyway that's all i have stay good stay healthy to get mental health and i'll see you later bye
Split Array Largest Sum
split-array-largest-sum
Given an integer array `nums` and an integer `k`, split `nums` into `k` non-empty subarrays such that the largest sum of any subarray is **minimized**. Return _the minimized largest sum of the split_. A **subarray** is a contiguous part of the array. **Example 1:** **Input:** nums = \[7,2,5,10,8\], k = 2 **Output:** 18 **Explanation:** There are four ways to split nums into two subarrays. The best way is to split it into \[7,2,5\] and \[10,8\], where the largest sum among the two subarrays is only 18. **Example 2:** **Input:** nums = \[1,2,3,4,5\], k = 2 **Output:** 9 **Explanation:** There are four ways to split nums into two subarrays. The best way is to split it into \[1,2,3\] and \[4,5\], where the largest sum among the two subarrays is only 9. **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] <= 106` * `1 <= k <= min(50, nums.length)`
null
Array,Binary Search,Dynamic Programming,Greedy
Hard
1056,1192,2242,2330
208
hello guys my name is lazaro and today we're going to be doing a lee code problem this problem is called implement try aka prefix tree a try pronounced as try as i just said it a prefix tree is a tree data structure used to efficiently store and retrieve keys in a data set of strings there are various applications of this data structures such as autocomplete and spell checker implement the try class so a nice little definition on what we are imp or what are we doing what data structure we want to implement and then here they're actually telling us uh what are the functions or the methods that this class should have so the try and this initializes the object insert inserts the string word into the try search returns true if the string word is in the try and false if word is not in our try tree then starts with it will return true if there's a word within our try that has the prefix and if there's no word that has that prefix we return false so there's a couple examples down here but it's one of those examples where it's pretty annoying to look at uh so i'm just gonna go straight into the uh doodling so let's say we're given uh a word a couple of words actually you know what i'll start drawing everything in blue change things up so we're given apple and let's say we're giving we're given apron there we go so this tri is first going to be initialized with an empty node and the reason why we want an empty node is let's say we didn't start with an empty node let's say our first node in this tree represents the a character in this case this really this wouldn't be an issue but let's say we also had another word called blue well this a we don't want it to point to blue because if we were to build our word by following this path there is no word that's a b so b should not be a children of a at all there's this should not be an edge so instead the we can fix this by just having an empty node as our root and then that empty node can go to a and if we had another word that starts with a different character it could also go to b so you can pretend this empty node is just an empty string so if we were to follow this path we just have the word be in this path we have the word a so that's why we're choosing the route of starting with an empty node in this case this empty node only has one child which goes to a the reason for that is because if we're inserting apple let's say apple is the first word we insert we want each node to represent a character in the word now this is a little hint that we have to create another class we can call that class node and we want to hold a couple of attributes number one since these nodes represent the character for this word we're inserting we want this class node to have an attribute for that character we can just call that value and in this case for this node right here that value will be a now something else we want to another attribute that we want this node class to have is the next so a can go to p can go to r or you can go to d there we go all right it took me a while to come up with a word with an a and followed by an r and then with a d we can do a door so we have these two words then a can go to p because a p and apple then ap and apron a r for a r in arc and then a d for the a d and a door so we want since it can have multiple children keep in mind this is not a binary tree this is an n array tree where n represents multiple numbers it could be one it could be two it could be five and so on and so forth so we want to keep track of this next or the children for this current node now since all these nodes are going to be lowercase english letters we can have next be an array of size 26 because there's 26 characters in the english alphabet or what i like to do is create it or set it as a hash map now something else that we want to another attribute when we want to give all these nodes is if a single node we're currently on if it represents a word now why is this important well let's carry on let's fully put out this uh tree right here with this app on apron i wonder if i can go back no nevermind it looks like we're keeping the square surrounding apple build out apple p then goes to l then goes to e now let's build out apron we already have a right after our root node we already have an a so this means that we do not want to insert another a now this is one of the reasons why it says that it's an efficient way of storing and retrieving keys for a string because it takes advantage of the fact that it might have a common prefix with all the words in this case ap in apron and ap and apple they are a common prefix so instead of adding another a let's just take the a from apple we can also take the p from apple but from here we need to insert another node that goes to an r for the r and apron then from the r we can go to an o and then from the o we can go to an n now this is perfect but let's say we had a third word called app here app we can go to the a we don't have to insert another one we can use the a from apple and apron we can also use the p because ap is a common prefix in all three words and now we can use the second p from apple because this new word app is a prefix of apple so in this path right here we actually have two words so we cannot determine when we have fully built out a word by just looking at the last node and checking if that node does not have any children the reason we can't do that is because although we have the word app in our tree in our tri tree p has a children so if we go by the logic of just checking whether or not a node has children we will fail to notice that app is a word in our tree this means that we need to give a new attribute to our node class let's just call it done and initially done is will be set to false but for every word we insert let's say we just inserted app we go from a to p and then to the last p at the last node we want to change this done attribute and set it equal to true and i can represent that but just doing a check mark right next to each node that has done set to true this way if we were to for example run through this tree we go from a p since this node has done set to true which is represented by this check mark we know that everything we've built so far which in this case is just the letters app representing the word app we know that this is one word in our try if we continue we add an l and an e that's another word so we have apple now and then once we backtrack all the way to the p we go down to the r o and n now n has done such a true so that's another word we've built and we get all the words that we inserted in our tree so these are the three main attributes that we need for a try tree so this already fixes or we already solved this first rule the insert method now let's talk about search if let's say we have a we have we just inserted all these words now let's search for the word arose now for a rose let's look at every character first we're starting at the null node the first character in a rows is a well from the no doesn't have a children that starts with the k that has a node value of the character a in this case it does so let's go to that node so now we're currently right here the next characters are does this current node we're on have a next node does it have a children that has a value of the character r we can do this by just looking at our next dictionary and we notice that it doesn't the next one is p and only p so at this case since there is no children that has a value of r we know we can return false so that's the case for returning false now let's run through this for searching the word app we're still starting on the null node the first character is ache we ask ourselves well from this null node can we reach a does it have a children that has value of a in this case it does so we go to that a node the next character is p for this node that has a value of a does i have a children that has a value of p in this case it does so let's go there and then finally it has another p so this node has a value of p does have a children that also has a value of p it does so we go there and now we're done we have no more characters left to look at for our word that we want to search for that means on the last node we finished on we ask ourselves is it is done set to true in this case since we it has a check mark it is set to true therefore we know that the word app is in our tree now if i were if i word the word we were searching for was a p l then after seeing the p we would have checked if p has a children that has the value l in this case it does so let's go there and now we're done so we ask ourselves the same thing is this node it's done attribute is it true if it is true then we know we have this word in our try tree but in this case since it does have a check mark we know it's set to false therefore we want to return false because that represents that this word is not in our try that's the requirement for search returns true of the string word is in the try i.e it was inserted before appl was never inserted before but app was so that's why app returns true and apple returns false now the final one is starts with where we want to return true if there is a previously inserted string word that has the prefix so now let's say start from the beginning once again let's say our prefix is apr we still start at an empty node the first character we want to go to is a can we go from this empty node to a child that has a value of a in this case we could so let's do that next one is p we could do that because it has a child with a value of p and then the final one is r we can do that so let's go to the child node that has a value of r and now we're done here but that's not all we want to do we want to turn return true if there's a word that has this prefix and false if there's not a word that has this prefix so what are what else do we have to do in this case well this path that we've taken so far is exactly this prefix ap r and now all that we left to do is to run dfs on this last node and if we reach a node that has done set to true then let's return true because that's telling us that there's a word that has this prefix in this case if we run dfs from the r we go to o from the o we go to n and we notice how n has a check mark which represents that done is set to true so we want to return true that there is a word that has the prefix apr and now that is the last uh thing the this problem is asking us now the first one is just to initialize it and we can simply initialize it by just creating this empty node that's all we really need to initialize it once we call the class we have to create this root node which is an empty value so let's get to the coding and solve this question like i said one of the first things we want to do is create that node class so here i'm just creating its constructor and i might give value a default uh value of an empty string then self dot next is be equal to a hash map or a dictionary in python and self.done is reset to false by and self.done is reset to false by and self.done is reset to false by default then here in the constructor of the try class we want to create that root and set it equal to node and since i'm not passing any arguments that means this argument is going to take the default value of an empty string next let's work on the insert method let's say current is equal to soft dot root and then for every character in word let's try to see let's check if this node is already in our try tree we can do that by just calling cur dot next dot get character and if that character is my children of the current node we're on let's default to creating a node for this character whoops else if it is the children then we could retrieve it and let's just retrieve that the node of that children now we can do curd.next for this now we can do curd.next for this now we can do curd.next for this character set it equal to that node and once again if this node is in our tree we're just re uh resetting it we're just re-adding it to our next dictionary it's re-adding it to our next dictionary it's re-adding it to our next dictionary it's not gonna change much but if it's not there then it's gonna create a new node and now we're adding it for the first time the last thing we want to do is set cur equal to node because now since we're going one by one through the every characters in this word then we want to add the next character in the word to the current character we just added then the final thing is set curve dot done equal to true at the end ker is going to be equal to the node that represents the last character in this word and since that it's the last character in this word then we want to set done equal to true now we want to do something pretty similar for searching so i'm just going to copy that and paste it right here else what we want to do instead of creating a character for the word we're searching for let's default to returning false if that character is not in the children for the node we're currently on and if not node let's return false instead of adding it to the children's list let's just say curry equal to node and then finally after all is this all we have to check is if the last character in this word we're searching for check if that is done so just return curve dot done this will be true if we have previously inserted this word we're searching for and it will return false if this character does not represent one full word in our tree and now for starts with we want to do pretty much the same thing self dot itself is sorry curry is equal to self dot root and then for every character in the prefix let's just do curd dot next dot get that character or default to false now if not node we also want to return false because that's saying that this prefix the character for this prefix is not even in our try tree therefore we know for sure that no word is going to start with this prefix else curve is equal to node now after this for loop curve is going to be equal to the node that right that is the last character in our in this prefix and that is also in our tree so all that's remaining is for us to re to run dfs from this node and try to see if there's a node that has done equal to true has the attribute done set to true so let's just return self.dfs so let's just return self.dfs so let's just return self.dfs of this starting on this current node and let's build out this dfs function now if no dot done so if that's true let's return true now if length of node.next if there's no now if length of node.next if there's no now if length of node.next if there's no children if that's equal to zero let's return false else we want to if none of those if's hit what you want to do is create a variable called answer initially set it to false and then for every character and next node in the children of this current node answer is going to equal to answer or soft dot dfs of next node then finally let's return whatever answer is so if at some case in this dfs we did return true answer will be updated to true and that would propagate all the way through the recursive stack call and finally we will return true here if we did find a word that has this prefix else we would just be returning false so now let's run this code see if i made any mistakes okay looks like indentation is out of line oh yeah it is i think it's here actually yeah it's there let's run it one more time perfect let's try some more test cases actually there's only one so let's just submit and it gets accepted perfect so hopefully you guys are able to understand what a try tree is now and you guys know how to implement this very important methods which is inserting searching and starts with for most tribe problems the one they're gonna be using most often is the inserting and property this starts with for most problems i've done that does require try there's a whole bunch of times where i do need to run this dfs given a certain prefix and of course every single time i'm doing a try i need to first insert the word into my try uh and then compared search comparing search to these other two methods it's the comparing search to the others to these other two methods it's the one that i've implemented the least because of course for searching uh you could just adds add all these words that you've inserted to your tree into a set and then just return true if word is inside that set of the words you've inserted but other than that hopefully you guys enjoyed if you did please leave a like and consider subscribing and thank you guys for watching
Implement Trie (Prefix Tree)
implement-trie-prefix-tree
A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. Implement the Trie class: * `Trie()` Initializes the trie object. * `void insert(String word)` Inserts the string `word` into the trie. * `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise. * `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise. **Example 1:** **Input** \[ "Trie ", "insert ", "search ", "search ", "startsWith ", "insert ", "search "\] \[\[\], \[ "apple "\], \[ "apple "\], \[ "app "\], \[ "app "\], \[ "app "\], \[ "app "\]\] **Output** \[null, null, true, false, true, null, true\] **Explanation** Trie trie = new Trie(); trie.insert( "apple "); trie.search( "apple "); // return True trie.search( "app "); // return False trie.startsWith( "app "); // return True trie.insert( "app "); trie.search( "app "); // return True **Constraints:** * `1 <= word.length, prefix.length <= 2000` * `word` and `prefix` consist only of lowercase English letters. * At most `3 * 104` calls **in total** will be made to `insert`, `search`, and `startsWith`.
null
Hash Table,String,Design,Trie
Medium
211,642,648,676,1433,1949
404
hello everyone welcome back to the channel so friends in this particular video we'll be solving this problem that is some of left leaves so friends what we are given is we are given the root of a binary tree and we have to return the sum of all left leaves and Friends Leaf is a note with no children so this is the example that we are given and these are the leaf node 9 15 and 7. basically these are the nodes which do not have any children but friends the question is that we have to return the sum of left Leaf node and left Leaf nodes are 9 and 15. this is the right node so hence the answer is 24 so friends uh let's understand the dry run first let's understand the logic how we are going to proceed with this particular question and then we will do the coding so friends let's try to understand how we are going to solve this particular ly so friends we have to simplify in the sum of letters okay that we know so over here we have two left clips that are 9 and 15. so the answer should be 24. the resultant should be 24. and friends the idea behind solving this question will be level order traversal so in my previous video I have also discussed that we can solve the level order traversal using Q so this is going to be our Q okay so what can we do so what we are going to do we are first going to enqueue the node this root node into our queue simple now what we are going to do we are going to check if Q dot length is greater than 0 or not r q dot length is greater than 0 then what we are going to do is we are going to Simply DQ this particular node that is 3 and then we are going to Simply go for two cases that is the left and one is right so friends in right case we are going to Simply check if write exist then simply Q do the Q dot push and simply push the Roots value basically write notes value but so friends for left node we have two cases uh that is basically one it is that it is the leaf node yes or not so friends one will be that it is not a leaf node another will be that it is a leaf node so if it is a leaf node sorry if it is not a leaf node then what we are going to do we are going to Simply make a q dot push and left node dot value we are going to Simply encute into the queue but if it is a leaf node then what we are going to do we are not going to enqueue it but we are going to Simply do sum equals sum plus its value got it so now what will happen first we had this three so what we have done we have simply checked if Q dot length exists or not and Q dot length is greater than 0 then what we are going to do we have simply decued it so when we have decode it we have simply got this three now we have checked for its left node and the left node is 9 which is a leaf node so what we are going to do we are simply going to update our sum to 9 and we are not going to push it but if our tree would be something like this let's suppose any other value over here like eight so what would be the result is then we will be doing something like this we would have pushed 9 to the Q but right now the scenario is different so we are not going to push 9 into the queue so friends till now we have our sum as nine now what we're going to do uh the left node is processed for three now we are going to process Its Right node which is 20. and friends I have simply told you that for right node we simply have to push it we simply need to enqueue it into the queue so we are going to Simply in Cube 20 into the queue now again we have to run the function from the beginning we will check whether the Q dot size exists or not yes Q dot length exists then once again we are going to DQ it now another node that we have is 20. what we have is 20. now again we are going to go for its left and right now again for its left node we will be seeing basically if it is a leaf node or not and over here yes it is a leaf node so what we are going to do we will be running this particular case and now sum will become 24 9 plus 15 24. now what will happen left iteration is finished now we are going to go for right iteration for 20. so the right node of 27 so what we are going to do we are going to Simply enqueue the right node got it and now what we will be happening once more entire function will run for 7 and we are going to DQ 7 and we are going to check for its left and right node and friends um it is a right Leaf basically and its left is also null and right is also none so nothing is going to be enqueued into the queue basically so now the cues length is 0 basically the length has become 0 now so our function will end over here and final result that we will be getting is 24. so friends this will be the logic that we are going to apply while coding we are simply going to take one queue and we are simply going to enqueue the node root node first and after increasing the root node we will be checking for the left and right node if it is right node we are simply going to push it push the value of the right node but if it is a left Leaf node basically if it is a left node then what we are going to do for left node we are going to run these two iterations basically these two conditions in which we will check if it is a leaf node then we are going to add this particular value to the sum or else we are going to Simply push it in queue it into the queue so friends now let's proceed to code friends welcome back I hope uh the I hope the logic that we have like just seen in the Whiteboard I hope it is clear to you all now let's do the same in coding so friends the logic that we have discussed was of level order traversal so let's try to do the let's try to mimic that particular pseudo code over here also so what we are going to need is we are going to Simply need a queue and in JavaScript we can mimic the queue with the help of array only click edit itself now what we are going to do we are going to we have simply like taken this queue and simply encute the root into the queue now what we are going to do is we are going to Simply take one variable that will be the sum to store the sum and now we are going to Simply check while Q dot length is greater than 0. now we are going to DQ the node that is in the queue and how we are going to do is using Q dot shift and now we are going to check for its left and right node if node dot left exists and over here if node.right exists node.right exists node.right exists so friends if node.left exists we have so friends if node.left exists we have so friends if node.left exists we have two cases to check basically if that particular left node is a leaf node or not so first let's check if it is a leaf node or not so friends right now we are standing over here this is the three that we have decued from the queue so right now we are standing over here so what we are going to do we have to check this particular node from here so how we are going to check it using node.left check it using node.left check it using node.left and we have to check if it is a leaf node or not so we are going to check it using IF node.left dot left is null and using IF node.left dot left is null and using IF node.left dot left is null and node dot left dot right is null so if node dot left does not exist and if node dot left dot right does not exist it means that it is a leaf node and we are going to Simply add it to the counter some counter so dot left dot well else it means that it is not a leaf node then we are going to Simply enqueue it into the Cube and Friends similarly for root like node dot right we are going to Simply enqueue it into the queue and finally over here what we are going to do is simply return the sum let's see if it runs or not uh friends it shows time limit exceeded actually there is one small issue over here we have to address node not because we have taken this root node out in this inside this node so we have to actually there is a difference so we have to correct this variable uh now let's try once more cool so friends as we can now see over here our first test case and second test case both of them are passed let's try submitting it cool so friends our answer has been accepted once again let's try to understand the code what we have done we have simply written the logic of level order traversal that is using Q we have Travers it level uh by 11 like first level second level third level we have simply enqueued the route into the queue then we have simply decoded inside this Loop where we are checking the queue length and we have and if it is a we are checking if it's left node exists then we are simply checking while standing over here that if it is a leaf node then simple add it to the some pointer some variable or else simply push it to the queue for the next iteration and for right node we do not need to find the sum of right nodes so what we are going to do we are simply going to push the right node to the cube and finally so friends uh this was the simple solution for this sum of left lifts problem and I hope I do hope that you have understood this particular code as well as the explanation that I tried to explain you earlier and friends if you have liked the content then please like share and subscribe to the channel thank you for watching we'll be meeting in the next video thank you
Sum of Left Leaves
sum-of-left-leaves
Given the `root` of a binary tree, return _the sum of all left leaves._ A **leaf** is a node with no children. A **left leaf** is a leaf that is the left child of another node. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** 24 **Explanation:** There are two left leaves in the binary tree, with values 9 and 15 respectively. **Example 2:** **Input:** root = \[1\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
562
and welcome back to the cracking vein YouTube channel today we're going to be solving lead code problem 562 longest line of consecutive ones in a matrix before we get into it I know you guys enjoy these Google questions you watch them the most so please leave a like and a comment on the video it really helps me out with the channel alright given an M by n binary Matrix return the length of the longest line of consecutive ones in the Matrix and this line could be horizontal vertical diagonal or anti-diagonal so if we have diagonal or anti-diagonal so if we have diagonal or anti-diagonal so if we have a basic example here let's look at all of the possible lines of ones we have right we have this line of ones we also have this line of Wands we have this one we could have this one and then this one right so we see that the longest one is obviously going to be four here because it's gonna be this one and just looking at this it's really simple to figure out how to do it but actually solving it is a bit more complex the way that we're actually going to do this is with a simple depth first search and what we're going to do is we're going to go from left to right over the array over our Matrix here row by row column by column and essentially the longest path starting at a given position is going to be what it's going to be one because obviously this is a one so we count it plus whatever the longest path up whatever the longest path to the left whatever the longest path here or here is right it doesn't matter which direction we go in it's going to be the maximum of basically paths right so we'll say one plus the maximum of all the paths right and where paths can basically be up down left and right or any of the diagonals right so we'll take the maximum of whatever that path length is and then we'll add one to it because our current element is a one and then that will be the longest path starting at that element and essentially um we will just keep track of whatever the largest value we've seen and at the end we'll have our maximum and you'll notice that you know let's kind of erase all of this and you're gonna see kind of a recursive structure here obviously it's a depth first search so when we do this one right we're gonna need to check the path here which is also going to need to check the path here and here so there's going to be a lot of duplicate um path checking which is why we want to use a memoization dict to actually keep track of um items that way when we get here we can actually check is it inside of our dictionary if it is then we're good to go we can just yank it and pull it out and use that value otherwise we have to compute it but then we'll just store it in the memo dictionary so this is basically just a simple depth first search with memoization now that we have the general intuition of how we want to do it coding it is relatively simple so let's go now to the code editor and actually type this up we're back in the code editor let's write this up the first thing that I want to do is actually Define a variable which is going to keep track of all eight directions remember we can move uh in eight directions up down left right and we can go to each of the four diagonals so let's actually Define a variable to keep track of that for us because we're going to need it for the solution so we're going to say self.directions we're going to say self.directions we're going to say self.directions we're actually going to use a dictionary here and what we're going to do is we're going to store the direction and we're also going to store how we actually move inside the Matrix so if we're going up we're going to go uh we're gonna the column uh sorry the row will decrease by one and the column will stay the same when we go down the row increases by one and the column stays the same when we go left oops when we go left the row stays the same and the column decreases by one when we go right um the car the row stays the same the column increases by one and then we can also go up into the right which is that diagonal which is going to be -11 we can diagonal which is going to be -11 we can diagonal which is going to be -11 we can go up into the left we can which will be minus one we can go down into the left which will be 1 minus one and then the final one is down into the right which will be whoops this should be a colon here down into the right which should be what uh one comma one so that's our directions dictionary and we're going to use this later you'll see why we typed it out it's actually going to make our code a lot cleaner when we actually do the DFS function but for now let's just go forward so we're gonna have a self dot memo because remember we want to use computations that we've already done to avoid us having to recalculate things because that would increase our time complexity a lot and we also want a variable to keep track of our result which is just going to be zero in the beginning now what we need to do is we need to go row by row column by column and then for each basically tile in our Matrix we need to calculate our results so we're going to say four row in range Len matte and actually uh I'm just going to call it Matrix because the solution I have that I typed up actually used Matrix so it's fine uh whatever you guys can just okay I'll just use matte for to keep it simple for you guys um we're going to say four column in range Lan matte zero um what we want to do now is if this current tile is a one so we're going to say if Matrix uh row call and remember it's either a zero or one so if this exists then it must be a one uh and then we want to go in all four directions and remember that we can't change direction Midway so the direction that we actually start is the direction that we need to keep going uh for this to work we can't just go left and then decide actually I want to go to the diagonal now and then I want to go left I want to so we pick a direction and we go all the way as far as we can and then we'll aggregate basically the maximum of going in all the directions and whatever is the best direction to go in uh from our point that will be actually the best solution we want to do here so we're going to say four uh Direction uh in self.directions and remember if uh in self.directions and remember if uh in self.directions and remember if you do for something in a um dictionary it will actually give you the keys um so that's why we're able to just do direction we don't actually have to call Dot Keys here uh we can actually just access them directly by with a for Loop so what we want to do now is we want to sell your result is going to be the maximum of whatever the current best result is and whatever calling self.dfs result is and whatever calling self.dfs result is and whatever calling self.dfs on this Matrix um and I call that Matrix here uh Matt we're gonna pass in our current row our current column and we're also going to pass the direction that we're going in because we need to keep track of that once this finishes all we need to do is simply return our result and we are good to go so now let's actually Define the DFS function uh so DFS what does it take it's going to take a matrix it's going to take a row a column and a Direction what we want to do now uh the first thing we want to do is actually check have we seen uh this row column Direction combination before if we have then we can reuse the result so we're going to say if row call Direction is actually in self um dot memo that we want to return self.memo of row call and Direction cool self.memo of row call and Direction cool self.memo of row call and Direction cool so that's that now what we want to do is we want to initialize our basically our memo dictionary here um how can I give myself some more space okay perfect self dot memo and we're going to say row column Direction and this is initially going to be set to zero now we're going to check whether or not we're actually within the bounds of our array here so we want to make sure that uh one we haven't actually left the boundary of the array and two we're actually at a one because if we're at a zero then there's obviously nothing for us to do we should just return zero which is what we've initialized uh this coordinate to be so we're going to essentially say uh let's check the balance so if our row is within the bounds and the way we do this is if it's um greater than or equal to zero and less than the length of Matrix and our column has to be within the bounds which means it's greater than or equal to zero and less than the length of Matrix zero and we also want to check that our current position so Matrix row column uh basically equals to A one so as long as it's non-zero we're good to go because it's non-zero we're good to go because it's non-zero we're good to go because there's only zeros and ones in our array now what we want to do is we want to figure out uh how we need to change our row and column position um based on you know the new direction we're going so we're going to say the row increment and the column increment is going to equal self.directions of is going to equal self.directions of is going to equal self.directions of whatever our direction is so this is the reason why we actually use a dictionary so we can use the key uh to actually get the increment so this will be the row change and this will be the column change that we want to do so as you can see we can actually clean it up here we don't need an if statement for every single direction we can actually just pull it out of the dictionary and it makes our lives easier and this is much cleaner so now what we want to do is we want to say that self.memo of row is we want to say that self.memo of row is we want to say that self.memo of row call um direction is going to equal 1 plus whatever calling DFS on Matrix row plus the row increment column plus the column increment and the direction will be and we do one plus because remember our current item we just figured out uh based on this statement here is a one so in the worst case it's at least one here so we need to do one plus whatever the best path going in the direction that we're going uh will give us so that is the answer for that one so the last thing we want to do is simply return self.memo of row call and direction self.memo of row call and direction self.memo of row call and direction and we are good to go so that is actually it let's now run this make sure that I make any stupid syntax mistakes take I actually wrote and here it should actually just be less than I don't know what the hell I was thinking anyway now that's there uh we should be able to run this without issues yep and now we can submit it that is a pretty funny mistake but it happens I'm only human um now when we do it okay cool accepted so that is nice let us now think about the time and space complexity here so obviously for the time complexity we have to Traverse the entire Matrix uh and we're going to have to do it in multiple directions uh so you know the time complexity here is going to be o of M times n uh where m equals uh number of rows n equals uh number of columns so the amount of work we have to do is basically just bounded by how big our array is here so that is that uh space complexity wise as you'll notice we don't Define any extra space I mean we have the self.directions but this is a have the self.directions but this is a have the self.directions but this is a constant space allocation because we know up front that there's only going to be eight keys so that doesn't really count but uh our space complexity here is actually going to be Big O of M times n uh because we have to account for um the recursive stack space so recursive uh stack frames uh from the DFS so yeah even though um actually no what am I talking about um it's Big O of M times n because we have the memo dictionary sorry I'm off of it today but yeah um obviously self.memo could potentially um obviously self.memo could potentially um obviously self.memo could potentially store a value for every single tile in the um in The Matrix so for that reason it's also going to be a big O of M times n obviously there's a few multipliers here in terms of like the constant since we have eight directions that we need to keep track of so technically it would be like times eight but because we don't care about constants asymptotically uh it's just going to be Big O of M times n so yeah that is how you solve the question um yeah just make sure you don't make that stupid little syntax mistake here um and make sure you actually count the so soft top memo Dix when you talk about your space complexity but like I said I'm only human sometimes I make mistakes it's fine we caught the mistake it's no big deal so that is how you solve this question if you enjoyed this 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 if you're interested in joining a Discord Community where we talk about all things Fang things like interview prep systems design uh you can have your resume reviewed by me you can ask for referrals by other community members if that sounds something interesting to you then join the Discord I'll leave a link in the description below and I hope to see you there otherwise thanks for watching and I'll see you in the next one
Longest Line of Consecutive One in Matrix
longest-line-of-consecutive-one-in-matrix
Given an `m x n` binary matrix `mat`, return _the length of the longest line of consecutive one in the matrix_. The line could be horizontal, vertical, diagonal, or anti-diagonal. **Example 1:** **Input:** mat = \[\[0,1,1,0\],\[0,1,1,0\],\[0,0,0,1\]\] **Output:** 3 **Example 2:** **Input:** mat = \[\[1,1,1,1\],\[0,1,1,0\],\[0,0,0,1\]\] **Output:** 4 **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 104` * `1 <= m * n <= 104` * `mat[i][j]` is either `0` or `1`.
One solution is to count ones in each direction separately and find the longest line. Don't you think it will take too much lines of code? Is it possible to use some extra space to make the solution simple? Can we use dynamic programming to make use of intermediate results? Think of a 3D array which can be used to store the longest line obtained so far for each direction.
Array,Dynamic Programming,Matrix
Medium
null
771
hey guys welcome back to my channel and i'm back again with another really interesting coding interview question video today we are going to solve question number 771 jewels and stones in late code 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 and coding related videos let's get started with the problem statement now so basically guys we are given two strings one string is called as dwells and represents the type of stones which are jewel stones and another is called as stones which represents all the stones that we have okay so basically there is a bigger string stones which is having all the stones and gels is having only gel stones and we want to find out how many stones inside the stone string are actually gel stones okay we have to take consideration in the part that all the letters in gels string iron and stone string are case sensitive so for example if i say that just is having small a then small a is a gel and if gel is also having a capital a then a capital a is a differential okay so uh the letters okay is uh sensitive we have to take that into consideration so if we see the first example we have got two different jewels one is a small a and another is a capital a and the stone string has one small a and two capital e so that's why the stone string is having three dual stones and the output is three okay uh another example here you can see the jewels is having small z as the jewel but the stones are only having capital z so that's why the answer is zero uh both the strings have length ranging from one to fifty both only contains english letters and all the characters of gels are already unique okay so that's the problem see guys and let's get started with the solution now so for the solution of this problem we are going to use the approach of a hashmap okay so we are going to create a hash map of a key value pair in which the key is going to be the gel uh character okay and the value is going to be the number of occurrences of that gel character in stones string okay in the end we are just going to sum all the number of occurrences and simply return the output okay so i hope the approach is clear to you guys and now let's quickly jump to the solution part so as said before first we are going to create a hash map so this hash map is of character and integer so map is equals to hash map and yeah there we go now we have created our map so now i'm going to run a loop from integer i to 0 to i less than gels dot length and i plus and i am just going to store all the gels uh in my map so map dot put gels dot care at i and initially the number of occurrence for each jewel is going to be zero now let's run another loop this time we are going to traverse the stones string so i zero to stones dot length we are going to check if map dot contains key so if map has uh the stone character that means if the stone character is hull then we are just going to increment the number of occurrences so map dot put stones dot care at i map dot get stones dot care at i plus one okay otherwise if the map doesn't contain that uh stone character it means the stone character was not a jewel so he will simply implement and go to the next character finally let's uh initialize our count to zero and for integer uh for integer occurrences so for each occurrence of map dot values that means for all the occurrences of all the jewels i am just going to increment the count value so count becomes equals to count plus occurrence and finally return the count so let's run this code guys let's see if this works and okay so we have got a compilation error here which is my bad so new hash map should have been there instead of hash map okay i'm so sorry guys there is another compilation error which is for my spelling and yes so now the solution is accepted it passes the example and hopefully it is going to pass all the other examples as well and there you go guys okay now let's talk about the time complexity so the time complexity for this solution is going to be order of n because we are going through the 12 string and the stone string only once considering both of them are of length n you can see that the time complexity is order of n another thing is the space complexity so actually because we are storing the entire dual array in our map so the space complexity also becomes equals to order of n um i'm sure there may be other ways to do the solution uh but that's what i think work for me uh so yes uh obviously the solution is a bit of memory heavy because we have a space complexity of order of n and a time from next to order of n as well okay so that was the video guys i hope you guys like this solution and if you have then please do not forget to hit the like button and share the solution with your friends of course if you have further alternative solutions to this question please write down in the comment section below so that everyone can benefit from them apart from them any other suggestions i are also welcome and uh also guys please do not forget to subscribe to my channel and hit the bell icon for future notifications on more such videos i make your videos every day from monday to friday so i'll see you guys in the next video until then take care and bye
Jewels and Stones
encode-n-ary-tree-to-binary-tree
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so `"a "` is considered a different type of stone from `"A "`. **Example 1:** **Input:** jewels = "aA", stones = "aAAbbbb" **Output:** 3 **Example 2:** **Input:** jewels = "z", stones = "ZZ" **Output:** 0 **Constraints:** * `1 <= jewels.length, stones.length <= 50` * `jewels` and `stones` consist of only English letters. * All the characters of `jewels` are **unique**.
null
Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
Hard
765
190
hey everyone welcome back and let's write some more neat code today so today let's solve the problem reverse bits and this happens to be another problem from the blind 75 list or list of common leak code problems that we've been tracking in this spreadsheet we have a solution for the vast majority of them and i'll be doing a few more of the binary questions the one today we'll be doing is this one reverse bits so this is a good problem to kind of go over and learn or refresh yourself on the bit manipulation operations so we're given a 32-bit unsigned integer and basically we 32-bit unsigned integer and basically we 32-bit unsigned integer and basically we want to reverse all of the bits of this integer so like in this example this is the integer represented in binary of course we might not be given the integer in binary you know that we might be given the integer 4 which in binary we know it looks like this and then we'd want to reverse all of the bits for it so basically we would you know the reversal is going to look something like this right and then we want to return that reversed integer of course we'll be returning a one value so let's say this is the 32-bit integer and let's just say is the 32-bit integer and let's just say is the 32-bit integer and let's just say it's four just because we don't want to do a super long binary integer like this there are many ways to kind of do this problem right suppose we declare an output variable for result and this is where we put the last bit the 31st bit and then over here is where we put the zeroth bit right so we have 32 bits in the output initially we'll just set all of these to zero right so we want to go bit by bit in the input right we'll start at the ones bit we want to get what is over here if it's a zero or if it's a one and then we want to take it and then put it over here in this case it's a zero so we're just going to put a zero over here right basically we're reversing right we're taking the bit from here putting it in this spot right just in reverse order pretty much like we would do with reversing a string next we're gonna go to this one put it in the next spot so we'll have another zero here and then we'll take a look at this one put it in the next spot so we'll have a one here and then since the remaining of all of these are zeros then we're just gonna have zero uh in the entirety of this so uh obviously before when i showed us just reversing these four we ended up getting an output of one but you can see when we actually do it with 32 bits the result changes right so and they specifically tell us this is just a 32-bit integer so this is going to be a 32-bit integer so this is going to be a 32-bit integer so this is going to be a pretty large integer and we're this is what we're going to end up returning right so it's pretty straightforward to understand what exactly we're doing at least with the solution that i'm showing you now the question is how can we actually do these operations for example how can we go bit by bit get the first bit get the next bit all the way until we get to the end right how can we go and get each bit well one way in binary is to just take uh this bit right and it with a one the and operation right logic and what we're saying is if since this is a zero right if we take zero and it with one we get the output to that is going to be zero right which makes sense because we want to know if this is a zero or a one so if we end it with a one we'll get zero if this value is a zero that's exactly what we want if this value is a one and we end it with a one then we get one right which is good because if this is a one then we want to get a one in the output so that's the operation we're going to do logic and to figure out what the bit is now that's easy in the case we're just looking at the ones place over here but what if we want to look at this next spot we want to look at the uh two's place right and then what if we want to look in this spot etc how are we going to do that well instead of taking this input value and then ending it with a one we're going to end it with a one shifted to the left each time we you know move a different spot in the input right how can we shift a one to the left that's also another binary operation so for example if we had something like zero one and then we do the shift operation to the left this is a bit shift operation if we shift it to the left all what it does is it shifts all of the bits to the left by one and it replaces the one spot with a zero so in the output we'll get this when we shift this by one we'll get this we'll have shifted the bit to the left by one and notice how if we have a one over here and then a zero over here and then we have zeros all the way for the remaining of it when we get the output value it's also going to be a 32-bit integer right also going to be a 32-bit integer right also going to be a 32-bit integer right but this is the only spot we're gonna care about because the rest of the spots are gonna be zero by default because if we and zero with anything else we're gonna get a zero in the output whether you know we have a one over here or not if we and these together we're gonna get a zero in the output okay so that covers how we're gonna get each of these bits now how are we going to put them in the output remember how initially we had a result that was just filled with zeros right and we're going to start at the beginning take every you know if we have a one here we want to insert this one over here if it's a zero over here then we just want to leave the output as a zero and then we want to move to the next spot to the right and do the exact same thing so we're going to follow a similar pattern here if we had a 1 we would take the 1 shift it to the left by 31 right because that's going to be the spot all the way to the left we're going to take this shift it to the left by 31 so then we'll have a suppose a 1 here and then 0 what we want to do in this case is not logic and but we want to do logic or when we're trying to figure out what to replace it with so for example if we had a 0 here we would want to replace this with a 1. it works because we take 0 or it logic or it with 1 we get a 1. if we take 0 logic or it with a 0 we get a 0. so if we had instead of having a 1 here if we just had a 0 here we wouldn't want to replace this we won't want to leave it as a 0. so that's what logic or can accomplish for us and similar to the previous example if we had something like this and we were trying to logic or this right we would want to put this one in this spot we don't want to get rid of this one right suppose we had already put a 1 over here we don't want to get rid of it so notice how if we take this logic or it with this we will end up changing this bit this will be changed to a one but this bit will stay the same which is what we want to do because if we're gonna have a zero here and we're gonna have zeros in every other position the other remaining bits are not going to end up getting changed if they are ones they're gonna remain as ones if they're zeros they're gonna remain as zeros so those are some kind of basics about bit operations logic and logic or bit shifting and that's kind of all you need to be able to solve this problem in the simplest way so now i think we are ready to dive into the code and it's going to be a little bit shorter than you might expect let's declare that result variable that i said so it's going to be a 0 meaning all 32 bits of it are going to be initialized as 0 and we're going to go through every single bit in the input end so i'm going to say for i in range 32 because we know it's going to be up to 32. i think we could change the logic of this while n is you know non-zero and we could you know non-zero and we could you know non-zero and we could continuously update n i'm just going to do it this kind of simple way so remember the first thing we want to do is we want to get the i th bit of n so how can we do that well remember we were going to take n and it with 1 to get the i bit but if we just end it with 1 every single time we're only going to get the first bit right we want to get the i bit so instead of ending it with one well we can take n shift it to the right by i don't think that's what i said in the drawing picture i thought i think i said we're gonna take the ones a bit and then shift it to the left but if we actually take n shift it all the way to the right then in n we will have the target bit that we're looking for and it will be in the one spot so then we can just take this and end it with one and then we'll get the result bit that we're looking for in the ones spot so this bit will be either one or it will be zero and then we want to logic or it with the output to put that bit in the output how can we do that is it going to be enough to just say result logic or the bit no because if we do it like this we're only going to be updating the one spot of this result but we want to be updating it in the reverse order we want to start at the largest bit and then work our way down how can we do that well we have this i variable right it's going to go from 0 to 31. so how about we do this we shift our bit to the right by 31 minus i so on the first iteration of the loop we will be getting the first bit from n and putting it in the 31 spot of the result and the next iteration will be doing the opposite will be getting the bit in index 1 from n and putting it in index 30 in the output so then we're going to keep doing that and this is the operation we're doing and we want to set the result equal to the result of this logic or operation and that is the entire code once we're done with that we can go ahead and return the result so this is the simplest way to do it is constant time big o of one because we're guaranteed that there's going to be 32 bits so the solution is not going to scale regardless of whatever the input n is as long as it's 32 bits and where you know the memory we're using as well is just a single variable right so this is just an o of one time and space solution so i hope that this was helpful i hope it taught you a little bit about binary operations if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
Reverse Bits
reverse-bits
Reverse bits of a given 32 bits unsigned integer. **Note:** * Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 2** above, the input represents the signed integer `-3` and the output represents the signed integer `-1073741825`. **Example 1:** **Input:** n = 00000010100101000001111010011100 **Output:** 964176192 (00111001011110000010100101000000) **Explanation:** The input binary string **00000010100101000001111010011100** represents the unsigned integer 43261596, so return 964176192 which its binary representation is **00111001011110000010100101000000**. **Example 2:** **Input:** n = 11111111111111111111111111111101 **Output:** 3221225471 (10111111111111111111111111111111) **Explanation:** The input binary string **11111111111111111111111111111101** represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is **10111111111111111111111111111111**. **Constraints:** * The input must be a **binary string** of length `32` **Follow up:** If this function is called many times, how would you optimize it?
null
Divide and Conquer,Bit Manipulation
Easy
7,191,2238
1,643
hey everybody this is larry this is me going with q4 of the recently code contest uh 213 cave smartest instructions so hit the like button to subscribe and join me in discord so i actually end up taking a really long time for this problem mostly due to stupidness um a couple of times i'm gonna explain it i also wanna explain the problem but know that i usually explain how my thought process goes because i think that's more interesting to learn if not that's okay you know you do you but um so this is actually to be honest this is a very classic textbook question uh which is why i feel really bad for taking so long i end up talking about 30 35 minutes during the contest and about 25 to 30 minutes of it was just debugging because i was watching it a little bit um because i knew it so i was rushing to solve it and then i just had off by once everywhere and as soon as i kind of forced myself to slow it down and took half an hour for me to do it first i just slowed down ask myself what every step of the things i'm trying to do um i was able to finally get it um almost the point where i was surprised but basically so the first mistake i did to be honest was that uh i don't for some reason that i don't for some reason it said row plus column is less than 15 so i misread the constraints because i thought it was very quick right and if that was the case then at most it's gonna be two to the 15 which is fast enough so i was trying to do a before solution maybe that didn't make sense to be honest looking back but that's what i was trying to do because i also knew the other way of doing it but i was like okay this is easy this as fast as i end up getting a time limit exceeded for that because it actually is that independently they're 15. so together they're at most dirty so 30 um 30 choose 15 is considerably bigger right and you can plug into the calculator now 30 choose 15 is uh 155 million right uh where 15 true seven or something like that is way easier so i misread that a little bit that was the first mistake the second mistake basically is that i don't know i just like i said i had off by one's issue so that took a long time and i'm gonna explain how you solve problems like this these kind of problems i don't know if there's a good name for it maybe you could call it digit combinatorics or something like that because you're trying to solve the problem one digit at a time and the way that i would approach this and this works for any type of these problems where there's some ordering and you're supposed to return the caves more to something um and so forth generally speaking i mean at least for like more basic ones i mean i guess in theory it gets really complicated if people are asking for before competitive programming he thinks that's how you do it so the idea is okay you know let's say we start with the input right two three that means that there are three h's and two v's right and then now um and then now you have to ask yourself one digit and you are able to ask yourself one digit at a time is the first digit in h or is it in re right if this is an h if the first digit is an h that means that the rest of the digits they only have 2h and 2e if this is a read this has 3 h and 1 v left right straight forward makes sense still i didn't explain anything right this is just basic but uh and now for but now the first thing to notice is that h comes before the v right that's just how the way that we defined it lexographically i you know that and usually in a problem they will tell you how to order it but and then the question is okay how the question here becomes in how many ways are there you know in how many ways are there to um let's say you have to ask the inverse question right so is the first character h or v right well if the first character is h or let's ask the second question maybe if the first character is v how many um combinations did it skip over right so that's a good that's the question that i would ask and in this case if the first characters are we would skip over two some combination of two h and two e's right and the commentarically and this is you know um this is just basic combinatorics this is going to be a prerequisite for this problem for obvious reasons i'm not going to go explain this part very well uh or in detail but suffice to say that given four characters two of them are age two of the marie it's this four choose two ways of um so this skips four choose two uh combinations right so guy so then the so then now we look at the number k that we're given right the is k is the k in the f you know in the first you know that's is the first character hov right well the first character is h if k is in the first four choose two combinations otherwise k oh sorry the first character is v and k is you know between this right so we to put some numbers to it so this is from 0 to 4 choose 2 which is me putting in a calculator because i'm a little bit bad 6. still to six and this is from six to i don't know what to um how many numbers are there twelve ten so six to ten right um so that's kind of uh maybe i'm off by one but that's the general idea right i think this is actually similar to five and five to ten five to nine maybe um total right uh because i like to start from zero right so basically those are the numbers right um so we ask ourselves k how what is the answer for k uh and if k is from zero to five we have an h if the k is from five to nine we have a v right okay let's say the number is two just for whatever so now we know that the first character is h so then now you can kind of think about this recursively i mean i'm going to do it relatively but you got to think of it recursively in terms of smaller primes as well right well now what do we have well now our problem is we have two h2vs as we know and we ask ourselves uh what happened like what is this first character of this new thing right if the first character is v how many combinations does it skip over well it skips over three choose two combinations which is three i think uh so this is zero to two and then this is two three um uh this is three to three i guess you wanna put it more precisely right uh because this is only one combination inclusive so again uh i'm gonna cheat a little bit and shoot make this a three um just to kind of you know demonstrate a little bit the other way and then now we go okay k is equal to three it's the first character in h or it's the first character v right well uh well i mean i think now it should be yeah this makes sense hopefully uh and that it should be obvious that the first character is a v or the current characters that we if you want to call it that way because i we know that our first character is already h so now the next character the next first character is a v right so now what happens well if you want to put k inside this range of three to three which is i guess a terrible example but let's just pretend we i'm gonna make believe numbers let's say was three to eight and k is equal to five you know i'm making believe numbers you know in this case we know that k is between five is between three to eight right so then how do we define this recursively well we define this recursively by noticing five is the third character or the third number between three and eight so then we what we do is we do k minus three right and then now we're able to move forward one character again so that's kind of the idea behind this algorithm is that one character at a time you do the math on what happens if the character is the next character so that you know um you skip it i had a lot of off by once because i was just rushing it because i was like i knew this i know how to do this so let me just do it um so i had an off by one on the choosing um because i don't know it happens uh and also just to asking the right question as a result um so yeah so that's the short answer of how you would sell this problem let me know what you think and this is also how you would solve it in a general sense how you solve these digit combination problems is that um like and these could be anything right uh and you know there's some function somewhere that generates you know like i get some range and ranges could look crazy like this as well and you go okay it's the first stitch in h is the first digit of e and then you with the multiple digits you could even keep going and then as you can keep asking these questions usually what happens is that because you only need to do the number of digits per for the length of the thing so it usually ends up being uh o of alpha times n or something like that and in this case because we only have two digit it's just all of uh n is linear time and you know if you want to count combination and stuff like that you know you could add in the complexity as you need but yeah uh that's all i have in this farm unfortunately i you could watch me struggle a lot uh both on the misreading and did it the brute force way and then i tried to i don't know i just had an off by one because i was trying to do it really fast and i was trying to like be like i know i'm off by a little i'm off a little and then i didn't just like what i need to do and sometimes i know about this and sometimes it still happens is that i need to slow myself down and then really ask myself every step of the way what does this mean and you said and you uh at the end i finally did that and i was able to find yourself the problem i hope you enjoy kind of going through my thought process uh these type of farms come up randomly uh and usually to be honest i'm really good at these but today i just i think i just put too much pressure on myself and i rushed a little bit maybe and it happens uh hopefully i'll do better next time and for the rest of y'all you can watch me solve this live during the contest next and it's a long video so feel free to um fast forward as or like watch it on like 2x or something right anyway thanks for the support i will see y'all with my other head okay i'm pretty slow on that one but that's okay four people already finished wished hmm tape flexographically smaller thing hmm that's 15 choose seven this definition two three okay so next hmm so you have hmm turn away i'm going really slow to be honest yes what's up oops hmm that's not good oh it's off by one so okay now what to do this is very stupid i'm running slow you're too slow oh come on oh schnapps i misread this i miss what the fingers 15 okay still could have gotten this the other way but oh jesus wow people are really fast today um this is a standard problem i should notice but i'm just really dumb and slow it's very mathematical i just missed about the inputs as well oh and if this is h if it is we it is that's a thing f minus k oh man well that's not right hmm what am i doing really bad at these map once also why okay i have to slow down um this is the h because hmm i'm going to try the combination sapping i'm just doing a little bit wrong here this is zero let's see what this is going to be just hhh right that's good i'm doing really fully on this one so first someone like this my mouth has been bad you so that makes up the mess of x and y as well but that's fine should be the same my recurrence as well actually that's one this is three choose two if i choose two so hmm this is we like what does it mean sorry that means that we've done all the previous numbers i'm going to fix that three ages and that's okay maybe i don't even know what's expected right here to choose one oh man am i just missing a minus one there's something as simple as that because i think i meant something like that but really must be on the math girl did i just have it in the wrong order maybe oh look i still know okay so what am i doing well i'm so bad at math today you know what you're doing it's too so this is okay we're getting something still off by one somewhere but that's okay maybe just maybe more than just off by one but hmm what is this why am i wrong right so one two three four five six yeah right yeah okay that's fair is that the case for two okay so this is not it shouldn't even happen this is two so we know that first guy is h so we subtract what am i printing here now this is nope this is this how does this happen huh oh and then it's three it's only one case and which is zero right and that's true maybe i'm messing up that actually that's not the case hmm let's do we choose zero there's only one case left that's true but this is right here because there's only one case is that right thanks so i mix up the x and the y again but that's okay it's something it's not right the answer yeah do you subtract this by just x oh i'm gonna cry i'm going to cry we should also just be never be negative three right what does that mean that means that is that true no this should be five right so here are four characters left and music next door is following me and this one looks okay but this one's the one that's wrong three because it's my mac performing along hmm how does this even just finish sad things i've solved this before too but i'm just like that's why i'm like so close but not really substrate why i'm out i still think this is desperate what now it works was i just like being dumb somewhere i don't even know where i got it wrong anymore oops oh that's fine okay i mean uh thanks for watching everybody uh hit the like button to subscribe for enjoyment discord and let me know what you think about my explanation this farm every question you ask i'll get better at answering them in the future preemptively i'll see you later take care
Kth Smallest Instructions
number-of-nodes-in-the-sub-tree-with-the-same-label
Bob is standing at cell `(0, 0)`, and he wants to reach `destination`: `(row, column)`. He can only travel **right** and **down**. You are going to help Bob by providing **instructions** for him to reach `destination`. The **instructions** are represented as a string, where each character is either: * `'H'`, meaning move horizontally (go **right**), or * `'V'`, meaning move vertically (go **down**). Multiple **instructions** will lead Bob to `destination`. For example, if `destination` is `(2, 3)`, both `"HHHVV "` and `"HVHVH "` are valid **instructions**. However, Bob is very picky. Bob has a lucky number `k`, and he wants the `kth` **lexicographically smallest instructions** that will lead him to `destination`. `k` is **1-indexed**. Given an integer array `destination` and an integer `k`, return _the_ `kth` _**lexicographically smallest instructions** that will take Bob to_ `destination`. **Example 1:** **Input:** destination = \[2,3\], k = 1 **Output:** "HHHVV " **Explanation:** All the instructions that reach (2, 3) in lexicographic order are as follows: \[ "HHHVV ", "HHVHV ", "HHVVH ", "HVHHV ", "HVHVH ", "HVVHH ", "VHHHV ", "VHHVH ", "VHVHH ", "VVHHH "\]. **Example 2:** **Input:** destination = \[2,3\], k = 2 **Output:** "HHVHV " **Example 3:** **Input:** destination = \[2,3\], k = 3 **Output:** "HHVVH " **Constraints:** * `destination.length == 2` * `1 <= row, column <= 15` * `1 <= k <= nCr(row + column, row)`, where `nCr(a, b)` denotes `a` choose `b`​​​​​.
Start traversing the tree and each node should return a vector to its parent node. The vector should be of length 26 and have the count of all the labels in the sub-tree of this node.
Hash Table,Tree,Depth-First Search,Breadth-First Search,Counting
Medium
null
587
welcome to League of JavaScript Channel where we solve every single little question is in JavaScript today we have Vibe 87 erect defense this is a hard question so you're given a retreat which result contains an array with an x on my coordinator representing the location of a tree in the garden we'll ask to fence the entire Garden using the minimum like the Rope regarding the 12 fence if known if all the trees are enclosed return the coordinates of the trees are exactly located on the front perimeter now how do we solve this hard question and like many other harder questions this might be a bit more mathematical in this case it has to be it has to do with geometry um the numbers it has to really algorithms so first instinct maybe let's be greedy start at any given point yeah straight to go to the nearest neighbor whatever the length of the connection will be as small as you just keep doing and essential you would do a really algorithm and that actually wouldn't work because if you try to minimize the length of the Rope locally that maximizes in insertory maximizes the length globally um and part of that intuition is what comes to the actual geometry of it which I wouldn't explain detail but you understand that trying to make the smallest connections often lead us to some more rope overall that's essentially what we want to know and there's a number that appears a lot and you realize when you do smaller connections you're more likely to do connections which form an angle of greater than 180 degrees for example where to connect these three the angle like between this and this would be greater than 180 with some like 270 degrees in this case and we want to avoid angles aboard one above 180 degrees as much as humanly possible um we want everything to be convex and thankfully there are algorithms and formulas for that are well known uh so we are going to be using them um maybe if you're not familiar with this you may want to spend some time reading our convex hole which is basically what I'm gonna do um but if even if you're familiar you probably realize that doing this for an entire closed space or um it's likely to be very hard however with the more algorithm algorithmic part comps is we decide to break this problem into two which I've essentially arbitrarily to have a lower and upper part and in that way we are gonna go gonna significantly reduce the complexity of what we're actually doing and we're gonna be able to do this in linear time if we were to have the point sorted so we're gonna need to sort the points which is going to be logarithmic time mobile so let's do that first so we're gonna do trees that sword and we're going to use the following compiler function comparing functions are relatively evicted to the JavaScript but in this case we're going to do h0 which is b0 or A1 minus B1 so what am I doing here is this relatively simple we're doing this in ascending order first take into account the x-axis first take into account the x-axis first take into account the x-axis so in this case the first element it's definitely going to be this one because the value of x is one but when we get to x equal to we have three which are tied done that's when I or comparator kicks in and we use Y and we also do it in an ascending order so this will be first second and third in this case and as I mentioned we're gonna be sort of doing this in two parts are going to currently remind you but so we're gonna have a lower rate and an up array lower or whatever and to actually populate this arrays we are going to have a comparison function and it's going to call it compare and what do we need here we need three points actually to make a decision grab P1 B G P3 and essentially what we're going to do is given three points which two should be connected and essentially we are gonna check um where the pass value is positive negative or zero positive generally means a P1 and P2 connect P2 and B3 connect in negative cases and B1 B3 connect in zero and the way we set this up P1 and P3 should never connect um so we're going to use this operator of the structuring to do x one by one let's go to P1 and since we know P every single point is going to be another way that contains two points we can just assign it to two where I was like so that's where we go to P2 X3 Y3 is equal to B3 okay so far so good now we're gonna return and again this counts for the mathematical for other geometric intuition um and more essentially comparing the three points simultaneously and try to do way one side to the other and the way it's going to be positive negative for zero go let me do X3 plus X all right now that we have the comparison function and then we sorted which in a certain way I think it's a more complicated parts of this problem we have a very easy Road I have ourselves um great forage though we'll do the three of trees I said before it show up here in JavaScript and the first thing that we're going to do is do low the push three and we're also gonna do up the push tree this summary that we always want to do we're going to protect round three now we are gonna check what actually belongs by following the but using a while I'm gonna we do use two wire loops we do use develops because low and up must be done separately so load that length has to be greater than equal to two because we need always nearly three points and we're gonna have the current tree and we need a lisp two more in the array and you compare low lower than length minus two in this we're simply going to take the two elements are at the end and we do low the length minus one again last element and second to last element um we do the current tree and in this case we're going to check whether it's positive and if that's the case actually we're gonna do lower the pop and if this conditions whole to have a positive value I'm going to be removing those things um now we're going to do the same for upper um it's gonna look almost exactly the same with one caveat and that's gonna be we actually wanted to check whether it is negative and edit if that's the case um we're gonna pop other than that after we do all those things um meaning here we do not want anything that's negative and he here we do not want anything that's positive um as a result of this compare function now at the end of that we are gonna be returning a an array because we do have to return it an array of points and here's the way we're going to do it we're going to use the destruction operator with three points and we're going to be using a set just to make sure we do not repeat any values that may be in low and up at the same time because they might repeat in some cases and get the app that concatenate low essentially we're going to concatenate upper and lower um arrays we're going to create a set out of that finally we are going to create a newer array based over that and in this case the order shouldn't really matter yeah and the Order of the output is not really important um as you can see so you can just run this code and it's going to work for the sample test kit let's try submitting this code and it works it's quite a fast algorithm it runs in 110 milliseconds the faster than 60 percent of our submissions now let's think about space complexity is relatively simple it's going to have all band uh because in the worst case up and low going to be filled to the end meaning we have all the elements of trees and for time complexity although we do have a single four in each Loop um this actually is going to be o of M log n and this is because we're doing sorting and remember sorting in the best case scenario with the a good algorithm that's optimal usually takes of n log n and we're just going to assume the JavaScript algorithm it's good enough and of course even this while Loops which is simply turning again through low an app and we just assume that's not linear um yeah that's it for today thank you so much for watching don't forget to like And subscribe
Erect the Fence
erect-the-fence
You are given an array `trees` where `trees[i] = [xi, yi]` represents the location of a tree in the garden. Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if **all the trees are enclosed**. Return _the coordinates of trees that are exactly located on the fence perimeter_. You may return the answer in **any order**. **Example 1:** **Input:** trees = \[\[1,1\],\[2,2\],\[2,0\],\[2,4\],\[3,3\],\[4,2\]\] **Output:** \[\[1,1\],\[2,0\],\[4,2\],\[3,3\],\[2,4\]\] **Explanation:** All the trees will be on the perimeter of the fence except the tree at \[2, 2\], which will be inside the fence. **Example 2:** **Input:** trees = \[\[1,2\],\[2,2\],\[4,2\]\] **Output:** \[\[4,2\],\[2,2\],\[1,2\]\] **Explanation:** The fence forms a line that passes through all the trees. **Constraints:** * `1 <= trees.length <= 3000` * `trees[i].length == 2` * `0 <= xi, yi <= 100` * All the given positions are **unique**.
null
Array,Math,Geometry
Hard
2074
43
today we're gonna be working on lead code question number 43 multiply strings given two non-negative integers num1 and given two non-negative integers num1 and given two non-negative integers num1 and num2 represented as strings return the product of num1 and num2 uh you must not use any built-in bit integer library or use any built-in bit integer library or use any built-in bit integer library or convert the inputs to integer directly so in the example one num1 is equal to two num2 is equal to three the output is going to be equal to 6 because 2 multiplied by 3 is equal to 6 but we are not supposed to use like the bit conversion basically we are not going to be converting the string to an integer and then do the multiplication and in the example two we're gonna be saying that num1 is one two three num two is four five six we're gonna come up with a product so initially uh what we're gonna be doing is like we're gonna be saying that okay the result is gonna be uh like basically an array of characters but the length of them uh so basically it's going to be an array of integers in the beginning and the length of it is going to be an empty array all filled with zeros so and the length of it is going to be equal to the length of num1 plus length of num2 after that we're going to start reversing from the num ones right most value and then we're going to keep coming back to the most significant value similarly we're gonna take our j is gonna traverse the other number which is num2 we're gonna start from the least significant value and then we're gonna keep coming back uh up to index 0 for the second string so every single time what we're going to be saying is like the we're going to have the previous remainder initially that's equal to the result at that i plus j plus 1 uh this is the previous remainder initially it's going to be equal to 0 so after that we're going to be calculating the product which is going to be equal to the num1 of i multiplied by num2 of j plus the previous remainder so and then after that we just have to update the uh the value of the result once we have the product uh so one thing is like we're gonna call uh our constant digit which is gonna be equal to the product uh at that particular i uh actually sorry product and then it's gonna be equal to the modulus of 10 this is going to be the digit because if it is more than 10 we can't take it if it is less than 10 it's just going to be equal to the value the carry is going to be equal to the product divided by 10 but actually we have to take the floor of that value yeah because otherwise it's just going to make it we don't want the floating with the uh the floats or doubles which we need and the carrier to be an integer after that we're gonna update the result at i plus j plus one which is gonna be equal to the digit and uh the carry is gonna just be accumulated at the index i plus j of the result so once we have that we can just in the end uh the index is gonna be equal to zero basically this time we're just basically converting uh the integer array to a string but we also need to make sure that if there are if there is any zero uh like the at the beginning we wanna shift that basically we wanna uh remove those from the result we don't want any uh preceding zeros in the result in the end we're just gonna be converting this uh result onto a string and then just return it so if the if there is no product nothing is there we just return uh like an empty zero otherwise we just return the result.join result.join result.join basically converting the uh converting the integer array to a string let's see if it works for all the test cases yep and it passed all the test cases
Multiply Strings
multiply-strings
Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string. **Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly. **Example 1:** **Input:** num1 = "2", num2 = "3" **Output:** "6" **Example 2:** **Input:** num1 = "123", num2 = "456" **Output:** "56088" **Constraints:** * `1 <= num1.length, num2.length <= 200` * `num1` and `num2` consist of digits only. * Both `num1` and `num2` do not contain any leading zero, except the number `0` itself.
null
Math,String,Simulation
Medium
2,66,67,415
103
hey guys welcome or welcome back to my YouTube channel so today we are going to discuss another problem is binary tree zigzag level order traversal so in this problem we are given root of binary tree and we need to return the zigzag level order traversal so it's level order traversal so that means it's breadth first search and we it should be zigzag so we'll see what's exact mean here uh of its node values that is from left to right and then from right to left okay and uh similarly for the next so see first of all let's say this is the tree which is given to us binary tree so what is a zigzag level order zig zag level order traversal so we all know what is level auditive also so level order traversal is going level by level so if we have to see level order traversal of this binary tree it would be something like this three then it will be 9 20 because second level first node is nine and then 20 so 9 20 and then after that the next level so here there is nothing here it's 15 and 7 so then it will be 15 and 7. so this is your level order diversity but here in this problem we have one additional thing which is zigzag so what is zigzag means that for this binary tree zigzag will be first level as such Next Level we will not start from left to right that is earlier we have taken nine node first and then 20 right now the next level will be right to left so basically it will be zigzag so first one will be left to right then it will be right to left and then again it will be left to right then right to left so similarly it's zigzag alternate so here it will be 20 that is right to left right direction to left so 20 and 9. then for the next level it will be left to right that is 15 7. okay so this is what level order a zigzag level order traversal is we have to do so whenever you find a problem right whenever you see a problem see what currently you know and then compare what additional things you have to do so if let's say this problem was simple level order traversal we all know how we can do level order traversal so if you are not clear just check out my Channel first for level Auto traversal so we know level order traversal right okay now here one additional thing which is zigzag that is for example let me draw the tree again so if the tree is 3 9 1 second 3 9 20 15 and 7. so if you have to find zigzag level order reversal it will be something like 3 29 and then 15 7. okay simple level order traversal will be 3 9 20. 15 7. okay so see the output how the output is we have to return each level in a vector like in an array and there is a main output array which is this one right which is this outer array so what we will do right we will be doing Simple level order traversal only how we do it uh like in traditional way but we will be storing the alternate level right let's say this is the alternate level this alternate level which we will be storing we will store it in a in right to left way because we want it in right to left right let's see how we can do that so let me quickly draw the tree again see first level this first level will be right left to right and the second level will be right to left then this will be left to right so I will take a variable which will tell me in which level I have to go left to right and in which level I have to go right to left so initially level will be zero value okay if it's zero value then it means that I will have to go left to right okay if it is one value then it means I have to go right to left okay so this variable will tell me in which format uh in which direction I have to go all right now let's do the traditional BFS that is breadth first search so in BFS we take a queue okay we take a cube this is our queue initially I will add the root of the binary tree in the queue that is first step is Q dot push the root of the binary tree the root so here 3 I have pushed when I say three I have pushed it means I have pushed the entire node not just the value of the node that is I have pushed the entire root not just the root value so just make sure don't get confused here we are going to be pushing the queue we push the entire node okay why we push the entire node because we afterwards we want the right and the left child also from that node so that's why we push the entire node not just the value all right awesome so this is the first root value which I have pushed in the queue now let's see what we will do so if you see the output guys output has the output array this in this outer area is the output array so here I will have a let's say output array which will store all the levels so this is your output array okay so now we will do the left uh we will do the level order traversal what are the steps of level order traversal level order or you can say BFS you can say anything right level order so here what we will do first of all we see the size of the queue what is the size of the queue size is one this is the first step second type step is we run a loop on the Queue size to get each of the nodes so for I uh is equal to 0 I less than this Q size I plus so basically we run a loop okay let me just do it like this okay then the third step is we will take the current node 3 we take the current this let's say this is the current node Uh current node three we will see and also if you see here for each level right for each level this is one level this is uh this is one level we need a separate area or vector or List anything so I will take a Vector in which I will be storing let's say this is my res result since initially level is zero initially I will check if the level is 0 that is if level is 0 it means I have to store the values in left to right way okay left to right so here this is my result a so here I will store this three in left to right you understand just wait for some time okay so here size was 1 and this Loop run one time only this Loop will run one time only and we got this result and we will store this in the output area because this is one of the one level this is one level so this output array will have one here three okay if you see the output we have this all right now let's also after this fourth step will be so you see here the step will be one second let me complete this so if level is zero we will let's say this is less of I rest of I we will store the current node will go in rest of I now let's see the fourth step is traditional BF so this is traditional leftward level order traversal just the extra step is this one this is the extra step which is we are doing okay for the zigzag so then it will be push the left child in the queue left of current that is current left and current right in the queue so currents left 3 is left is nine so we will push nine so when we will also pop this when we get its value right so we'll pop it from the queue here 9 will come and here 20 will come that is current site so this is one iteration and we got our first level okay and lastly fifth step is what we will do we will push this rest into output because we got one level rest into output okay so basically this is your fourth step this will be inside the loop for Loop this will be inside the for Loop and okay this is your third step push and fourth step is make the level as one basically alternate so we will make it alternate so if it's zero we will make it one if it's one if we will make it zero because for the next level it needs to be alternate so let's now let's see the next level it will be more clear just wait for some time it will be clear so see now the next level we will take we will see what is the size of the QQ size is now 2 so 2 will be queue size for Loop will run for two times because size Qs is two first current is what current is current value current this will be 9 current will be nine okay current will be 9 we will see if level is zero level is what now level will be changed to one okay now level is one so here there will be else if level is 0 is what we will do we will take a rest vector this will be a rest vector in this race Vector we will make this rest Vector of size Q size because these two nodes only will come here in this rest Vector but we still have to know the order because it will be from right to left right so this 0 1 so this current node right if level is 1 we will store in rest of Qs minus 1 minus the current I in this index we will store the current value that is C res Q size is what Q size is 2 is the queue size minus 1 minus the current index will be initially zero I will be 0 so 2 minus 1 that is rest of 1 we will store the current node which is 9. that is here right after that what we will do we will see push left of current push current left and current right so there is no currents left no currents right so nothing will be pushed in the queue okay now again Loop will run now I will become what I will become one initially I was Zero now it will become one current will be what current will be this node 20. and level is one only so it means in the rest of Q sizes 2 minus 1 minus index I which is 1 we will store the current value so that is rest of 2 minus 1 is 0 we will store current which is 20. so rest of 0 is here 20. so this is the new so see you will see this is from this is right to left order which we have stored in this stress vector now this for Loop is done now we'll go to third step we will push this rest into output so here output will have 20 comma 9 vector and level we will change again so level now will become zero okay level will be long become zero and I forgot one step sorry here after this for Loop we'll have to uh after this level step we have to also push the left is 15. and currents right is 7. okay now we will go to the next iteration so this whole thing like this whole level order traversal will continue until your queue is not empty that is all these steps right all these steps will go on until Q is not empty so if you see here Q is not empty as of now it's 15 and 7 there Q is not empty okay so now let's see the next step let's take the next step so here uh Cube size is what Q size is 2 there are two uh nodes then I will be initially zero it will run two times for i 0 and for i1 right now I is 0. current is 15. level is zero so it will be rest of I we will take a s vector initially of size 2 since Q size is also two so only two elements will go so same so this rest Vector you can make same size as Q skill size that is Qs this one okay so 0 and 1 here rest of 0 require 0 will current will store here 15 will come here and push left of 15 and right of 15 so that thing is there so nothing will be pushed this will be popped when we store here okay now again this Loop will run I will become 1 current will now become 7 we will pop 7 and current will be 7 level is still 0 so address of Iris of I means rest of 1 that is here 7 will get stored and push left and right of seven into the queue so 7 has no Left Right child so nothing will push and lastly third step push this race into output so this rest will be pushed here in the output array that is 15 comma 7 will be pushed and the level will come one okay now you will see the queue is empty Q has become mq is become M has become empty so it means that we are done with the level order we have traversed the binary tree level device and this is our output see 329 157 this is the output so I hope you understood the dry run just do these steps once yourself understand the algorithm it's same as level order traversal just the extra step which we are doing is this thing this step this if else uh sorry this if else part this one otherwise the rest of all the steps are same as level order errors so let's quickly see the code I hope you understood the diagram okay so what we are doing is this is the base key Edge case that if root is null that is there is no tree just return empty uh Vector uh then we are taking this Q which will be storing the node we have taken this output array which will be area of array a vector of vectors because this is outer vector and it has inner vectors then we'll just simply first of all push the queue push the root in the queue and level will be initially zero which we have taken early initially until this see until this queue is not empty we will take out the size of the queue which was IQ is then we will run the loop based on the size of the queue take the current node so we were taking the current node right and we were checking we'll also pop it from the queue and we'll check we were checking if level is zero rest of I is equal to current L else store the current value here and after that we were pushing the left and the right child into the queue so left and right child into the queue after the for Loop so after this for Loop what we were doing we were pushing the rest into the output so output array we will push the rest Vector so I have just this is a different terminal variable names and level we change it to alternate so here if level is 0 it will make it 1 because this is not right in a logical operator so if its level is zero it will make it one or if level is one it will make it zero that is not this is a not logical update okay so I hope you understood the problem and at last we will return the output so time complexity since it's simple level order traversal time complexity is O of n and space is also off in because we are using this extra Vector to show the output so I hope you found the video helpful if you found the video helpful please like it subscribe to my channel and share it with your friends who are preparing for placements thanks for watching bye
Binary Tree Zigzag Level Order Traversal
binary-tree-zigzag-level-order-traversal
Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[3\],\[20,9\],\[15,7\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-100 <= Node.val <= 100`
null
Tree,Breadth-First Search,Binary Tree
Medium
102
1,658
hey everybody this is larry this is day 11 of the june eco daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's problem i hope you enjoy the intro as much as i'm uh showing you the intro aruba is kind of fun so definitely check it out if you have a chance as you can see i'm just doing a lot of hiking and seeing the shoreline and just a lot of beautiful places anyway today's problem is 1658 minimum operations to reduce x to zero okay what does that mean so in one operation you can remove the left most or rightmost element from the array nums and subtract its y from x okay uh okay so basically it seems like you can only remove from the left or the right most right so um immediately i'm thinking about the first thing i think about is how is there a way i can do it brute force right um and the idea i mean of course obviously you can do before but not brute force in the sense that you're that brute but maybe brute force in a way that you're just checking every possible solution and here i think there is right the way that i'm thinking about it is that okay for example given this uh array here i'm trying to see okay let's say if i use one number from the left and i have one and we're trying to get x well now we're just trying to find a suffix array of okay looking at the suffix is there something that okay let's say x is equal to five let's say we have a prefix of one is still a four uh in the suffix right does that exist um let's say we have two is there three that exists and the answer is yes and of course in this case this takes um this takes uh what you may call it um this takes three moves so then you check it out right one three uh and then three is to go to three moves um and of course i actually skipped a step where you have no numbers from the left and you have two numbers from the right and that's five so that's uh two steps right stuff like that and you keep on checking so that's going to be my initial goal and then the second thing is that okay um and of course i'm jumping a little bit ahead in my mind to check the feasibility is that on the right side we can just have a lookup table right one thing that i'm going to check on is where what's the range of the number meaning if they're negative numbers it complicates things in terms of trying to minimize um but i think that should be actually given a minute let's take a look okay actually it's only positive numbers but even the negative numbers i think it's okay you can choose um how many numbers to use but there are some new ones uh i mean there are like a little uh just like one edge case depending on how you want to how you write the code of if they have overlap right can you see me yeah if they overlap then obviously you have to check for that but without negative numbers it's not possible to have an overlap um yeah right because uh wait is that true no i guess it is possible to have an overlap so you still have to check for it but you can also check it in an easier way because if there's an overlap that means that the total of nums is um bigger than x right so or smaller than x right then that means that it's not possible so okay so here we can maybe just write this up real quick if this is less than x then we return negative one because it's not possible um there are other ways to be not possible so that's not the only way but that's one way and that is the case where overlap would happen and if you think about it overlap happens when that means that the middle the overlap part is counted multiple times meaning that to get the x you have to count multiple times so that's what this case does um okay so now what i'm going to do is just have a suffix scene type thing um and it is kind of what it see looks like maybe so you can do a suffix array and then maybe do a binary search on it that's one way to do it um the way that i'm gonna do is just have a lookup table so this is a thing and yeah so can it have zero i guess it cannot have zero so i'm just looking good constrain zero is equal to zero right so if you need the number zero then you need zero from the suffix otherwise for x in nums uh reversed of this uh i guess we should use actually reversed um because i think that actually returns an iterator versus uh so that it's slightly more efficient if you know what i'm talking about if not that's fine too um so yeah current is equal to zero and then current we add x and then x is you go to um i guess back to enumerate this from one right yeah i think this is right um just checking for it off by one but i don't know and typos in general but yeah so zero three is one two uh five should be this is awkward oh i use okay this is why you check things uh that is a really silly mistake i actually did not i was confident about it but sometimes you could be confident and still wrong and actually for me many times but now just looks okay um so then now we can do for left right so in enumerate nums if uh okay so now we're looking at the prefix right so okay we have to do a few things press is equal to z um okay it's equal to sum infinity this is just a big number you can choose any best number it doesn't really matter um actually let's make this that because we can reuse it in a way you'll see later um yeah and then here we have to check um if suffix scene or if uh x is in suffix scene then best is equal to min of best suffix scene of x oh okay i'm gonna change this to target that's why i was trying that's why this feels a little awkward because i use x here as well and here because i don't know also that's just a terrible variable yeah anyway um yeah so if that means that using no numbers from the prefix and all the numbers that we can on the suffix this is the result otherwise i'd like to move this closer to the code so let's set it to go into zero uh x and then if so you know you could do the equation really quickly target is equal to some current plus some suffix so now target minus current is equal to some suffix that we're going to search for so then that's basically it right so uh if target minus current in suffix scene um best is then that means that we got look it up so suffix scene of target minus current plus uh i plus one right i suppose for the number uh i guess we could have started this on one as well actually uh basically the idea here is that this is not the i this is just the number of numbers we use from the left right so this is the numbers we use from the right the suffix and this is numbers we use from the left and now that we checked everything we can just return the answer oh we i lied because we didn't do negative one but also we're gonna fix that um if we did all that and best is still equal to infinity we return negative one i forgot to change that but i found out i also had a different type because we changed the random name uh okay that's one more test not just for one example okay that looks good let's give it a submit huh i found it in the past i got it well hopefully this time i don't get it wrong okay cool yes 802 day streak um cool uh and yeah in terms of time and spaces it's going to be linear time linear space coming from this suffix scene array um and time you know we just go through the loop once and twice uh and each of them we do a one lookup and not much more but yeah uh that's pretty much what i have i'm curious how what i did wrong previously oh maybe i misunderstood this one because i just wrote this in a really weird way um i don't know maybe check that video but uh but yeah anyway that's all i have for that one i don't think i have anything to learn but uh yeah stay good stay healthy took your mental health i'll see you later and take care bye
Minimum Operations to Reduce X to Zero
minimum-swaps-to-arrange-a-binary-grid
You are given an integer array `nums` and an integer `x`. In one operation, you can either remove the leftmost or the rightmost element from the array `nums` and subtract its value from `x`. Note that this **modifies** the array for future operations. Return _the **minimum number** of operations to reduce_ `x` _to **exactly**_ `0` _if it is possible__, otherwise, return_ `-1`. **Example 1:** **Input:** nums = \[1,1,4,2,3\], x = 5 **Output:** 2 **Explanation:** The optimal solution is to remove the last two elements to reduce x to zero. **Example 2:** **Input:** nums = \[5,6,7,8,9\], x = 4 **Output:** -1 **Example 3:** **Input:** nums = \[3,2,20,1,1,3\], x = 10 **Output:** 5 **Explanation:** The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 104` * `1 <= x <= 109`
For each row of the grid calculate the most right 1 in the grid in the array maxRight. To check if there exist answer, sort maxRight and check if maxRight[i] ≤ i for all possible i's. If there exist an answer, simulate the swaps.
Array,Greedy,Matrix
Medium
null
1,293
hello friends today life so shortest path in a grid with obstacles elimination given M times and grid wage there is either zero empty or one obstacle it one step you can move up down left or right thrown in the - an down left or right thrown in the - an down left or right thrown in the - an empty cell returned the minimum number of steps to walk from the upper left corner to the lower right corner given that you can eliminate at most K obstacles if it is not possible to find a such work return negative one so let's see this example we needed to go from the left up left her cell to the right bottom cell and this is one possible way because we can eliminate almost one obstacle there is only one obstacle here so we return six well last thing about this problem actually it may we remind you of the breadth-first search the difference breadth-first search the difference breadth-first search the difference between this problem which a normal BFS problem is that we can eliminate some obstacles and one thing in breadth-first obstacles and one thing in breadth-first obstacles and one thing in breadth-first search if that we usually need a vetted array to mark whether we have VT does itself before how about it in this problem do we need a VT array the answer is no because the reason we use a vita array in a BFS problem is that if we can video like this cell we can visit by go from here go right go down this is just the two steps and we can also reach it by go from here and go down go right and go up so this is four steps and we know that the two steps is less than them steps so if we can reach it and Sue sooner is better so we do not need to reach it again but in this problem as we can eliminate some obstacles if we mark it and VT though we may lose the right parts to the end this is in this example we can only eliminate at most one obstacle after this is the owning valid away because out of this destination cell they are obstacles so we can only eliminate one all this one so that means in the road we cannot eliminate any obstacle this is own invalid or paths but if we mark this cell as we do we will never find this purse why because when we meet this so we can eliminate right because we can mean later one Abstergo and then we go right then we go down so we reach this cell by only three steps so about actually the result we go down go right go up so this is five steps so we will like miss this part but in case we get a ton limit or exceeded or arrow how do we know whether we can go for go from these parts at then just ignore it because if we do not mark it we made end or some loop because like we go from here we go down then we can also go up right because this is one step we can go from here to this place but we can also go from this place to the store so actually neither two cultures obstacles in this path we are called how many obstacles we meet in this path like if we go these parts we know we already meet one obstacle but if we call this part we know we meet a zero obstacle so this may be a candidate or result so we updated the obstacles the minimum obstacle we meet go from 0 to 1 2 is 0 right because we can reach here by eliminate 0 optical so this is a whole idea we need an array we will call it a see this is a 2d array that means the total of circles we go from the source to the place and actually this is the minimum obstacles as this is BFS so once we reach the end we just returned the steps because every step is 1 actually this is unweighted and interact item search in a graph so what we should end we just return the answer okay now let's write the code we first get the and M and ungraded $0 so we need a see ya need and ungraded $0 so we need a see ya need and ungraded $0 so we need a see ya need a see that means the minimum of stir call we can meet but we need to go from source to here so this is the end and that we needed to initialize this array so for each i from 0 Allison and I plus so erase fail feel I enter as we needed to Gaza me as minimum as possible so we initially buys it to max value but the C 0 should be 0 right this is 0 obstacle and we needed to do a BFS search a BFS so neither Q into this and the alpha so we need offer the 0 and 0 means the number of obstacles will meet sofa and a while is queue is not empty we need a get the size of this cube because all the cells in the kernel level has the same steps size for int I caught user and best in size I prospers we also need a steps the first is 0 okay and outside this for loop we need to let the steps increment by 1 and we also need other directions for directions private aesthetic direction directions there one and there 0 negative 1 and 1 0 and the next 1 0 ok there we pull from the cue enemy to occur so cute and we get a row is curved there and the color is curve one and it was the row equal to a month M minus 1 and the : you equal to a month M minus 1 and the : you equal to a month M minus 1 and the : you caught you and minus 1 we just returned the steps otherwise we check the for Direction get our equal to Rho plus easier and the see what you call a plus d1 this index to be valid so when the quota equals n 0 and unless the M and the Secret Origins you and the C that's then and so if the obstacles on okay inter Oh damage obstacles equal to cur to Palast not greet our C because if it is obscure of circle which the increment by 1 if it's empty we just plus their role so we add it once this all is great Oracle the end the zip top circles we see here we have we there is no need to add a current cell into the to all the obstacles greater the under limit which is okay we just continue otherwise we update the C which is Oh and the we offer that into the tube which is RC and the OS obstacles so outside of the breadth first search we cannot find in the adult purse so we returned active one okay thank you for watching see you next time
Shortest Path in a Grid with Obstacles Elimination
three-consecutive-odds
You are given an `m x n` integer matrix `grid` where each cell is either `0` (empty) or `1` (obstacle). You can move up, down, left, or right from and to an empty cell in **one step**. Return _the minimum number of **steps** to walk from the upper left corner_ `(0, 0)` _to the lower right corner_ `(m - 1, n - 1)` _given that you can eliminate **at most**_ `k` _obstacles_. If it is not possible to find such walk return `-1`. **Example 1:** **Input:** grid = \[\[0,0,0\],\[1,1,0\],\[0,0,0\],\[0,1,1\],\[0,0,0\]\], k = 1 **Output:** 6 **Explanation:** The shortest path without eliminating any obstacle is 10. The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> **(3,2)** -> (4,2). **Example 2:** **Input:** grid = \[\[0,1,1\],\[1,1,1\],\[1,0,0\]\], k = 1 **Output:** -1 **Explanation:** We need to eliminate at least two obstacles to find such a walk. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 40` * `1 <= k <= m * n` * `grid[i][j]` is either `0` **or** `1`. * `grid[0][0] == grid[m - 1][n - 1] == 0`
Check every three consecutive numbers in the array for parity.
Array
Easy
null
198
in this problem there is a rover and his task is to rob some houses in a locality and there are houses in the locality in a row and each house has some money in it so maybe this house has five billion dollars this has 10 billion dollars this has 2 billion dollars 7 billion and so on the condition is that the robber cannot rob two consecutive houses so if the robot decides to rob this house then he can order off this house so he has to leave at least one house he can also leave multiple houses but at least one should be left otherwise people will call police so that's the strategy that robber has to decide and it's quite a popular problem and it has been asked in many of these companies so let's take an example so let's say we have this number so these numbers denote the money that is there in the houses and these are in consecutive the same order in which the houses are there so let's say the robber drops this house number two house with a money of two then he cannot rob seven so uh similarly if he drops seven he cannot drop nine and two so how can we do this so let's try to break this problem so let's say we have 2 7 9 3 1 so what we will do or let's say we are solving for nth number last number so either the robber will rob pick this value or not there are only two cases so if you look at the last one you can also look at the first one we will look both the approaches so let's say we are deciding for this value and we have already calculated for everything so first we are trying to come up with some recursive solution for this so that we are breaking n into in terms of smaller values of n so either the last one is robbed or not robbed there are two possibilities so one case is that last one is not robbed and the other case is that the last one is robbed so let's say plus denotes it was robbed so the robot picks one here so he has to lose this one he cannot drop three and one both so in this case what is the problem the amount of money that he got from robbing this one is one so one is there plus what else whatever is the optimal solution in this part not till here because this is definitely we will ignore it so n minus 2 so if this is n then f n breaks into two things the nth house is robbed so we get this let's call it a so a n it should be in fact n minus 1 but let's say it's starting from 1 whatever you are comfortable with a n plus f n minus 2 where f is the optimal solution for this in houses the best uh the largest money that the robber can get so this is one possibility when the robot tries to decide or decides to rob the last house the other possibility is that he says that see that this is a very small value let me try with excluding this one and including this one so in this case the robber will drop n minus 1 and then f n minus 3 these are the only two possibilities or if n minus 1 is already solved so it will be f n minus 1 so these are the only possibilities so let's get rid of this so max of these two so we had solved till this point so if we don't pick it will be same as f n minus 1 because we did not pick it if we pick it we will not pick n minus 1 so the best solution till this point so and we take max of these so in terms of code we can write fn equal to max of f n minus 1 and a n minus 1 plus f n minus 2 so here i am taking actual index and min or let's take n only so it's very simple but and this should work provided we have some base case that is if uh there is just one element or just one house then it will always rob that if there is there are two houses then uh max of these two so these are the base cases in fact you don't need even this base case here you will add this number and uh max of 0 that is 0 if n is 0 then it's 0 nothing to rob so the base cases should be n equal to 0 then 0 n equal to 1 then a of 0 otherwise this recursive formula so this will work but there is one problem so let's see what is the problem we have f n we are trying to solve it and we are expanding it as f n minus 1 and a n plus f n minus 2 so let's ignore these things for now these are constants so for solving f n we need f n minus 2 and f n minus 1. again when we expand f n minus 1 we will need f n minus 2 and f n minus 3. similarly here we will need f n minus 3 f n minus 4 so you will immediately see that we are seeing something similar to fibonacci series here also we will need f n minus 3 f n minus 4 f n minus 5 and so on so here you see that f n minus 1 f n minus 2 is solved using this if you expand this complete tree and here we are also solving f n minus 3 and f n minus 4 but you see that these are solved here again if n minus 3 is already solved if n minus 4 is already solved similarly f n minus 5 would also be there these are all already solved f n minus 2 is also solved so this entire thing is redundant there are overlaps so you see dynamic programming approach coming here we have optimal substructure that is if this f optimally solves for f n minus 1 and f n minus 2 then we can optimally solve for f n and also we have overlapping sub problems overlapping solutions so we will memorize this store it so there are multiple ways you can store everything in an area of same length as the house or you just need the previous two values like the fibonacci case so in fibonacci we keep track of previous two values because those are what we will need so here what we will do uh we will store the previous two values so let's run through this example 27931 so let's do it bottom up you can also do top down so let's solve this problem so we have fn if n is 0 then return 0 if n is 1 return let's say we have a and i am writing n here but we will need to calculate this in here a dot size or length if n is one return a0 so these are the base cases next uh we will keep two values what are these values let's call them val 1 and val two so initially this will be a zero and this will be max of a zero and a one so at any point of time val 2 is the latest value that is optimal solution till current you can name it in a better way previous and current so val 2 will be max of these two and valve one will definitely be a0 initially because if we have one element this is the maximum so this is val one or let's call it v1 and v2 will be solution till here current so it will be max of these two so v2 will be max of these two that is 7 so this is 2 this is 7. next we will gradually increase we will come here in order to solve this we need what we need these two things so this is the main formula so you can easily convert from this recursion formula to dynamic programming formula whether you write top down or bottom it does not matter both are same uh so the main task is how to find this recursive formula that we have seen so either we take it or not take it so if we take it we get 9 plus v1 if we don't take it then it will be v two so what is the loop that we will create here till one we have already it will return from the base case all only so if it goes beyond that means it has at least two elements or two houses so for i equal to uh one this is zero and one so this is the second element i equal to one to n minus one so what we will do we will have val two is the latest so this will be max of val2 and a i current element plus val 1 this 9 is nothing but a i the current element so this is v val 2 and then val 1 will take the value of val 2 we are shifting to the right so val 1 becomes this that is solution till previous so whatever was the solution till this point now this is v 1 and v 2 is here so listen till here but valid is change now so better we will keep it in temp and finally return v2 that's it so let's write the code for this if you want i can write the recursion also just to show you that will work for small test cases but that should fail the time limit so first let's write the recursive solution without dp without dynamic programming so if n equal to 0 return 0 if n equal to 1 or we don't need this one max off so we had taken max of n minus 1 this n minus 1 and n minus 2 plus current element these are the two cases where one once we include it or not and uh so it will be rob nums n minus two plus nums n minus 1 and we are passing here till n so let's see so this works for this case but you see time limit exceeded because you can see the recursion tree how quickly it's expanding we have 1 2 4 8 2 raised to the power n so it's exponential solution so clearly the time limit will exit similar would be the case when you try to find fibonacci using this kind of simple recursion so let's get rid of this but we will use this idea here and we will use bottom up same base case we had v1 so vt v2 is the current till current so that is previous and previous to previous so uh i denote the current index so max till here will be either max till previous value that is v2 or we include the current then max will till previous to previous that is v1 so this is v2 and this is v1 plus nums i so our answer is one more y so we have solution till 0 1 so we have to start from third element till 2 we already have this v2 so let's see if it fixes or not it should now our answer matches so let's try it on this example again an error here it should be max of v1 or num0 and this because v2 is the latest solution latest best solution till previous value now the solution is accepted and you can try a few times it should be 0 millisecond also so what is the time complexity here we are doing just one pass of this array so let me write it down so time complexity is o of n space complexity is o of one if you don't use dynamic programming time complexity would be 2 raised to the power n now let's complete this in java and python java solution is also accepted and here also it's 0 millisecond finally we will do it in python 3. and the python solution is also accepted
House Robber
house-robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**. Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_. **Example 1:** **Input:** nums = \[1,2,3,1\] **Output:** 4 **Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. **Example 2:** **Input:** nums = \[2,7,9,3,1\] **Output:** 12 **Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 400`
null
Array,Dynamic Programming
Medium
152,213,256,276,337,600,656,740,2262