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
126
hello friends today I saw what that to profit like even true words begin world and in the world and the dictionaries or at least find Osho days transformation sequences from beginner to end the word such that only one letter can be changed at a time each transformed word must exist in the world least not there begin word is not a transform the world let's see this example we are given a begin world which is heat in the N word is coke and these six words are the word list we needed to do some transformation so we can find a way from the heat to so we needed to find some sequences actually it's like generation you will think about your backtracking yes we need the backtracking to find Valley the way but how do you know build a graph it's just things like words we need abstraction to change it at your grass problem let's just do something by is tension we know the begin word is heat and then we can change some character actually one character to go to another word in the world list we can change i 200 so we can go to hot and then we're at hot we need to change to add the word we can change to dot change the edge to T now we can also go to a lot we change the edge to L but we do not write hit again also we can change all to I and go to hit but this is just a invalid maisha in well where's the many times you know we'll never be the shortest transformation times the same idea when we are as thought we will not change back to hot because we already use this transformation that means once we use a word we delete it from the world list we will never use it again and so suppose we can change to other word and you see this is just like the diagram we are at heat and we change one character we can only go to hot where we are at the hot we can go to two different words dot and lot and this two words are in the same level because we only change one character from hot and then we go from Tata to talk go from not too long this is another level and finally we can cut your so you will see that we change one character is it just a cost of one it's an unweighted every time we change one character is just a custom one and the analysis we can change from hot to heat we can also change from he that your hot this is all directional this relation are two way so this is the only the on directional graph you will think about breadth-first search to find a shortest breadth-first search to find a shortest breadth-first search to find a shortest path from a source to target in this graph yes we need to use BFS to find the you know the shortest path so what do we exactly do in this problem this is each level right and at each level we can change every character in this word and go try to find whether we can change to another exist a word in the dictionary so actually we can call it star sat for the current level although at the first a just one word but afterwards they may have two words in the same level so that call it starts at for each word in the current level starts at and for every chart in the world we change from A to Z we see whether this new word exists in the world list if it exists we can build a relation like from heat to hot we use a map heat too hot now once this new world new course to the N word we finished right this must be the shortest path because we go from the target that you sauce and once we find that the end the word we know it should be the shortest path do you see the problem about this algorithm actually you see as we go far this star cell will be larger and larger so the transformation we need that you make is more and more can we do better yes we can do some optimization we can call the N word initially it just one word in the word we can call it an asset once the star that has a larger size than the answer we can switch these two selves what does a me like if we are the star cell now is thought in a lot but the NSA is we need to change every word and every character inner star set but actually we can switch this to set that means we just change the world in the n set which is a and every character in this set because this transformation is true way we can go from told your dog and your we can also go from how to talk to dot but if we just change his it's much less transformation so we switch this to set but if we switch this to set the relation is also reversed what does that mean if we just keep the traditional prefer search every relation should be dot maps to talk in a dog maps to but if we switch these two sets we can go from cockatoo dog but has this reversed so we need that you record the dog max as a then maps dog so you needed to know that so once we switch this starts Ellen and said we also need to reverse this in relation let's see this example this is the star seller first is heat and LSAT is and then we change this eight to hot is still one word in the star set so we keep go keep going and then we change hot to can't talk and a lot now the star sale have is larger than and set so we switch this to set so currently the star cell is and answer is thought and law and the we can change this to can't talk and log previously we map the heater too hot and hot not to talk and lot but currently it's reverse so we do not write map to talk we write talk map to cut and lock map to and finally with this also started and this end set but there's a relation still reversed so we were right dot truth dogs and a lot to lock so this is the graph with Butte so the final step were just a bit to a traditional backtrack and you get the result would go from heat to hot there how to dot in the dot to dock and - and then we aren't use dog we - and then we aren't use dog we - and then we aren't use dog we aren't you start we choose lot and a lot go to block look go to so another way so the final part is just a typical backtracking problem ok so now let's write code first I will write the optimized solution we just used the and the world we just start from first choose the end understanding I will optimize the solution we will add these two cells so now let's write the code we first need the result list result new array list and though we need to change this what leads to set the reason is that we can quickly look at whether this word exists in a dictionary will passes you know what list okay we also we first do a quick check if the tick thousand that contains this and the world we will never find a value the pass so we were just to return the empty list it will use a graph there will be stream and there's a value could be a list the string or cell as you like now new hash map okay do a perfect search okay let's write to the breadth first search void BFS will use the stars here because as we go further in the same level we may have more words so it just snapped start set you have said we will add the start set you know star set editor became word okay so the first prep from MIT for metal will be their status tree parameter star set and their strength and the word sorry extreme and the word we also need path the map right let's drink okay so if once the start set size you caught your zero we just heard return otherwise we yeah we also needed to pass this dictionary so set straight ticked okay we need a temporary set because we needed a worse to the legs next level so we call it temporary hair said okay we need to not forget to remove all the words in the current star set their set we also need to check whether it finished so finish at first is false then for every word in the star set actually the current level star set we change the tutor Chari to charge a rape and the for every chart sis dollars plus we saved all the chart will be yes I know we try to change to other words so C star from a and C let's all call then Z C++ we can get the new world will then Z C++ we can get the new world will then Z C++ we can get the new world will be a new string but do not forget change so CS I will change to this right change in C okay so if the dictor contents if it contains the current word that means we can do something if the current word equals to the N word we finish right so finish will equal to qu otherwise we needed to add the word chooser transform the word to a temporary set so add word okay and yet if map yet as you got you know we will put s new ArrayList right current work the wheel adds map get as add word letter transform the world okay so for this folder but we needed to this for will reset CS I to the old chart okay yeah we will see if finished not yeah finish thought you go true we need to do another BFS there will be temporary Tabriz current are set and the end the world and will be ticked okay do not forget your move oh yeah sure so we fill these parameters there will be start set under and the world they will be map they will be ticked okay another thing is to do that therefore such a general result there will be list why because we needed to add the picking word to the list so list will add this begin word then we do their first search party result list and the King world and end word final return result okay now let's write this that first search we need this list o list straight result this will be the stream Thanks also there will be a current word and it will be the end word so what is the best case if the current word equals tutor and word we just add the current list choose a result list but we cannot just add the list you know that because of the reference so if we changed this we will also change the result okay oh yeah we also needed to pass the map because without this graph you cannot generate any Pass so we'll pass the map straight least astray map okay so if map get the you know get the word you go to now will not find any path so we just return otherwise for every next word in the map get word what should we do we add the next to the list and the weaker we do the backtracking we keep choosing next word so there will be next and in the world map then we all choose it so let's remove this is the size - yeah okay so let's do the optimization we can't use the you know and the set because we can switch is true that at some point then we add the zone and the set at this end would what do we do only needed to change the birth breadth-first needed to change the birth breadth-first needed to change the birth breadth-first search part so there will be an asset and the first it's not reverse so it's false okay so now there will be fat straight and the set okay food it is false miss that doesn't reverse okay so if once the start set the size greater than and the set size we reverse so we end the set start set map ticked and read those we will carry to reverse the we return okay finished false so what we do we need to change is here once the under set contents the end world sorry contains a current word and the second has a word we find a way so we finish also other than the SW we needed to reverse if the you know if the reverse is true that means the original transform the word will be the key right so if reverse true there will be word transform the word otherwise is as and the value the reverse is true in a web yes otherwise his work so it's not as its key so there will be kids oh sorry I had the bow okay so it's not finished this will be temporaries setting and set and the map dicta and we keep the same the reverse okay thank you for watching see you next time
Word Ladder II
word-ladder-ii
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that: * Every adjacent pair of words differs by a single letter. * Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`. * `sk == endWord` Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _all the **shortest transformation sequences** from_ `beginWord` _to_ `endWord`_, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words_ `[beginWord, s1, s2, ..., sk]`. **Example 1:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\] **Output:** \[\[ "hit ", "hot ", "dot ", "dog ", "cog "\],\[ "hit ", "hot ", "lot ", "log ", "cog "\]\] **Explanation:** There are 2 shortest transformation sequences: "hit " -> "hot " -> "dot " -> "dog " -> "cog " "hit " -> "hot " -> "lot " -> "log " -> "cog " **Example 2:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\] **Output:** \[\] **Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence. **Constraints:** * `1 <= beginWord.length <= 5` * `endWord.length == beginWord.length` * `1 <= wordList.length <= 500` * `wordList[i].length == beginWord.length` * `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters. * `beginWord != endWord` * All the words in `wordList` are **unique**. * The **sum** of all shortest transformation sequences does not exceed `105`.
null
Hash Table,String,Backtracking,Breadth-First Search
Hard
127,2276
455
hi everyone so today for leak code we're gonna actually try to do a problem that's kind of interesting I was just looking through the website and I saw a posting here by someone that you know congratulations got an offer from Google at l5 position that's pretty impressive so I was reading through this position a little bit to get understanding of the backstory because I want you guys to have a real-life experience you know have a real-life experience you know have a real-life experience you know this was done in October 14th 2019 and this individual gave you know some examples some tips on how they succeeded and I thought it would be a good question just to you know see real life possible questions right one of the questions that they got at least was his case his particular story was that he had two phone screens right one phone screen because and then he's trying to solve it but you know if you don't meet the full bar a lot of the times these big companies will give you a second chance if you're like very close so before diving into this person's profile I'm not gonna follow that I'm more focused on the question itself it seems like the first question that this person got ads asked was you know on the in the Revel one of these four questions which is assigned cookies employee tree and so on and so forth so I took a look at the first question and I thought that would probably be a good one to do with you guys cool let's look at assign cookies cool all right let's not look at his solution and actually just look at solving it ourselves now this person did it in you know C++ but let's try doing it in you know C++ but let's try doing it in you know C++ but let's try doing it in JavaScript for art's sake right so let's read the question first like always I assign cookies alright 455 it's an easy question so I don't expect this to be too challenging the question is asking assume you were an awesome parent and want to give your child some cookies great but you should give each child at most one cookie okay so that's an important factor right so no one can get fat they could only have one cookie great I understand that problem each child has a great factor of G okay a fine G of one that's fine which is the sighs of cookie that the child will be content with and each cookie J has a size s J so it could mean like basically this is gonna be the greed factor and this is the size of the pretty much cookies that you have right so if the size of the cookie is greater or equal to the greed factor of your rakaat child maybe might as well let's call this like the hungry factor we can assign the cookie J to child I and the child can be content and everybody will be happy okay cool let's see some of the important notes here you may assume that the grief factor is always positive you cannot assign more than one cookie to one child so this is very important like once again I keep repeating this if the interviewer asks you to give any tips about notes or assumptions make sure you note those down because those will be very important in solving your problem so we know for a fact here in summary that you have you know a list of hungry children and each of those you know you're given an array G right here that pretty much indicates how hungry each children is right and then you're giving a stack of you know cookies and those cookies have various sizes so you have a stack of cookies with sizes simple enough so in this case this is an example here's a list of you know people like children and they're hungry factors so this is like 1 2 3 simple enough and then you look at two equal sized cookie size right so in this example if you look at it since you're only allowed to assign one cookie to one child the only case that you know makes people happy here is if you know give child level one without one size of one cookie right because if we give child to you can't give me two cookies to satisfy their appetite because that's breaking the rule and none of these cookies are of size two or more but therefore you know these two unfortunately they're too greedy and they don't get anything so when the solution here is equal to one same place on the bottom here you know one too simple that they're gonna eat these two cookies and they're all happy so you have an excess of cookie in theory you can also give them these two cookies on the back but you know that's not the most efficient things so let's just trying to do something a little bit more efficient in a sense so let's go dive into the question I'm gonna actually turn this into a sixth format first now before I even think about like how to solve this problem let's give it a thought process what we have to do right so since you're giving a list of children each indicating how hungry you are it doesn't tell us anything about how these you know children line up or anything right so assuming that you're like in a field with a lot of you know honey folks you probably line up in a certain way right so what I mean by that is think about okay maybe I should you know sort the first the kids and I should probably sort the sizes of cookies that's my first thought and I think we need to probably you know capture or record the solution of each of the all the people that are successfully fed right so I'm gonna let's do that so let's create a variable solution equal to zero these are pretty much how do people how many people are fed great and then I'm gonna also keep an index here saying that let the greed index so this will basically keep track of where we are on the position of where the kids are like so I would call that green index because our solution we think about it I'm gonna go and basically go through my cookies and start seeing if my cookies feed the appropriate children right if it is great I just keep moving on to the next children but I'm gonna go all the way to the end of my cookie list and if I go to and my cookies no more food then you know sorry but you know the first people in the front get fed first so alright so next thing we need to do is make sure that the inputs are sorted so I'm gonna make sure my things are sorted a I'm a passive be in here so for those who don't know the sorting function you probably Google it yourself but effectively what this does over here is gonna sort it and increment increasing order right from smallest to largest and sort I'm gonna give it to a and B the two variables minus one a minus B boom okay that's great well semicolons cuz it's JavaScript and great okay cool so now we have two things that are sorted so what do we do right we're gonna actually go and look at every cookie sighs so cookie size right of s so this is a list of cookie sizes that I have and I'm just gonna be you know checking whether or not you know if my cookie size is greater or equal to greater equal to much my greed factor which is greed index which is basically gonna say okay it's the saw is gonna be fitting for that particular kid if it is alright great someone is fed so what I'm gonna do is gonna go solution I'm gonna increase by one and also the greed index I'm gonna increase it by one because that child has been fed and this is a you know a very simple question and the sound it's not complicated at all after you do this then I've kind of feel like we could just return the solution right and that's it let's try to submit the code see if it works and great we win now I know it's kind of like saying that's like 27% and whatnot but like I that's like 27% and whatnot but like I that's like 27% and whatnot but like I said before leak code is various you know it's kind of wonky sometimes depending on the night time of day you are each of these times can vary another example was like if I run the same piece of code here and just submit again you're gonna get a different time in 96 so anyways this solves the problem and yeah this hope this helps stay tuned for the next one see ya
Assign Cookies
assign-cookies
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number. **Example 1:** **Input:** g = \[1,2,3\], s = \[1,1\] **Output:** 1 **Explanation:** You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. **Example 2:** **Input:** g = \[1,2\], s = \[1,2,3\] **Output:** 2 **Explanation:** You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. **Constraints:** * `1 <= g.length <= 3 * 104` * `0 <= s.length <= 3 * 104` * `1 <= g[i], s[j] <= 231 - 1`
null
Array,Greedy,Sorting
Easy
null
452
hello everyone welcome back to coding Champs in today's video we are going to be solving the good problem minimum number of arrows to burst balloons I hope everybody has already gone through the problem statement if you haven't already do read the problem statement and come back here so to summarize the problem uh we have given some spherical balloon taped onto a flat wall representing X Y plane and the balloons are represented as a 2d integer array points point of I equal to x dot comma x n denotes a balloon whose horizontal diameter stretches between x dot and X end you don't know the exact Y coordinates of the balloons arrows can short up directly vertically in the positive y direction from different points along the x-axis a balloon with x dot and x n the x-axis a balloon with x dot and x n the x-axis a balloon with x dot and x n is burst by an arrow short x star less than or equal to X end there is no limit to the number of arrows that in B shot a short Arrow keeps traveling up infinitely bursting any balloons in the path so given the array points return the minimum number of arrows that must be short to burst all the balloons so basically the problem states that we are given a some balloons those are arranged in the X Y pane so they can be in at any y but the X range is given to us we don't really have to care about the y-axis and really have to care about the y-axis and really have to care about the y-axis and we have to shock short and arrow from X point uh into the positive y direction and it will burst all the balloons uh which are which have the diameter um like the X point from which the arrow is short is between the diameter of the balloon then that will that balloon will be burst and the arrow is will be traveling up infinitely so it will burst all the balloons in the way and we have to find the minimum number of arrows we can solve short to burst all the balloons so let us understand the examples uh in the first example we are given the points 10 comma 6 to commit 1 comma 6 and 7 comma 12. I let us represent it diagrammatically uh so here we can see in the first example we have uh 10 comma 16 and 2 comma it one comma 6 and 7 comma 12. uh so we can chart an arrow x equal to 6 bursting the balloons to commit and one comma six if we short and arrow here at 6 we can burst the balloon to command and one comma six if we shot at 11 then we can burst 10 comma 16 and 7 comma 12. so we require minimum two arrows to burst all the balloons now let us see the next case next example we have one comma two three comma 4 Pi comma six and seven command if we see the intervals of the balloons or the diameters of the balloons are mutually exclusive so we they are not overlapping mutually exclusiveness they are not overlapping so we require uh we must require a arrow to burst each pillow so for one comma two we require One V comma 4 requires one Arrow our gamma 6 requires another arrow and seven gamma require seven comma it requires one Arrow total we require four arrows to burst all the balloons and the next case we are given with the balloons one comma 2 comma 3 comma 4 and 4 comma five one comma two and two comma 3 are overlapping it two so if we bur if we launch an arrow at 2 we will burst one comma two and two comma three and in one shot if we launch next we have three comma four and four comma five if we launch an arrow at four we will burst three count four and four comma five in one shot so this will take another arrow so all of it all of the balloons can be buzzed in two arrows so all this um I hope you all have understood the problem uh so this problem is almost similar to the merge intervals problem uh in March intervals we see if two intervals are overlapping if they are overlapping we merge both intervals here as well if both intervals have some overlapping area those two intervals can be shot by a single Arrow so we can consider who everything as a single Belling or something and we only require one Arrow to short the overlapping intervals but there is a catch there is a difference between the both problems in merge intervals problem if we have let's say we take this example we consider the three intervals if one comma two and two comma 3 are over overlapping it too so we merge these two intervals and then we consider everything as a single interval and we go here and we try to merge these two intervals with this interval then we see there is a overlapping at three so we try to merge this interval in this two intervals and all the three intervals will become a single interval and all the three can be short um considered as a single interval but in this problem two short an arrow and burst the balloons we need a common point between all the intervals so if we consider these three intervals this three intervals should have a common X common x value uh so that we can short the arrow at that X and burst all the balloons if we consider here 1 gamma 2 and 2 comma 3 has a x value which is common which is 2 but for 1 gamma 2 and 3 comma 4 there is no x value in common so we do not consider them as a overlapping intervals or a single interval um so this problem we can solve similarly as um similarly similar too much intervals but we have to check that there is a common point so to check that we can sort the intervals based on the ending point and then check if both what are all the intervals that are that have a common x value to the current interval and consider them um as one arrow and then we go to the next interval if we take this case for example we have 1 comma 6 we take the ending point as 6 we see what are all the next intervals which um have common point with this uh current value so we next go to 2 comma it so two commit has common values so we consider both of them as a single short arrow and we move next we check if this um vertices 7 comma 12 has any common point with one comma six how we can check that we can check the starting value is um less than 6. or less than or equal to 6 then it has a common point but in this case uh the starting value is 7 which is greater than 6 so they are not overlapping we consider this as a new arrow and then we check then all the next intervals if they are merging with that in that way we can count the number of arrows number of minimum arrows required to burst all the balloons so I hope you have understood the inclusion let us code it up so in the first step what we have to do we have to sort the points in um we have to sort the points based on the ending point so for that we can use a comparator Indonesia dot compare based on the ending value so we have to give a of 1 and B of 1. after sorting we have to go to the we have to go through the balloons we have provided over the big nodes and now we if it is the starting will only consider it of or else when we consider as non-overlapping when we consider as non-overlapping when we consider as non-overlapping when the here let us consider the you know more value to store result which is arrows and we have another variable to store the current ending point initially it is 0 if the and ending is less than points starting value then we consider it as non-overlapping so we start a new Arrow non-overlapping so we start a new Arrow non-overlapping so we start a new Arrow here so for we increment the arguments and we update the ending point this and finally we return number of arrows so what are we doing here firstly we are sorting the intervals and then we this is for counting the number of minimum arrows required and this is the to keep track of the ending point of the current interval and we iterate over the balloons and we always consider the first balloon so I equal to 0 and ending is less than uh we are considering this case um so to start a new Arrow the ending the current ending should be less than the next starting so current intervals ending should be less than the current um points start then we increment the arrow and consider we update the ending point and then finally we return the arrows it is ramen it runs all the sample test cases it is submitted it passes all the test cases I hope you have understood today's problem if you did understood make sure you like this video if you have any doubts leave them in the comment box below and make sure you subscribe to the channel for more daily videos thanks for watching bye
Minimum Number of Arrows to Burst Balloons
minimum-number-of-arrows-to-burst-balloons
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where `points[i] = [xstart, xend]` denotes a balloon whose **horizontal diameter** stretches between `xstart` and `xend`. You do not know the exact y-coordinates of the balloons. Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with `xstart` and `xend` is **burst** by an arrow shot at `x` if `xstart <= x <= xend`. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_. **Example 1:** **Input:** points = \[\[10,16\],\[2,8\],\[1,6\],\[7,12\]\] **Output:** 2 **Explanation:** The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons \[2,8\] and \[1,6\]. - Shoot an arrow at x = 11, bursting the balloons \[10,16\] and \[7,12\]. **Example 2:** **Input:** points = \[\[1,2\],\[3,4\],\[5,6\],\[7,8\]\] **Output:** 4 **Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows. **Example 3:** **Input:** points = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\]\] **Output:** 2 **Explanation:** The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons \[1,2\] and \[2,3\]. - Shoot an arrow at x = 4, bursting the balloons \[3,4\] and \[4,5\]. **Constraints:** * `1 <= points.length <= 105` * `points[i].length == 2` * `-231 <= xstart < xend <= 231 - 1`
null
Array,Greedy,Sorting
Medium
253,435
88
hey everyone in this video I'm going to show you my solution to the code at8 merge sorted array first I'm going to explain what the problem is and then I'm going to show you the code implementation all right so basically you have two arrays and you have to merge and sort them into one at the same time okay uh here's the input to your function uh first is nums one which is an area of numbers second is M which is the length of Noms one then is NS 2 area of numbers and N is the length of nums 2 okay so here basically nums one is 1 2 3 and these three zeros are the empty spaces that you have to fill with nums two so there is three zeros and there is three elements in arms two and uh you are not allowed to use any array methods or anything and you have to change nums one in place so you have to sort merch nums 2 into nums one and you are not allowed to create a new variable so your function can't return anything it has to change NS one at place here is my excal notes uh when I was solving this problem uh here we have two arrays first is nums one which is 1 2 3 and remember these three zeros are the empty spaces that you have to fill with nums two and then we have nums two which is 256 first you have to find out what is the total length of the array after merge uh which will be the length of nums one which is M plus the length of nums 2 which is n uh and then since AR starts as zero index you have to minus one so n + nus1 will be the total length one so n + nus1 will be the total length one so n + nus1 will be the total length of the array after merge okay so we have a pointer uh which will be pointing at the last element which is here then you have to run a loop and compare the element at position M and the element at position n and put the bigger element at the last index here for example uh at the N is pointing at six and M is pointing at three you have to compare these two elements and then put the B one here which is six is bigger than three you put six here then we have to move n the pointer n back here MSA is here then we do the same uh we have to compare five to three uh five is bigger than three so here we be five then we have to point uh move this pointer to previous element which is two then we have to compare two and three uh three is beer than two so we have to put uh three here and then instead of uh moving n we have to move M okay we move M here then again it goes on you have to compare two these two are the same so it doesn't matter uh after to put two next and then uh change this pointer position to one then you have to compare uh two with one two is biger and so the N is zero at this point and then we know that uh m is the smallest element and we put it at first inex so basically this is our solution this is our approach there are several ways to solve this but this is how I solved it now I'm going to show you the code implementation to this problem uh here's our variables that we've seen earlier which is NS one uh M NS 2 and N then they execute merge and uh remember this merge function will change nums one at place and it doesn't return anything it's a void and then the console L out nums one all right so inside merge first we want to find out the last index uh of array after merch which is let last is equal to n + nus one okay then we want to run a + nus one okay then we want to run a + nus one okay then we want to run a loop here I'm going to run a wi Loop and as long as m is uh bigger than zero and N is bigger than zero you want to do something here uh no matter what we want to uh decrease Last by one and no matter what happens we want to run this okay the last elements is going to be decreased no matter what then we want to compare nums one and nums 2 so we have two pointers right we have M and N uh first for nums one I'm going to compare element at pointer M remember AR uh starts at index zero so we have to do this minus one on our arrays all right uh so if nums one at position m is bigger than nums 2 at position n then you want to do something here El we want to do something else so here we know that nums one is beer so nums one at position last is going to be equal to uh nums M minus one all right then here we want to decrease our M pointer y1 I'm going to save the file else we know that um NS 2 at position n is beer so again NS one at position dust is equal to nums 2 N minus one and instead here we want to decrease n pointer by one all right now if I save the file and see the output so this is our output uh it's working correctly uh we mered these two arrays and now one is sorted it's one 2 3 5 6 everything looks right uh there is an edge case to this problem where uh for example imagine here in this array uh We Run The Loop and then uh we go through all the elements at nums one and nums one is finished but imagine the scenario that you have some elements that are left in nums two so we have 2 five six but for example imagine if this uh there is two and we have the one here so uh maybe we go through all elements into Noms one and once we're done we have elements that are left in Noms two so we have to run another VRE Loop to make sure that all the elements in nums two are taken care of now if I go back to my code editor I can run another while loop here and say as long as n is bigger than zero I want to put these last elements inside nums one I'm going to say n nums 2 nus 0 and then I'm going to decrease n by1 and last y1 I'm save the file and copy this merge function go back to the code paste this here submit and there you go this is the solution to merch sorted di thanks for watching
Merge Sorted Array
merge-sorted-array
You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively. **Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**. The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`. **Example 1:** **Input:** nums1 = \[1,2,3,0,0,0\], m = 3, nums2 = \[2,5,6\], n = 3 **Output:** \[1,2,2,3,5,6\] **Explanation:** The arrays we are merging are \[1,2,3\] and \[2,5,6\]. The result of the merge is \[1,2,2,3,5,6\] with the underlined elements coming from nums1. **Example 2:** **Input:** nums1 = \[1\], m = 1, nums2 = \[\], n = 0 **Output:** \[1\] **Explanation:** The arrays we are merging are \[1\] and \[\]. The result of the merge is \[1\]. **Example 3:** **Input:** nums1 = \[0\], m = 0, nums2 = \[1\], n = 1 **Output:** \[1\] **Explanation:** The arrays we are merging are \[\] and \[1\]. The result of the merge is \[1\]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. **Constraints:** * `nums1.length == m + n` * `nums2.length == n` * `0 <= m, n <= 200` * `1 <= m + n <= 200` * `-109 <= nums1[i], nums2[j] <= 109` **Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time?
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
Array,Two Pointers,Sorting
Easy
21,1019,1028
234
hey what's up guys uh this is john here so today uh today's daily challenge problem number 234 palindrome length list you know even though this one's easy problem you know the reason i want to talk about this one is because you know this one has a few corner cases you know especially if you want to solve this one with the o1 space complexity so there are some i think it's worth talking basically you know okay so the problem is pretty straightforward given like a linked list and you return true if it is a palindrome right so i think everyone knows what palindrome is right so if you reverse that you know then it will be it'll be the same as the original one right so for example this one is true and second one is false because if we reverse this one you have two and one right cool so i mean the a naive approach is that you know since there's a linked list we can only start from the hat and then going uh continue going to the right side so a naive approach that we're gonna make uh maybe just have like a array right or a string whatever it is you know and then we while traversing the elements we store that element into a into that array and then in the end we will simply reverse the array and then we compare if the reverse array is equal to the original rate right so that's going to be a o of n time and by the time complexity it will be o of n right since we need a rate to store all the nodes value and so i want to talk about 01 time complexity sorry the one space complexity so in order to do that you know we have to use like slow and fast pointer so which means that you know let's say we have basically we have like some one two three four three two one right so let's see if this is the one if we use the slow and fast pointer technique and actually so if you look at this one uh for this one the number is odd right so which means we simply need to compare if these two parts are the same right and if we don't want to use the time the actual spacecraft space you know we have to somehow basically reverse either the front end or the uh either the first half or the second half you know in our case i think we are we're going to reverse the uh the second half oh sorry the second half you can i think you can you other also reverse the first part so after reversing that you know we have one two three right and then we simply just need to uh compare if this first half and second half are the same right and now the problem is that how can we find the starting point of the second half right like i said we need to use a slow and faster slow and fast pointer so basically we have a slow in a slow uh pointer it's increased by one so it jumps one step and the fast it jumps by two so that you know when the fast reach the end of this uh node list the slow will be pointing to here okay but as you guys can see that you know we have some corner cases here because you know this is the odd case right and how about the even case we have one two three let's say we have four and then three to one right so for this one you know actually the uh you know for the out case you know the starting point of second half is this three here but the uh for the even case you know the starting point of the our second half is here right so we have to so basically we have to be careful when we uh write slow and fast uh slow and fast logic to make sure you know the slow pointer we're always pointing to this one here and then for here this is going to be slow so here we want to make sure it's pointing to here okay so that's the first thing and another corner case is like it's like this one so one and two so for one and two so what is the starting point of second half it's here right so which means that you know we want to ask we want our slow pointer uh stay at x1 here because you know basically that the starting node of the second half will be the slow pointer dot next and that will be the starting note of second half and then we just need to use this node set the starting node to reverse the second half all right cool so let's try to write that slow and fast point slow and fast logic so we have slow and fast starting with hat right and while slow sorry well fast it's not empty and the fast dot next is not empty we'll have like slow equals to slow dot next and then fast equals to fast dot next right so and then we have second hat second half equals to what let's assume we have this kind of reverse and we have a slow dot next and then we just need to compare that right but this if you write this while in this way there'll be a issue here because the uh because in if it is a one two case right if it's a one and two fast and fast next there are they're both not nine so which means that the slope will moving will be moving forward right which means that slow will be pointing to here which is not what we want uh slow to stay here not moving forward right so how can we solve this one for a corner case uh only has two elements we can simply fix this one by doing a fast dot next and then fast dot next this will make sure the slope will stay at here you know let's verify this one with some like more examples here let's say we have one two three right and then four three two one right so let's take let's only look at the fast pointer so the at the beginning fast will be pointing to will jump to here and here it will jump to here right and then here how about here so from here we have a fast dot next which is two fast dot next is one so it will also jump from here basically the fast pointer will jump uh three times so which means that you know after this one the slope pointer will be at one two and three so this will be the slow pointer right and the slope pointer.next is the starting point pointer.next is the starting point pointer.next is the starting point of the second half which means the odd case works so let's try that even case right four three two one so for the even case again right so the fast jump to here one two and three all right so when the and the slow pointer will also point into one two and three which is here right and then slow dot next is also the starting point of the second half so which means it also works um actually you know what actually i thought about a little bit more i actually you know if we use it previously like fast and fast out next and we can simply change the slow dot next to slow because if we use the fast and the fast dot next actually the slow pointer will slow point will be pointing to the starting point of the next of the second half right because again so if we use this one the slow will be pointing to here and here the slope uh sorry i think i take that back actually you know this one should will not work basically no uh if you use this one i mean for this even case first out case you know the slow will still be pointing to here so basically we're trying to reverse here trying to reverse this starting from four here because this one will still jump to us three times and here basically we will have like uh a one two three four in the end right which might also be okay because you know even though this one even though it's for the odd case you know if we use this one the odd the slow point is not pointing to exactly the place we want to do the reverse but even though we reverse a little bit more on one more element but this one will not affect the final answer because you know in the end while we're comparing is one two three and one two three four it will stop at three here so we'll not we don't care about four so this one will also work actually so i think so yeah and for the even case right if we just follow this one you know we're gonna have like one two three and then here right so as you guys can see when the fast pointers here the fast and the fast knack they're out they're both true so which means the fast point will move one more one step forward which means the slow pointer instead of pointing to here it will point into here which is exactly what we need right and then we just do a swap reverse so okay basically either way it works you can either use the fast dot next and then you use the slow dot next or you can use the fast and fast next and then use slow here okay because later on you know when we do the comparison here we're gonna do a wild hat right and then the uh and the second hat right and then we'll compare that basically if the hat dot value does not equal to the second hat dot value will simply return false right otherwise we can move this hat forward right otherwise we simply return true in the end and but how about this one actually i know you have some questions let's say we have one two three four three two one right you know when we have when we try to compare these distance here right basically you know we have one two three four and when we reverse the uh the second half right so from four here it will become uh one two three and four right that's the second half because from second half here is one two three four and when we try to compare the hat this hat here you know what's going to be the hat so it will also be one two three and four actually right so for the second for the first half it's still one two three four because you know we never change the next pointer out of three so which means that three dot next still pointing to four and this while loop stops when the second hat equals to empty equals to nine which is the net the next one is none here right it's not that's why you know even though with this kind of like uh reverse even though it's reversed a little more also reverse this four here but it will not affect the final answer because the four it's common they're basically the fourth is the same in both the first half and second half right and so this one also works you if the effort if the slow point if the second half is at its correct position which is three here if that's the case you know of course it will also work because one two three it also works with one two three okay so now the only remaining part is the reverse right that's going to be a very standard uh method it's going to be a reverse i'm going to have a note right so for the reverse you know we always need to have a pre right and then we have a current equals to ha to node and then we have a while current right so we have we need a temporary node to store the current dot next and then we have current dot next equals to pre right and then the next one is the uh pre equals current and then the current equals the temp and in the end we return the pre yep i think that's it right so if i run the code here okay this one accept it and the let's submit cool so this one works right and let's just give it a try let's try the other one right fast dot next and fast dot next all right so if that's the case we have to use dot next we have to use dot next we have to use dot next right so this one should also work yeah cool yeah i think that's it right i mean obviously this one is like often time complexity and of off one space complexity because we're not using any additional uh storage only by changing the pointers right of each node cool i think i will stop here and thank you for watching this video guys stay tuned see you guys soon bye
Palindrome Linked List
palindrome-linked-list
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_. **Example 1:** **Input:** head = \[1,2,2,1\] **Output:** true **Example 2:** **Input:** head = \[1,2\] **Output:** false **Constraints:** * The number of nodes in the list is in the range `[1, 105]`. * `0 <= Node.val <= 9` **Follow up:** Could you do it in `O(n)` time and `O(1)` space?
null
Linked List,Two Pointers,Stack,Recursion
Easy
9,125,206,2236
1,025
foreign welcome back to my channel and today we are going to solve a new lead code question that is divisor key the question says Elise and Bob take turns playing a game with Elise starting first initially there is a number n on the chalkboard on each player's turn that player makes a move consisting of choosing any x with 0 is less than x and x is less than n and n fact factorial means n mod x is equals to zero replacing the number and on the chalkboard with n minus X also if a player cannot make a move they lose the game alright return true if and only Alice wins the game assuming both play optimally so what we are going to do here is we have to return true only and if Alice wins the game we have to return true as we have to return false so how is she gonna win the game I will tell you the lot behind it see first of all if n is equals to 2 let's see what how Alice will win so I will say that at least if let me write it here that if n is equals to 2 then early space at least we first choose one so automatically she will win all right if n is equals to me means four then again Elise will win because it will be 1 and 3 all right if n is equals to 5. then at least Let's Lose how is she gonna lose I will tell you how much you want to lose because uh I will say that a ice will choose Alice will choose what at least we'll choose one three and five see so if cheese choose is an odd value she will lose we will lose if she chooses uh an odd value else she will win so there are multiple ways of choosing uh of solving discussion uh numbering them I can say that return and mod 2 is equals to 0 that will give me an answer or I can see that return written what return me and mod 2 is not equal to 0 then also it will give me an answer I am saying that sorry is not equal to 0 no um I will say that is not equal to 0 instead of this I can say that if and mod 2 is sorry is not equal to 0 means if it's an odd value return false all right return true otherwise I can also solve this like this also it will run see it's running successfully so what I am gonna I am just doing here is I'm just checking if n is equals to odd or even if it's even then I will say it's true if it's odd then I will say it's false so uh if it's odd then it's false if it's even then it's true so that's all we have to apply the logic here so guys I hope that you understood this question and guys if you do so please subscribe to the channel hit the like button press the Bell icon button and bookmark the playlist so that you can get the updates from the channel thank you guys for watching this video and see you next time
Divisor Game
minimum-cost-for-tickets
Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of: * Choosing any `x` with `0 < x < n` and `n % x == 0`. * Replacing the number `n` on the chalkboard with `n - x`. Also, if a player cannot make a move, they lose the game. Return `true` _if and only if Alice wins the game, assuming both players play optimally_. **Example 1:** **Input:** n = 2 **Output:** true **Explanation:** Alice chooses 1, and Bob has no more moves. **Example 2:** **Input:** n = 3 **Output:** false **Explanation:** Alice chooses 1, Bob chooses 1, and Alice has no more moves. **Constraints:** * `1 <= n <= 1000`
null
Array,Dynamic Programming
Medium
322
274
hi everyone welcome back for another video we are going to do another decode question the question is h index 2 given array of integers citations where citations i is the number of citations a researcher receive for their eye paper and citations is sorted in a ascending order return compute the researchers age index according to the definition of each index on wikipedia a scientist has an index age if each of their n papers have at least eight citations each and the other n minus h papers have no more than h citations each if there are several possible values for h the maximum one is taken as the age index you must write a algorithm that runs in logarithmic time let's walk through the code we can solve the question using binary search we set n two citations that length left to zero and y two citations the length minus one while left is less than or equal to right we set mid to left plus y minus left divided by two if citations meet is equal to m minus mid we can return m minus mid since every element to the right of the index meat is greater than n minus meat else if citations meat is greater than n minus mid we set y to mid minus one if citations meet is less than n minus mid we set left to meet plus one finally if the exact point is not found we return n minus left thanks for watching if this video is helpful please like and subscribe to the channel thank you very much for your support
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
1,578
welcome to my youtube channel so after a long time i am actually making a video on solving a lead code challenge so one of my friends had a doubt on how can we approach this problem and i gave it a thought and i had a approach in mind so i thought of making a video on it and also code it and see whether my logic works or not right so yeah let's get started so the question is something like you're given a area of balloons and balloons have different colors obviously they signify them using the lowercase letters so if the lowercase letters are a so just imagine it as one color b is a separate color c is a separate color so if we give them different colors the array would look something like this now we need to figure out um like we made basically we make we need to make this area colorful so by that it means that no consecutive balloon should have same color right so in our case we see first is blue red it's fine blue again is fine but there are two blues back to back so we need to remove one of them and in order to remove them we are also provided with another array say which is named as needed time so we want to make sure that we make the array colorful at the same time the time needed to remove the total number of balloons um should be less right so we want to minimize that so in this case let's say the balloon at position three has needed time of three seconds and balloon at position four has needed time of four seconds so it makes sense to remove the one with three seconds because three seconds is less than four and i don't want to spend any more time similarly if we go down and take this example this area is already colorful so we don't need to do anything then we move here we see that there are two cases where the colors are back to back same so in this case i actually take care of the ones which take less time right um let's and before coding let's understand this problem um by going over the example so let me go here and let me create something like an example so i will first let me type it out let's say we have something like a let me zoom this in okay so we have a let's say a b right so we have something like this let me give it a needed time so this takes three seconds five seconds this takes two similarly this takes um six this takes five four eight and one right so these are the needed times now um let me create the colors because i have two colors i'll create a with red so i have red here then for b i will use green then i have a and then i have green which is a one two three four right so i have four here now what i can do here is if we see clearly um the first three balloons are in um are together so i'm confident that um in order to make it colorful i can only have one balloon out of these three right so these three is a group so it logically makes sense to keep the balloon which has the maximum needed time which is the balloon with the number five right so if i keep this balloon and i take out these two balloons then it makes sense that okay a total time it's taken till now will be three plus two because the first balloon takes three and six third balloon takes two if i had removed the second balloon then the needed time would have increased by five and i don't want to increase that five because i have to i want to minimize it right now let's come to the next group which would be it's the only single balloon so we don't care so let's keep it similarly after this there isn't any group like there is a divide division um so we keep that balloon as well now here we come and we see the four balloons right now in this four balloons also it makes sense to keep the balloon which takes the maximum needed time which is our balloon with the number eight so i remove these three balloons so my sum becomes now 5 plus 4 plus 1 which is equal to 15 is my answer because 15 is the total needed time needed to make this array colorful right now if we try to remove any other balloon you will see the time will increase and it's not going to give us the optimal answer so in this case i can actually greedily use my logic to remove the balloons in a group right so think of it as like i can start a for loop um from the start of the balloon and then till the time i see that the balloons match right i take out that group out of that group i take out the one which has the maximum value and just add the rest of them to my answer right so let's code it now my answer is 0 i'll start a for loop now i'll keep the i as it is um because as i said i will be starting another inside for loop now inside for loop doesn't mean that it's of n square because if we see our constraints um 10 to the power 5 is the allowed n value so we'll need to do it in o of n so i will be traversing over each balloon only once right and you will see how that happens so i will create another variable j max index so max index will keep store of the maximum index for one group right as i said in our case this last four balloons is one group and the first three balloons in one group and the other ones are individual ones because the group will be formed till the time we iterate over them all right so i have j color sort length colors of i equals colors that okay now i'll just make sure that if needed time uh for any other value is greater than my maximum value that i have then i'll update my max index equal to j and then i will have needed time sj cool and i will increment j plus now here we need to do one more thing i'll do i equal to j because um there is no way to increment i so and i have already traversed those values right so i don't need to go over them again otherwise it will become of n square now i will have my sum equal to zero now i'll just iterate over what i had between i and g right because that's my range let's say if there was only one color balloon in the group so it won't go inside this for loop because i am having this condition right and then if my k is not equal to max index so just ignore the max index right sum plus equal to needed time and then answer plus equal to sum and then i can return my answer let's see let's run this um it will run on the default test case oops where did it give the error expression unused oh sorry okay it works i hope it works on our test case as well okay it works so yeah this was the approach i hope it was clear if so if you have any doubts please ask me in the comments and then i'll reply also you can join my discord group for asking any doubts and i'm readily available hope you guys enjoyed this video if so please subscribe to my channel give me a thumbs up and follow me on instagram thanks everyone
Minimum Time to Make Rope Colorful
apples-oranges
Alice has `n` balloons arranged on a rope. You are given a **0-indexed** string `colors` where `colors[i]` is the color of the `ith` balloon. Alice wants the rope to be **colorful**. She does not want **two consecutive balloons** to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it **colorful**. You are given a **0-indexed** integer array `neededTime` where `neededTime[i]` is the time (in seconds) that Bob needs to remove the `ith` balloon from the rope. Return _the **minimum time** Bob needs to make the rope **colorful**_. **Example 1:** **Input:** colors = "abaac ", neededTime = \[1,2,3,4,5\] **Output:** 3 **Explanation:** In the above image, 'a' is blue, 'b' is red, and 'c' is green. Bob can remove the blue balloon at index 2. This takes 3 seconds. There are no longer two consecutive balloons of the same color. Total time = 3. **Example 2:** **Input:** colors = "abc ", neededTime = \[1,2,3\] **Output:** 0 **Explanation:** The rope is already colorful. Bob does not need to remove any balloons from the rope. **Example 3:** **Input:** colors = "aabaa ", neededTime = \[1,2,3,4,1\] **Output:** 2 **Explanation:** Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove. There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2. **Constraints:** * `n == colors.length == neededTime.length` * `1 <= n <= 105` * `1 <= neededTime[i] <= 104` * `colors` contains only lowercase English letters.
null
Database
Medium
null
103
in this problem we have to traverse a binary tree in level order but we have to do it in zigzag manner so it's a natural extension of the simple level order traversal so if you do level order traversal of this we will first print five then three and 6 are at the next level then we print 2 and 4 in this order left to right but here the difference is that first you will start from this to this so you go from left to right at the first level then you are in this side so you return from this side and first print six then three now you reach this end left hand so what you do in the next level you traverse from left to right and you continue like this so you can see this zigzag so left to right everything then right to left to right to left and so on so i will just give a brief recap of level order traversal uh if you already know it then it will be a quick revision for you so in level order traversal what we do in simple level order traversal we keep a queue and we push the first node to it so 5 is pushed here then we see how many nodes are at a given level so previous level we had one node and this is denoted by the size of this queue so size i will write here below it so now we are at next level so this denotes so just when we reach this level the size of the queue denotes how many nodes were in the previous level so we see that there are one there was just one node so we run a loop i equal to 0 to whatever is the size minus 1 that many times pop from the queue and why we are doing this loop because we need the info not just in one sequence like 5 3 6 2 4 but we need them in separate lists a list of lists where each list will hold nodes of a given level so when we come to a next level we should know how many nodes were in the previous level because we will be inserting in the same queue so it will grow so when we pop this element and we push it left and right to the queue so we will lose track of how many nodes were there in the queue before we started pushing nodes of next level that's why we add this loop and in this case it's just one so it will pop five so whenever we pop we push into a local vector or list in this case it will just pop one and it will check if it has left or right or both it will insert them in the queue so five is popped it has a left three so we will insert three into the queue it also has a right so we will insert six into the queue now this labels nodes we have inserted we come to next level so we see how many nodes are there in the queue there are two that means in the previous level two nodes were there so we will start pushing them one by one so for i equal to zero and one whatever is the size this time size is two so it will run two times we will pop three and look at its left right push into the queue so three we popped so six is remaining two and four are pushed and then we also pop six we will do it two times since earlier we had two nodes now two and four are in the queue so we pop three and six so we put it in a new list now again uh we come to the last level after the last level so these are holding the last level nodes so we pop two and there are no left right so we will not push it then we pop 4 and again there are no left right so we will not push anything now this queue is empty so we return this call terminates this level order call and these are the results 5 3 6 and 2 4 so here what we need to do first time we have to insert 5 next time how we will insert 6 and 3 so in this case you would say that keep a reverse variable a boolean initially you can set it to true and when we are done with this loop outside it what we can do reverse equal to not of reverse so it will toggle between levels for one level it will be true for next it will become not of that and that is false again it will become naught of that and that is true again and so on so let's see how we will do it let's say we are at some general level uh let's call it c and deal for simplicity let's assume there are only two nodes in this and there are many more nodes of it is just one level and it has some child or like e f g h so i'm just focusing on a generic level let's call it level l of the tree so uh there are two possibilities this level we had either printed like c and d so this was the state of q or the other possibility is that we had printed it in reverse order dc depending on whether this was before this level the we had we were in this side or this side so these are the two possibilities now if cd is the case that is from left to right then this should be printed in reverse order that is h g f e and in this case if dc that is we came from this side now we are in this side so we will print it in or push it into the list this level list in order ef gh so i have written both the possibilities so in this case let's say you are using another queue or dq in queue you can only push in the end but in a dq you can push in the beginning as well as end so uh so what here how we can achieve this so first we have to pop c so what we will do so how can we print these before e and f because first we will pop c and c has child e and f but these are coming in the end so what we can do here in this case we will pop an element and we will have a dq let's call it dq in dq we can insert from both beginning and end and similarly remove also so in this dq we will push front whatever node is popped let's call it x dot left then so dq dot push then dq dot push front x dot right and we will do for all these nodes so what will happen so first we parked c so its left is e so this dequeue is empty so we pushed e push front or back does not matter for the first element next its right is f so we are always doing push front so f is pushed in front of it next element popped will be d so left of d is g so we push in front of everything then right is h so we push in front of everything so you can see now in this or dq we have h g f and e whatever we required so we can simply append this dq to our original queue so this queue is just like this original level order traversal queue and we will continue till q is not empty so whatever the content of this dq append that into that queue so this these two would have already been popped you would have become empty and then we add this to the queue so this becomes the content of q before going to the next level and here what you can do again we can have ndq and dq dot d is popped first so what we can do in this case dq dot again push front and x dot right then x dot left here also we are using push front but here first we are pushing the right then left then right then left so how many elements these are for all the elements x in the queue it will do the same thing so first d is popped so right of d is h so h is pushed then left is g so g is pushed in front then next element popped will be c so its right is f and its left is e so this is the content of dq and the q has become empty so we append this into the queue so q now becomes this thing so we are taking care of both the cases so one of them will be reverse other one will be reverse equal to false so whatever we said here that we will keep a boolean reverse equal to false in the beginning and when we are done with one loop this for loop this denotes popping elements of one level so after that we will toggle it and in one of the cases we will do this thing left followed by right in other case we will do write followed by left and then append this dq to the queue and we will continue till q is empty so this is very similar to normal level order traversal so let's write the code for this you can go through this example it's also similar to our example so we come in the first level from left so 3 then we come to the right side so next is 29 which is 20 and 9 and now we are in left side so we will traverse from left to right that is 15 and 7. so the base case is that if root is empty or root is null then we have to return empty vector otherwise we have to return a vector of int and then we have a dq uh so i think i made a mistake here so this outer thing will also be dq because q in c plus only support push operation and it's pushed in the end and popped from the uh front it does not support inserting a i travel but dq supports insert function also where you can pass two iterators begin to end so you we already have this dq we will pass dq dot begin and the second iterator would be dq dot end so we are not using qs we are using just dq so let's keep in dq but we will call it q since to keep it similar to our normal level or traversal and q dot push back root and then let's keep that reverse thing also bool reverse equal to true and while not q dot empty and then inside this what we do first thing we do is count just like normal level order traversal so q dot size and then we run the loop and what we will do we will have a temporary vector which we have to insert in this vector of vectors so this internal vector will be a vector corresponding to a given level and this is the combined vector so each time we are creating a local vector and we are pushing into the bigger vector and we will also have this in internal dq which we are appending to the outer dq since it's a dq we will specify whether we want to pop from front or back so we are using it like a queue only facility we wanted was this insert function other than that we are not using it for any other dq operation we are using it as a queue only so if reverse is true we will do something what we will do if it's reversed then we will first push left so you can do a rough work and convince yourself run through one example and you will get to know in the reverse case first we will put left and then right and in the other case we will do the opposite and in this case it will be simply opposite first right then left and at the end of this loop which will denote one level so this denotes one level uh what we do q dot insert in the outer cube insert this is uh in this queue from where to insert so this will be empty so end does not matter and from this iterable from where to where so we will insert everything dq dot begin dq dot end and then in our final result this level is complete when this loop ends we are done with one level so we will insert all the nodes corresponding to that level like this to the outer result and we have to toggle the reverse this is very important one level done for next level it will be negative of this not of reverse so it will toggle between true false and so on and finally we return result so this was not very different from normal level order traversal only thing is that we added this reverse logic to take care of that exact thing and this works for this case let's try or let's submit if there is something wrong we will try some examples and this is accepted and you can see that it's uh zero millisecond that is we are right here no better than 100 of the accepted submissions so this seems to be an efficient solution although uh you can see a lots of variation here
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
355
A Pappu Gas Welcome Back Vansh is immersed in the record Designer Data Success Problem Designer on Twitter This Problem Women Have Not Decided To Withdraw Its Current Lever's Problem Try To Understand The Problem That Did Not Appear From The Tarzan The Structure Will Have To Do The thing but will try to understand this can be implemented and how can you to the data subscribe our YouTube Channel Please subscribe to spirits follow and to other user and effective directly top ten most recent centers new feet can be found and decided to support the following method From Online Shop The First Method Have Posted Valid Input You User ID And Create ID And This Will Create New Twitter Interviewers Profile Ok Intertwined Composer Profile From 1000 K Notes Second And Third Hour Second Operations Devi Will Need To Design Cigarette Newsfeeds Website Will Have Been Put User ID Pimple Top Ten Most Recent Visits To Reduce Newspaper Items Newspapers Posted By Users Udayveer Open Volume And By Viewers Harsil Acquitts Must Be Ordered From Most Recent To-Do List Recent Most Recent To-Do List Recent Most Recent To-Do List Recent Visits To Return To Top Ten Most Recent You Posts Which Posted By User Access Oil and half users pair is country for glowing and rider ne bittu method is just you a follow and always one is your fluoride itna the following and e saw this user profile has following eyes subject minute create for and follow alive latest and one example given in Directions statement morning is that tweet a class online first method will quality dot print and electronic against the 2019x dot new subscribe this one subject used for the return again that not to member use office follow also have appointed president card and Tweet cold six a that after all nav dot get new speech for one ok let's call the newspaper in three 500 immersed in top ten news feed for this you will have answers 65 subscribe and subscribe this following 10 users will doctor of law does this will rule Will Not Let You Know It And Not Only Will Return Latest Videos Only 10 2010 Inna Udhar Shivdarshan Network OK Should Only For All Right Now Been Replaced Home Mix Of Your Leaders Structure Design Award Winning Design Of This Problem Will All The Best Quality Don't Like And Also will inform and they will strive for solution subscribe this Video give water and witch should be used to this information for this is what the nation needs from being and will always be in touch with your user and others is not read this ki sadi sath twenty- 20 And Date Of Birthday Through Your ki sadi sath twenty- 20 And Date Of Birthday Through Your ki sadi sath twenty- 20 And Date Of Birthday Through Your System's Novel The Best Water And Data Structure Wood Like To Shoulder And How Will Stop This Details For This They Want To Implement The And Subscribe To Posts To Details They Will Make To Reduce With Your User ID And Respect you will always check on because minutes were taken by user and you only use also will work properly so whenever you will create post tweet and follow this video follow also will have new it can have a new user ID during this period This operations will be called at the time will check weather tuesday or notification not the sweet scanner for global wire map where are the usage details will be ok now that solve all problems like how to start user data of date of birth not win with Not need a part of this affidavit useful through out when you make improvements for it's ok know the next piece loveless gautam one such software to implement post ki verito will have user id and twitter id shock improvement this chaupat will do in this prithvi hai and user objective Question without you sir object which can have a e will start at you specific water that tweet cordiality and in the kind of list a half paint tomorrow morning w dot print will always love story in this list not know what to list will reduce date villa Kuwwat in this third okay but for now you will have a list of the day know the will cover subscribe and yes subscribe the self I will only be used once you subscribe The Amazing spider-man 2 subscribe The Amazing spider-man 2 subscribe The Amazing spider-man 2 how to user hall object of user can only Stroll a phloem for doing right now so friend details you can store in the uses of the following you are following na ruke this time number you have this method call you access user objective was to mother for right you have given in the new updates power To the set up the way you read this language have a one chord one to so you will read ******** are you later this user one chord one to so you will read ******** are you later this user one chord one to so you will read ******** are you later this user object you all actors tarf we new land to the deposit in from Bigg Boss whenever you call Unfollow This page no access this subject and you will remove the country from the states where they have also conveyed Last to the Best Ones Get Newspaper User ID Enter Tweet to Return to Top Most Recent Video Subscribe Must Subscribe Don't have any timestamp or Any Time Details Where They Can Find The Weather Dushmani For Any Other Disciplines After Firsts And How To Identify Weather This Entry Has Been Made For Dushmani Segment First Okay Sorry For That We Can Do It Is Winter Twitter Class's Science Has One Variable Which Will Hold And Which Will Be Like The Time But Will Be Quality Time Subscribe Thank You Are The Weather For Every Time You Will Always Be There Will Be No Subscribe And How The u Have Been Initiated Into The Are And Posted In To The Twitter Show Will Always At This Time Winter Tweet Subscribe 24512 Do Subscribe Will Have A Time Samruddhi Net And Jewelery Laika Unique Identity And Uniqueness For This Treat For The Best Wishes Give The Order That In Which Product Of All The States In Which All Distinct Comes That Your members are also useful when you two of your top and restaurant eyes are not thanks Things like how to get this top ten like Twitter and Huffington top ten most recent activities should forget what needs and lu se this Ronit is following a for different uses 1654 Is polling 126 polling booth free liye 4 k and five ok khan knowledge beach following hai na for each view where are the different at it's the everyone hai is loot se yes this to hacking this All there videos 124 ink tank ok user as soon as possible Say yes money will fix seven days good songs ok thank you sir for having and tweet from this 6 and your 05 having it's only one from 2009 decide that is nothing but water at times between stamping fennel till first backam and what is the president Warning don't know the way to the top most in this app you can go to the user consolidated but they would rather have been shot Video subscribe The Amazing and 1234 the walking and they can start this one and boys take top most of budget way recent Vighn Tech Top Most 10 and returned at result OK Know the Problem Share Is Hair Oil Interested in a Standard Top Most Recent Smoking But Necessary Before All Accommodating the Old Trees Which Were Not Interested OK So How Can They Reduce That Hak Hai Ko Choukor Example DJ Old Tits Yes viewers to ring in abroad use raw jack tweed is that finance goal even list will define the village do student no 1 is so issue of you remember the recent technique that how to mju's shot dead play list that your so let's you have and different List Given Limited Only 3 Jhaal Ki Aapke Knowledge Hai Data History Set A Good And Final Result Will Like To Create That Is Want So Short Doctor Chance 4 How Can We Do The Way Can Do It Is You Have A Shot At Least Ok Define One G Yes from behind Arvind size ok and all the first node from you are list chocolate vanshu and 4 others like this under you all actor will define we will define them app after few days active water minimum number from yameen hip sort will b and fast element here result will be whenever you to remove the element just set the next element from 10 m electronics coming from this one so add no cement to the list so you will remove 10 you will have three now again take minimum will be this lineage Elements to do the same process will and five to the your earliest so now you have a 3514 absolutely minimal set you will again be coming home and you will have final result in more share two they have decided to do something like but ultimately using ups only Extra Notes and Subscribe Now He Will Depart Immediately After Normal Quarterly This Lecture Will Start in Tourism Link List 920 To Every Time You Are What is The New York Times and Newsweek Schemes Will Start After This He Also Lets You Have This Link Class I Already New Tweet You Will Create New Nodule Edit Hair And You Will Make Your Head 210 Nokia 110 Will Give You Will Always Have Your Latest Will Be The Front Thank You Will Always Get Initially Water AlertsU Have Always Get Latest Software Can Apply Here Logic Gets You Can Start Which Will not go beyond Chauth Fast Lootega Dam Co for the next lemon juice unit them dot next9 tax date will give the element which is added new and is ok so after that will follow the same process you will take out 1000 blood for your that your 9486 you will again taken out in you Will add as they do not have anything from the on words from the lines will not enter ok word is gown hai navya 19 these elements which will follow the same process 2828 main all of will and deceive only for seven six will take off its 70 Game Same Process Will Continue Till They Creator Final List Finance Tan And Dano Mode Heart Bits Present In Any Followers Ok Happy That They Can Get Till Top Most In Recent Years No Water Tank Near Lake City For This Solution Sounf Your Desires Will Have Say It Is Savings And Follow Is The Nature Of Your Dream Dosh * Create That The Size And Look At These Women * Create That The Size And Look At These Women * Create That The Size And Look At These Women Need And Long And Time Together Top 10 Every Man Detox That For This Tricks Knowledge To Go Through The Code Will Be A Little More Clear Hak And right knowledge through it will define first global times at village in to the world with whip will poison we all the way are creating new user and newly appointed secretary of Newfoundland One Object will talk plug we will put off the Udayveer system will Always Have Enough To Main Objects In Space And Others Is A Sorry But You Will Have Decided To Win Every Year's Shooting Unmute Wear Passing An ID Service Team The Time Is Nothing At All Times Time Battery Are You Have Solid Will Give You All Will Benefit When you take top ten most recent activities in the further again wear is next to ultimately district will work as link cleavage show at will have or point to the next notes will define a vighn-vighn will have to the will define a vighn-vighn will have to the will define a vighn-vighn will have to the self journey to the first to create 800th Urs Painter Mintu Bhaiya Sign To The Time Okay Now 101 He Will Discuss Vighn Kaut's List In 1000 Drops Uses For Yours Will Do Be Sensitive Will Happen Will Remove It From This Site And Whenever This Use Pending What Will U Will Create New Twitter The Video then subscribe to the Page if you liked The Video then subscribe to the Page If Subscribe 201 After All What Are You Doing But That Practice Follow What are the Uses for Delivery Near De Villiers Setting to the Worst Saturn in 7th Floor During and After Removing the tide and user can also post 100 Ultimately behavior the user can do we need to the number you all subscribe solved and posts older posts newer posts tagged with the days you will want to create object and subscribe to current you stop this point to Point Sonth Ka Video E Will Find The Current To The Next Top Best In The World With Newly Created Evil Point To The Head Should Immediately You Will Move The Current To The Next Time You Will Also Have Newly Created A To The Head Master Person Mentally 9.9 Twitter objective will Person Mentally 9.9 Twitter objective will Person Mentally 9.9 Twitter objective will create civil lines for the structure of the first subscribe they have used this will create user in the global village will want to create a village subscribe to the Page quid top judge and wealth creator posted party wear calling in it third o post update User And Will Take Care Of Creating A Posts After Creating Tweet Online Safety And Post Method Will Work For Anything Which Has Been Targeted Newspaper Member Will Win To Return To Top 10 Recent Activities From Poverty This Chop Result Will Want To Return Pimple List Civil Defense First LIST OF CIVIL DEFENSE WITH THIS USER IS PRESENT IN OUR TWITTER ACCOUNT NUMBER SYSTEM USED TO KNOW WHERE TO GET THE TOP 10 RICHEST POLITICIANS WILL RETURN LIST subscribe The Channel Please subscribe and we will define criminal why or like feet and will be like based on the Order Be Done Before Time Tuesday Govind Strips Curved 810 Will Give The Order Of The Crescent Will Head Into This Priority Ky He Honge Nao What Will Do It Is Soviet Hai Viewers Set Will Tree To All Through The Day When Will The Head For Each User To This priority queue software you will have all the uses here into your page to start packing weight adhir wheat from the priority queue and again add new cars subscribe we want to go for all times and subscribe to quite added to your result because this is Not the final result is going to be written no drain plug defined no check dual next tweet user name is the edit into your priority for this pattern for at least tens and this YouTube is not aimed at a shop in the and you will have a result When you have a top ten recent loot simple c for raids and id 2013 global user name is not the first will not go into your system and will not be used in the village list shruti provides ultimately will decide to the yo set a fierce form s Third is there in the user object that is what is to is just same to you all set for dog and cat user name and oil doing something remove that id online facilities in it third option foils principle sonth dashrath in addition to pune its limitations of object oriented Design as well as the greatest value than 100 injured in next video
Design Twitter
design-twitter
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the `10` most recent tweets in the user's news feed. Implement the `Twitter` class: * `Twitter()` Initializes your twitter object. * `void postTweet(int userId, int tweetId)` Composes a new tweet with ID `tweetId` by the user `userId`. Each call to this function will be made with a unique `tweetId`. * `List getNewsFeed(int userId)` Retrieves the `10` most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be **ordered from most recent to least recent**. * `void follow(int followerId, int followeeId)` The user with ID `followerId` started following the user with ID `followeeId`. * `void unfollow(int followerId, int followeeId)` The user with ID `followerId` started unfollowing the user with ID `followeeId`. **Example 1:** **Input** \[ "Twitter ", "postTweet ", "getNewsFeed ", "follow ", "postTweet ", "getNewsFeed ", "unfollow ", "getNewsFeed "\] \[\[\], \[1, 5\], \[1\], \[1, 2\], \[2, 6\], \[1\], \[1, 2\], \[1\]\] **Output** \[null, null, \[5\], null, null, \[6, 5\], null, \[5\]\] **Explanation** Twitter twitter = new Twitter(); twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5). twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> \[5\]. return \[5\] twitter.follow(1, 2); // User 1 follows user 2. twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6). twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> \[6, 5\]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. twitter.unfollow(1, 2); // User 1 unfollows user 2. twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> \[5\], since user 1 is no longer following user 2. **Constraints:** * `1 <= userId, followerId, followeeId <= 500` * `0 <= tweetId <= 104` * All the tweets have **unique** IDs. * At most `3 * 104` calls will be made to `postTweet`, `getNewsFeed`, `follow`, and `unfollow`.
null
Hash Table,Linked List,Design,Heap (Priority Queue)
Medium
1640
919
hi everyone in this video we are going to solve the lead code problem complete binary tree inserter so uh in this problem we have to implement the CBT inserted class as you can see here uh CBT inserted renote uh this is these are the function description given here right here on the right side you can see these functions we have to complete this class here right so what we have to do is uh first um we are given a complete binary tree okay so complete binary tree is a binary drain which every level except possibly the last is completely filled and all nodes are as far as left as possible right so let's discuss what a complete binary tree is so complete binary trees are binary tree obviously it has binary in its name uh in a complete binary tree all the levels are full right as you can see this is the second level this is the third level they are full except for the last level may be full or may not be full but in the last level um if the notes are not um complete right to be complete there are there should be two raise power n nodes in this level right but they are not right so what we will do whatever the number of the nodes they should be as left as possible for example this eight right so we let's say we have only one node right so if we have only one node then if I insert it here right so this is not a complete binary tree similarly if I insert in any of these positions right we will not get a complete binary tree it should be like a complete binary tree starts filling from the left side right so if we had to make this tree right and we have values one two and three and four and five and six right from these values how we have created this tree first we inserted one here right that is the root node then we inserted in the left right one is inserted 2 is inserted to the left of it we cannot insert it to the right then after 2 is inserted we have to insert three so where will we insert three we have to complete the level also so we have to fill it inside of this right node right then three is also filled then we have to fill four right so where will we fill the four we'll fill the four here right because this level was full right after inserting one two three this level was full so we have to insert 4 to the left to most position which is empty so this is this one right so we will insert it to the left of two then four is inserted then we have to insert pipe right so pipe will be inserted where wood is already inserted here so we have to find the leftmost position right so the left we have three positions left so the leftmost position is this so here we have field pipe right five square now we have to fill six again this level is empty right it's not full it's not empty but it's not completely full so where will we insert six so for us now this and this position is empty so we'll fill in the leftmost position so we'll we have built six here right and so on like we have to seven and eight and nine we can put it um in this manner only right first if the level is not full then we have to find the positions which are left and we have to fill in the leftmost position right in all of the positions that are empty in that particular level right we have to complete it until this level is full and then we have to repeat the same for the other levels right so this is what a complete binary tree is now in this question we have a complete binary tree given to us right its root node is given and we have to complete this insert function that you can see here end insert it will insert the tree node into the tree with the value that will be given to us through this function right so the tree remains complete and Returns the value of the parent of the inserted tree node right and this tree node get root will return the root of the root node of the tree so let's see how we will um solve it right so first of all let's complete the very first function given here that is um this right here you can see we are given three functions that is the CBT inserter this is the Constructor this is um this is the function that we have to complete right the main logic of the program you have to write here so first of all we'll do is we'll create a tree node right create a tree node here so that all the functions will be able to access but you know let's call it R okay and then the user will you know when this class will be initialized we have to initialize this crude R right with the root node that will be um that the user will be given giving to us so what we will do we will simply write R is equal to root right so we have initialized our root so our first function is complete right it initializes the data structure with the root of the complete binary tree okay now we have to discuss the logic of this insert function what we have to do in this insert function we have to insert a tree node into the tree with the value this so that the tree remains complete and Returns the value of the parent of the inserted tree node we have to insert a node inside of a tree that will be given to us and then we have to return something also right the value of the uh node um the parent of the node that we just inserted so that is what we have to do so let's see let's take a tree here right so we have this tree all right let's say we have this tree right and now we are given on node 5 right we have to insert it inside of this tree so how do we have to approach it so as you can see two points here right first is the levels are complete right except the last level right so we have to complete all the levels right except the last level right so what we will do will check whether this level is full okay this level is also full so we have to find the level which is not completely full only there will be inserting rate if there is like if all the levels inside the tree are full then definitely we have to just create a new level and put the node new node inside of that right so this is one thing that you just noticed the second thing is that the um the node should be inserted in the leftmost position right the node should be inserted in the leftmost position so what we'll be doing first we'll be seeing the levels right whether they are full or not so when we have checked if the levels are full or not so we'll reach the level which is not full so we'll check right so we'll check whether this level is not pulled right so we have to check which positions are will here right so there must be even one two or three or maybe all the positions are that are empty so we have to check that and then we have to insert a node here right so in this case we had three positions which are empty so we inserted five here so we'll insert five here right so that is what we have to do so let's see how we'll be solving it as you can see we are checking levels so whenever we have to check levels what we do a BFS traversal right what is a BFS traversal we Traverse the tree level wise right let me draw the tree again so we'll have one year two here three here and Fourier and we have to insert this new node called pipe inside of the stream so whenever we are talking about BFS how is BFS implemented it is implemented using the Q data structure right so we'll be using Q right so we'll make a Q right let's say this is the queue okay right so first of all we will push the root inside of it we already have the root right so we will push the root inside of it okay then what we will do we will move to the next level right how do how will we move to the next level we'll check if this if the node inserted in the front of the queue right if this node it has both the children or not we will check if it has a left and if it is if it has a right or not so in this case you can see it has a left and it has a right so we'll push its children in here right so we will push the children in uh in this fashion right first will push the left one and then we'll push the right one okay so we have pushed these children inside of this node okay so the inside of this Cube now after we have inserted this we will pop this out so one is gone now we will come to 2 right so we are seeing for two also we'll check the same right if it has a left and a right so for two you can see that it has a left but it doesn't have a right so we have two fill this portion right and once this portion is full then we have to return the value of this node from our insert function that we have here right so that is what we will be doing right so let's say 5 is inserted here now let's say we have um let's say this was the tree given to us okay so because we have to keep moving forward right so this was the case that was given to us now we have to insert a six number node inside of it so again let's draw the Q again okay so that will make you understand the question more easily so we have this tree right now right so what we will do we will make a cube right so first the root will be inside of this queue then we will check if this root has a left and a right so then we can see that it has a left and a right so only then we will push these nodes inside of the queue so we'll push the left one first then we will push the right one right then we will pop this out and we will check this right two for two we will check whether it has um no it's children or not right so we can see that we have four and a five also so what we will do we will insert 4 and 5 here okay and we will pop this out right then we will move to 3 right now you can see we are at three we are at 3. so we will check if it has a left and it has a right it does not have right so we'll have a condition that if it does first we will check if it has two children right then we will insert inside of the queue and continue the continue our Loop right we will not go below the loop and below the loop what we will do is we'll put two conditions right if both the levels are not fill right both the children are not well then we'll check if the left is empty then we will simply insert here right so we'll simply insert 6 here right so this is done but let's say 6 was here and we have another uh another note 7 and we had to insert 7 also so what we will see we will move to the second condition right if take left was there but if the right exists if the right does not exist then we will put inside of the right so I hope the algorithm is clear so let's implement it okay so what we are doing right what we are doing is we are first creating the cube okay we are first creating a queue let's name it Q okay then we are the first value that this will contain is R okay and it's also create our um new node here only let's call it new node right which we will be inserting so it will be easy right we will we won't have to declare in inside of the Loop that we will be writing so we'll declare it here only so we'll create a new node keynote and with this value right so this is how to we have to create it so we'll put this here right so let me just write it here created node which has to be let me just it created the node which has to be inserted in the dream okay so this is done now what we will do is we will Traverse inside of this queue right so we'll check if Q is not empty only then go inside this Loop okay now what we'll do we will um we create it's a node and we will take the front of this queue right what we were doing here we were checking here right here as you can see we are checking here right so we inserted the root burst inside this queue so we inserted the whatever is in the front we have to insert inside of the node and then what we have to do is we have to check if we have a left child or not right and we have a right child if we have both then what we will do we will push the left child first inside of the queue we'll put the left child first and then we'll push the right child of this node right that is what we will do and we will just continue this function we will not move forward right because it uh this particular node has both the left and the right child so definitely will not be inserting in this node right then we will check if so now we'll write for these two conditions right we had these two conditions here that this first condition was two just uh if the like if a particular node has both the children right then we have to push it inside of the queue otherwise what we have to check right otherwise what we will check if uh if the current node that we are at if it has a left child or not right so if it has a left child then we will be moving towards the right and inserting here if the left chain does not exist then we will be inserting inside of the left of this node right so we have to check if this left child is empty right if this left child is null then what we will do is we will say that node of left because it does not contain anything we will just put the new node inside of it so here we have inserted the new node if there is no left child insert the new node to the left of the current node okay so we have inserted here and what we have to return we will simply from here only we will return the value of the parent node right because we have to return of the parent of inserted tree node so this node because we are inserting to the left of it so this node will become the parent of this new node right so that is what we have to return otherwise let's say the left one is filled then definitely right will be empty so we'll move towards the right and we'll insert our new node to the right of the current node right and then we have to Simply return the value of the node right so this is what we have to do inside of this function and simply will return 0 even though we will not reach this condition but we have to return 0. also we have to like pop the nodes out of here also right then the last function is tree node get root Returns the root node of the tree right we have to return the root node of the tree so we'll simply return R right so it took this node here right and we have just made all these changes inside of this R right and so that is what we will return so let's submit it okay so it's submitted so I hope you've understood how to solve this question thank you
Complete Binary Tree Inserter
projection-area-of-3d-shapes
A **complete binary tree** is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Design an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion. Implement the `CBTInserter` class: * `CBTInserter(TreeNode root)` Initializes the data structure with the `root` of the complete binary tree. * `int insert(int v)` Inserts a `TreeNode` into the tree with value `Node.val == val` so that the tree remains complete, and returns the value of the parent of the inserted `TreeNode`. * `TreeNode get_root()` Returns the root node of the tree. **Example 1:** **Input** \[ "CBTInserter ", "insert ", "insert ", "get\_root "\] \[\[\[1, 2\]\], \[3\], \[4\], \[\]\] **Output** \[null, 1, 2, \[1, 2, 3, 4\]\] **Explanation** CBTInserter cBTInserter = new CBTInserter(\[1, 2\]); cBTInserter.insert(3); // return 1 cBTInserter.insert(4); // return 2 cBTInserter.get\_root(); // return \[1, 2, 3, 4\] **Constraints:** * The number of nodes in the tree will be in the range `[1, 1000]`. * `0 <= Node.val <= 5000` * `root` is a complete binary tree. * `0 <= val <= 5000` * At most `104` calls will be made to `insert` and `get_root`.
null
Array,Math,Geometry,Matrix
Easy
null
210
hey folks welcome back to another video today we'll be looking at question 210 course schedule two the way we'll be solving this problem is by using two data structures um we'll use one of the data structures to keep a track of the number of courses uh that a course needs before they can take that course um and for a given course how many courses actually depend on that so if we create these two data structures it becomes a lot easier to solve the problem um so let's get started with that and then we'll understand the solution and as we continue quoting it so to keep a track of the number of courses that just create an end array and let's call this number of dependent courses okay so new end and then the number will be new courses awesome so and we also need a list of lists you could use other data structures as well to store this we could possibly use a hash map but just for Simplicity let's just use a list of lists um and let's call it dependent courses uh the dependent courses new areas wait uh I think that makes sense awesome um so before we start populating these two data structures we actually need to um add um new arraylist to the list of lists so let's do that I plus yeah we have a for Loop here so dependent courses dot add new every list awesome um number of dependent courses yes okay so we have that ready to go um since we have our data structures that are in place let's actually start populating them so for INT we actually have to iterate through the collection that's given to us which is the prerequisites and since it is an area of arrays let's try to pull out um each of the areas so prerequisite so for every single actually let's name it the prerequisite all right so let's get into course right um it would be prerequisite of zero and then we get into pre-chorus and then we get into pre-chorus and then we get into pre-chorus uh would be prerequisite of one wait okay so once we have this let's just clean this out so that it looks nice okay awesome um once we have that we get the dependent courses dependent courses dot get so for uh for this pre-chorus for this pre-chorus for this pre-chorus right for this course which are the courses that actually depend on that so for this course uh the pre-chorus this for this course uh the pre-chorus this for this course uh the pre-chorus this course is actually depend on it okay I feel like I'm saying course a lot so what do we want to do in this data structure is that for example if we look at example two we have one zero two zero so instead of uh storing it this way what we're trying to do is we're actually doing it this way so for zero we have one and two so basically what we're trying to say is that okay for um for the chords so course one and two depend on course zero and then um one depends on so three depends on one and then two depends on now three also depends on two so basic basically what this gives us is that it tells us um you need to take this prerequisite to take one and two you need to take one before you can take three you need to take two before you can take three so um I'll tell you how it becomes easier for us to solve it when you store it that way uh let's just keep it here in the comments so that we can walk through an example if needed later um okay so we have that and then we have number of dependent courses as in basically how many um courses uh do you need as a pre-rec so courses uh do you need as a pre-rec so courses uh do you need as a pre-rec so this will be course would be equal to plus actually I think I have a number of three courses actually I misnamed it pretty Rec courses so what are we saying here we are doing two things here we are adding um all of the courses that get that depend on a given course and then we are saying um for a given course how many courses does it need to take previously to be able to take that course um bit glitching is not used I think maybe I didn't basically uh why is this cannot find symbol number of predicts I think it should uh correct itself and sometimes okay once we have that we have populated like the data structure that we need to actually solve the problem um the next thing we need is actually a queue a linked list right and we also need a couple of other things and what do we need we actually need the array that will be returning so let's initialize that um what's the size we need number of courses to be the size okay we also need an index let's call it card index that keeps a track of uh the index where we're placing the courses in the resulting area and the other thing that we need what do we need out of this I think this one or yes so we need a for Loop that goes through all of this and we'll I'll tell you in a second why we need that so it's basically let's copy with this for Loop so what we're trying to do is we're iterating through all of the uh the courses and if um number of prereq courses of I it equals zero so what are we doing here so we're checking in the number of prita courses that are needed if any of them are equal to zero which means that if it is equal to zero that given course does not need any prereqs to take that course it doesn't need any prerequisites to take that course so those are the courses that will be added to the resulting area first so Q dot offer I so basically you won't be starting off with is uh the courses did not need any prereqs so once we have a queue it becomes pretty simple right you keep looping through that till the loop is isn't empty right um so let what do we do in the while we obviously pop uh in the queue so current course equals to Q dot remove I think it is yeah okay and then we add that uh to the resulting array uh and then content x equals oh sorry yeah current Index right is equal to current course and then you increment current rise current index okay awesome um what do we do now so basically we're saying hey once you're adding it to the resulting area right here that means by definition we've already taken that course right so if you're taking that course we no longer need to count it as a prereq so what you need to do is for end I in um dependent courses dot get uh current course we do number of prereqs of I minus so what are we doing in this for Loop we are saying hey the number of four since we've already taken this course since we have added it to the resulting list get all of the courses that depend on that course right so we are getting all of that and since we've already taken that the number of courses that we need to take now is reduced by one right so you subtract that and then you check if number of prereq courses for that course that we just subtracted if it is equal to zero that means you no longer have any remaining prerequisites to take that course so um so if it is equal to zero you actually offer that to the queue so that is the next course that we'll be looking at so it'll be um I awesome so this while look like while loop will keep continuing till um it is empty but there are some cases in which like for example there's like some sort of a circular dependency that doesn't really work so if that happens uh you want to make sure that you return an empty um array so how do you check that so you check that by seeing if the current index is actually equal to uh the number of courses so current index uh if it is not equal to a number of courses you just returned like let's initialize that's like a new area and just return it as a new end and then let's put size zero and just return it so you might be thinking all right so why number of courses right um it should have technically been so the current index so the number of indexes that it should occupy is a number of courses minus one but because it's in a while loop it does increment it by plus one so it will add the last course that we care about and it will still increment it by one so that's the reason why we actually check it with the number of courses instead of number of course is minus one right so that is like a check that we need to do before we return the array and in the end if everything is okay you actually return the resulting array awesome so let's try compiling this and see if it's okay all right the first few test cases are okay everything else is okay as well awesome so let's talk about the space and the time complexity um the time complexity of the internal resolution is of an um we're going through all of the prereqs here and then we are iterating um through all of the courses once so it is of n um and of n being like the number of uh prereqs that are given to us um and then the space is also off and since we are using data structures to store that data awesome so that is how you solve the problem um if you have any questions please let me know in the comments below if uh please don't forget to subscribe to the channel and like this video I would really appreciate that it definitely keeps me motivated to make more videos um thanks so much and I'll see you folks in the next video peace
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
787
hello everyone my name is Eric today I want to talk about legal challenge and June 14th and the problem is ship is flies with in case top and if it is actually a very traditional shortest path problem with but with one concern we cannot have more length K start K intermediate not and for example 1 we can only have one intermediate node so we can find toupees wine is co2 and the eyelids year one two and because this wine shorter so the answer is 200 but if we change the intermediate k in to do then we only have one pet because for these pets we have wind I know which is bigger than zero so the answer for example 2 is 500 and in my opinion there are two solution for this problem the first one is to use the price research and that the second one is to use latasha algorithm and port 1 has lay benefit for breathless search because when we insert into a priority queue integer algorithm it will take log n time however if will insert into a queue in BFS we only have to take recall one we go one time so in some cases BFS will become faster however for titles no reason if out wave is very skew it mean if Sun weight is very small or if for example one and the other for some way is very big for example 1000 the title algorithm will always found that shortage space so I chose operator Hoefler trend who found the deceased from the final answer more quickly if we carefully analyze the content of velocity the PFS will be km plus the number of age but for title so it will be a local class number of edge it means it will at 8 small then we use PFS is better and evil okay is largely Logan young Ustasha avoid maybe better but we have to care about one thing if the grave is very balanced for example all the weight his lesson laying if you use PFS we are perpetual integer algorithm no matter what 1 K is Len for this problem I want to explain the preferred search because the title of origin is already written in the textbook but for this problem the preface is a little different from the traditional PFS because false additional pf8 we for each know we can only face digital ones however for this problem because if lasers we although we have already fitted who we have to reach it to again because the place is different and this space is smaller so it is a little different from latino PFS so we have to have touch we have to have a terminating condition which is when account when in demon are not counted bigger than K all the price is P : bigger than K all the price is P : bigger than K all the price is P : cramming hose it should not continue and let me explain my algorithm of be a vet ed love beginning we have to insert the source node to our queue and we also want to memorize low current you may accumulate Christ and accumulate count means how many intermediates known now and then we will pop the source node for the first iteration and we get 1 and 2 in our cube and because for the to18 we have a weight of 100 here and 4002 we have a know of 500 then we will update the price to 100 and 500 and ladle account P plus 1 in the 4-3 key iteration we will plus 1 in the 4-3 key iteration we will plus 1 in the 4-3 key iteration we will pop out of the first node and lay up de la - because laser age 2 to 1 from the 1 to - because laser age 2 to 1 from the 1 to - because laser age 2 to 1 from the 1 to 2 we were 8 100 to least 2 to this 100 and we can get a payday lender which is 200 now and then for father - below there is no outgoing age father - below there is no outgoing age father - below there is no outgoing age so the 200 is love find no answer and there is one thing I want to mention because for the second iteration we don't need to tarry popular first note we may pop outlook second know we can also pop out a second know but for titles of origin we will definitely pop out lovers not and it is the benefit of a digest algorithm pathan eater will always found shortest paths but for PFF preface it is not necessary it is a advantage of love Dajjal shock and a little bit penalty of the PFA is of when we incident no we only have to take recall one time it is a difference I hope you can see that and like they let us see the implementation I use that EQ to make our make my queue and use a give or take which is very convenient in my opinion because we don't have to initialize the dictionary when it doesn't have kick and this is the PFS algorithm and the difference is here we have to have this condition so we will not waste our time and because when know each feature either can still read it again so if we don't have leased condition it will be attending achieved then we will return the mean host if it already updated if not we return negative one and it's our final answer and to summarize these problems we have two solution whines BFS and of the Alice DFS and when the K is small or look Rev is balanced BFS is better and Lok Lak is much paid is greater than Logan and grave is not so parents land I chose our operation is better and I what I have explained is let PF wasteful its problem and that digest algorithm can be read you can be seen in the textbook thank you for watching my video
Cheapest Flights Within K Stops
sliding-puzzle
There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`. You are also given three integers `src`, `dst`, and `k`, return _**the cheapest price** from_ `src` _to_ `dst` _with at most_ `k` _stops._ If there is no such route, return `-1`. **Example 1:** **Input:** n = 4, flights = \[\[0,1,100\],\[1,2,100\],\[2,0,100\],\[1,3,600\],\[2,3,200\]\], src = 0, dst = 3, k = 1 **Output:** 700 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. Note that the path through cities \[0,1,2,3\] is cheaper but is invalid because it uses 2 stops. **Example 2:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 1 **Output:** 200 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. **Example 3:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 0 **Output:** 500 **Explanation:** The graph is shown above. The optimal path with no stops from city 0 to 2 is marked in red and has cost 500. **Constraints:** * `1 <= n <= 100` * `0 <= flights.length <= (n * (n - 1) / 2)` * `flights[i].length == 3` * `0 <= fromi, toi < n` * `fromi != toi` * `1 <= pricei <= 104` * There will not be any multiple flights between two cities. * `0 <= src, dst, k < n` * `src != dst`
Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move.
Array,Breadth-First Search,Matrix
Hard
null
1,833
hi everyone so today we're going to solve lead code daily challenge problem number 1833 maximum ice cream bars so in this problem basically we'll have to find out the maximum numbers of ice cream we can buy with a given number of coins okay and we will be given an array of cost in which each uh individual ice like each this array will it will represent the number of coins required to buy this particular ice cream okay for example we can buy one ice cream at uh one coin three coins two coins four one okay and we have to find out the maximum number of ice creams we can buy with the given number of coins so it's a very straightforward and I'm uh easy problem to solve so what we're going to do we're going to sort these costs out and we will be checking like we will be iterating through this uh array until either we get uh our coins less than equals to zero or the cost uh you know becomes larger than the number of coins left so these are the only two conditions which you will have to check in the loop and as soon as uh we boil it any of these two conditions we're gonna return the reserve so let's move for the solution okay so uh first what I want to do is I want to sort the cost at it costs okay so the array is sorted now next I want to clear a variable in which I'll be storing my results okay after that like we just have to iterate through the costs a so I'll be using enumerate for that so that I can uh or we don't need to use enemy let's see for cost and costs okay if the cost of current ice cream is less than or equal to coins we have left then what I'll be doing is I'll be implementing one into the result and I'll be subtracting down the uh cost from the remaining coins okay like there could be condition if the cost becomes greater than the number of remaining points so I just want to return the results from that point itself uh we will be returning the results from like from outside this uh loop as well because there are there might be a condition where we will be able to successfully uh loop through the condition and this condition will not get qualited so let's see now yeah so the test case we got accepted let's submit for further evaluation yeah so we were able to successfully clear the test cases and I think we performed decent we outperformed 49 of the submitted Solutions so thanks again guys for watching the video and stay tuned for the upcoming ones thank you
Maximum Ice Cream Bars
find-the-highest-altitude
It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible. **Note:** The boy can buy the ice cream bars in any order. Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._ You must solve the problem by counting sort. **Example 1:** **Input:** costs = \[1,3,2,4,1\], coins = 7 **Output:** 4 **Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7. **Example 2:** **Input:** costs = \[10,6,8,7,7,8\], coins = 5 **Output:** 0 **Explanation:** The boy cannot afford any of the ice cream bars. **Example 3:** **Input:** costs = \[1,6,3,1,2,5\], coins = 20 **Output:** 6 **Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18. **Constraints:** * `costs.length == n` * `1 <= n <= 105` * `1 <= costs[i] <= 105` * `1 <= coins <= 108`
Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array
Array,Prefix Sum
Easy
null
799
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you have not liked the video please like it subscribe to my channel and hit the bell icon so that you get notified whenever i post a new video so without any further due let's get started so problem is champion tower guys see it's very important to see how we can approach this problem right so we will focus more on the approach then we will do dryer and then we'll see the code so let's see how after reading the problem statement we can think of the approach right so see problem is we stack glasses in a pyramid where the first row has one glass second row has two glasses and so on until the hundredth row each glass holds one cup of champagne what does this mean this means that there are glasses which are staggered in a form of pyramid that is see let's say we have this is the first glass then this is the second glass third class so this is your first row this is your second row right first row and second row fine and then uh this here in the third row glasses are like this so this is glass then here it's glass and here it's glass so basically they are staggered in a form of a pyramid then in the fourth row glasses will be something like this right so they will they are in a form of a pyramid so this is a pyramid right okay so and they are saying that each glass will hold one cup of champagne that is in this one glass we can have only one cup of champagne right one cup of champagne then some champing is poured into the first glass at the top so in the first glass which is at the top some shampooing is poured and when the topmost glass is full any excess liquid poured will fall equally to the glass immediately to the left and right of it for example let's say over here i am pouring one cup of shampoo right one cup of champagne i am pouring so what will happen this one cup will get stored in this first glass because this first glass can store one cup of shampoo so i'm pouring how much i am pouring one cup of champagne so this first glass this is the first glass this will be completely filled fine now see what will happen now let's say i am pouring how much i am pouring two glasses or two cups of shampoo so when i am pouring two cups of champagne only one cup can be stored here right if two cups are being poured one only will be stored here rest will spill out and how that rest amount will be divided so if i am let's say i am pouring two right i am pouring two cups and only one cup can be stored here so how much will be spill out what will be the amount that will spill out so spill out amount will be whatever is poured minus one y minus one because one cup can be stored here rest whatever it is there will spill out will fall so two minus one that is one so one left one cup one which will spill out will get uh like that will be spilled out from this glass right now that one amount will equally divide into the left class and the right glass fine so if one is there half will go here that is if we divide this whatever spill out amount by 2 and whatever will be that x let's say x that x amount will go in the left also and the right all fine so here what will happen see what will happen here this glass second glass will be filled so here what will happen this half is filled and this is half filled when we are pouring two glasses two cups of champagne so this will be the scenario so if they're asking now let's see what they are saying um for example after one cup of champagne is poured the top glass is full so one cup when we are pouring one cup the first this blue one right only the first glass was completely filled after two cups of champagne so when we are pouring two cups of champagne first glass will be filled and the second row glasses will be half filled two glows uh two glasses on the second row are half full right they are half full after three cups so let's see when what will happen when we pour when we are pouring three cups so now we are pouring three cups right so see what we are doing over here let me erase this is very important guys just carefully see this we are approaching the problem right when you will read the problem now side by side you can also make this kind of diagram and you can think of approach so see now we are pouring three glasses right we are pouring three cups of what uh shampoo so one cup will store here because this glass can only store one cup of champagne so if three we are pouring and only one can be stored in this glass so how much will be spilled out two glasses of champagne will spill out right from this and this two will be equally divided in left and right so equal amount will go in left equal amount will go in right so that what will be that amount this we will divide by two one two by two is one so one will go here that is one cup of champagne will go in this cup and one cup of champagne will go in this cup so now this is also a glass right this is also glass and one glass can store one cup of champagne so this glass will be completely full complete be completely filled because one cup of champagne is being poured spilled out from the above cup right so above glass so this will also be full filled fully that is when after three cups what is happening uh after three cups of champagne are poured the two cups become full so these two cups this one and this one are full now when we put when we poured two cups then they were half if you remember now we are pouring three so now they have become full so there are three full glasses total now this is one full glass this is one full gas and this is one full glass so there are three full glasses now after four cups of champagne so now let's see how what happens when we pour uh when we pour four cups of champagne so pouring four cups of champagne so see what will happen so this is also very important guys uh just carefully see this also so see what will happen uh when we are pouring four cups of champagne just try to pause the video and think what will happen when there are four cups of we are pouring four cups of champagne so see uh over here let's say we are pouring four cups of champagne so here four are poured so four minus one will store here so left will be 3 so 3 will go here so this will be 3 by 2 that is 1.5 that is 1.5 that is 1.5 will come here and 1.5 will come here and 1.5 will come here and 1.5 will come here fine 1.5 in the right half a right cup fine 1.5 in the right half a right cup fine 1.5 in the right half a right cup and 1.5 in the left cup and 1.5 in the left cup and 1.5 in the left cup now we will go to the second row we have we are done for the first row here it is one only here one will be stored and rest of the three amount will spill equally in the left and right so three by two one point five so one point five come here comes here one point five comes here fine now we go in second row now we will see this one point five is greater than the capacity of this glass see guys in this glass we can store only one cup of champagne fine which is was mentioned in the question it was mentioned that each glass can hold only one cup of champagne but here we are storing 1.5 but here we are storing 1.5 but here we are storing 1.5 which is same as this case right here also 4 we were storing but actual capacity is 1. so see same thing we will do here as we were doing here for this first glass same thing we'll do 1.5 is greater than 1 means what we will 1.5 is greater than 1 means what we will 1.5 is greater than 1 means what we will do 1.5 minus 1.5 minus 1.5 minus 1 that is this is the amount that will spill out from this glass spell out so 1.5 minus 1 will get spell out so 1.5 minus 1 will get spell out so 1.5 minus 1 will get stored here and rest 0.5 stored here and rest 0.5 stored here and rest 0.5 0.5 will 0.5 will 0.5 will spill so spill will be equally in left and right both the glasses so 0.5 divided by right both the glasses so 0.5 divided by right both the glasses so 0.5 divided by 2 that would be 0.25 2 that would be 0.25 2 that would be 0.25 so 0.25 will come here so 0.25 will come here so 0.25 will come here and 0.25 will come here and 0.25 will come here and 0.25 will come here left and right that is this is 1 by 4 1 by that is quarter so they're saying and for this also for this 1.5 is there right for also for this 1.5 is there right for also for this 1.5 is there right for this was first glass now we will cover to the second glass this one 1.5 cover to the second glass this one 1.5 cover to the second glass this one 1.5 for this also 0.25 for this also 0.25 for this also 0.25 will go in the left so for this c for this glass this will be the right glass and for this glass this will be the left glass so here of 0.25 will come so here of 0.25 will come so here of 0.25 will come and here also 0.25 will come so this and here also 0.25 will come so this and here also 0.25 will come so this 0.25 plus point two five this will be 0.25 plus point two five this will be 0.25 plus point two five this will be zero point five fine so what will happen when we are pouring four cups now see this is fine right this is under one so this can this is not spilling out this is also under one and this is also under one less than one so this can be stored in this glass fine here we will stop now so see when we are pouring four cups of water one two and three he cups three glasses are total full these are totally fully filled and the last row uh glasses one is half filled this middle one is half point five half filled and the rest of the two are the are quarter filled that is one by four you see after four cups of chiang ping are poured the third row has the middle glass half full third row this is third row it has middle glass half filled 4.5 0.25 from this side 0.25 half filled 4.5 0.25 from this side 0.25 half filled 4.5 0.25 from this side 0.25 from this side and the two outside glasses these two this is the outside glass this one and this one these are 0.25 0.25 these are 0.25 0.25 these are 0.25 0.25 they are quarter full means one by four filled fine so this is the scenario i hope you understood the problem see now after pouring some cups of champagne so in the problem in the input we will be giving how many cups are being poured like two cups of pork three cups of food four cups are poured right so let's uh in the input we will be given integer cups how many cups are of champagne are being poured and we need to tell how full the jaith glass in the ith row will be that is let's say i'm just erasing this so let's take input they are saying that four glasses are being poured like four cups are being poured so uh here poured this poured value will tell us how many cups are being poured so four cups are being poured query row one query class one means in the first row and the first column they are zero index right so what will happen here we saw this thing right so when there are four cups being poured so in the first row this will be the first row right zero index one so this will be the first row and query glass means the first column that is this one zero this will be zeroth column and this will be the first column fine so see what will be the case if four glasses are being poured then in the rows the row first and column first that will be this one right that will be this one so here this is the first row fine just a second yeah this will be the first row zero one two indexing is starting from zero and zero uh and this will be your first column so one point five or that is sorry one will be your answer for that fine one the here in this cup you have to tell how many uh how much what uh like the amount is there so one is the capacity one is the shaping in this so now see guys now we have to think of we got some understanding from the uh like a problem right after reading uh the problem we got some understanding what's that understanding let's see that so see when we have this glass and there are two glasses below it so this is something like this right something like this so every glass let's say this glass has left and right this glass has this left and this right fine so for example if here x amount is there and this x amount is greater than one why if it is great so see if it is one or if it is less than one or one right if it is less than or equal to one then it's fine then there is no problem because this glass has a capacities to store one maximum right one cup maximum but if x is greater than one that means let's say it's four or it's three so this three cannot three cups cannot be stored in this single glass right so only one cup can be stored so rest of the two cups will over will overflow will spill out so that will go in the left and right equally that is x minus 1 whatever the amount is that will be divided by 2 and that will go here in the left and it will go here in the right so this was this is what we were doing here right if you remember this is what we were doing here we subtracted and then we added in the left and right fine now we have to see how we will represent this thing how we will represent this so that means see if this is see this is so clear that this will be some kind of matrix where because see here we have rows now this is these are rows and these are columns iath row and jth column this will be some kind of matrix so how we will store this matrix in a pyramid form how we will do that is the main problem and that's the main difficulty in this question right see let's say this is i comma j index right this is i comma j where this glass is now when this glass is uh will spill out like when it will be overflown uh so then it will go in left and right fine now this left will be what this left will be the uh the next row this is the next row so i plus 1 so here this will be also next row i plus 1 now this is the current column right this is the current column so this column ideally will be j minus one that is one previous column and this column will be one next the next column that is j plus one fine so we will like initially we will think like this that okay this will be the left column and this will be the right call but this approach is not correct why because see you will make some kind of this matrix right uh this first glass where you will store it this first glass you will store it here in the middle or where like in which column we are not sure enough about that it could be in any column it could start from here or it could start from here so that's the main issue where to store where to have this first glass if it will be here then this one left one it will go out of bound because it's j minus one column so solution to this when you find when you face this kind of issue that where you have i comma j and you have to have i minus 1 i plus 1 comma j minus 1 and i plus 1 comma j plus 1 something like this you have then if you want to uh store it in a matrix how you can do that see uh let me draw the glasses again so this is these are the glasses fine this is a very interesting question guys so see um something like this so this is like and indexing i will also do indexing so this is zero throw first row second row third row and columns i will not mark as of now but that will not mark for now so see we will store this in a form of matrix only but see this one so 0 let me do an x in 0 1 2 3 4 so this first glass right this first class will be stored here at zero comma zero then it's left this glass left glass will be stored here and the right glass will be stored here that is if this is i comma j it's left glass will be at here this is i comma j in j so this will be i plus 1 comma j only j column but the next row and this right glass will be i plus 1 and j plus 1 that is the next column right it will be the next column so this is how you will be storing the left and right glasses fine so this will be our approach right in this way we will be following this problem that here first class will be i comma j so the left glass will be i plus 1 comma j and the right class will be i plus 1 comma j plus 1 right so i hope you understood the approach so let's see the test cases so in this test case what we are given here see board the row and the class so this row is the row and this glass basically is your column but which column it will be in so see now let's dry run right now finally let's dry run i will take a smaller test case because otherwise it will be too long so see let's say we are pouring poured value is three so in the test case this port is given three that is three cups are being poured so i'm making a matrix and guys in the question now in the constraints they have mentioned that the number of maximum rows could be 100 fine so there would be maximum hundred rows that is these glasses rows these one two three these will be maximum hundred so i am making this kind of uh matrix and if you see a pattern guys here if you see uh if the see if the row is the one right columns will be zero one that means uh this column count will be equal to i that is let j will be less than equal to y that is j is equal to 0 comma 1 if i is 1 here i is 2 so j is 0 1 comma 2 0 1 and 2 that is j will be less than equal to i fine this is one observation you can make from here so if i is 3 0 1 2 3 fine so see now what you will do let's uh dry around so here three cups of board uh let's we can make see we can make her one zero one rows only we can run a loop for that much only because one zero one is constant only so it doesn't really matter here columns will be like this so see this could also you can take one zero one only because we just saw that j will be less than equal to i so if i is hundred j will be hundred fine so this will be 100 1 0 1 cross 1 0 1 matrix fine now initially uh what we will do let's also see the code side by side so what we are doing is uh we are making this c we are taking this matrix one zero one and initially we are giving value zero here so all cells will have value zero right initially three cups of board so i am here in the zero comma zero that is let's say m zero comma zero i am val i'm just uh storing the value port three now what we will do we will check we will traverse this row and we will check 3 is greater than 1 means this will overflow so this how much will overflow 3 minus 1 2 will overflow so that is it will go in the left and it will go in the right so left is here right is here how much will going left this 2 divided by 2 1 so 1 will go in left one will go in right fine so see we are traversing in the first row and in the this column fine and what will happen and this j will be going less than i right if result i j is greater than 1 here 3 is greater than 1 so what we are doing in i plus 1 comma j that is here this is i plus 1 comma j we are storing result i comma j that is 3 minus 1 divided by 2 we are taking 2.0 so that we can get in we are taking 2.0 so that we can get in we are taking 2.0 so that we can get in a decimal 1.5 like that a decimal 1.5 like that a decimal 1.5 like that fine so here one will stored and in i plus one comma j plus one here one will store that is this is i plus one comma j so left also and right also equally spelled equally amount is spent and this you will replace so now since you have spilled here right now this here will we'll store one only because now we have equally spilled right so here one will store and the rest is in the left and right so if now query is that you have to uh what you have to do you have to tell in uh first row in the first class that means first row is this that is first row as in one index row and first glass means this glass so one comma one that is this so here glass is full that is one the glass amount is one fine so if you see here if we write three cups are being poured and we need to know what is that one comma one index that is here one comma one so run code and we will get one so we are getting one fine i hope you understood in the last will return row class comma query plus so let's submit this so it's getting passed right i hope you understood the problem guys very easy problem and complexity is fairly simple to see what is happening here i is constant right i is constant that is i is maximum value 100 so 100 in 200 will be time complexity and space complexity will be also 100 into 1 0 1 you can say because we have taking this matrix fine i hope you understood the problem let me know in the comments if you have any doubt and you found the video helpful please like it subscribe to my channel and i'll see in the next video
Champagne Tower
minimum-distance-between-bst-nodes
We stack glasses in a pyramid, where the **first** row has `1` glass, the **second** row has `2` glasses, and so on until the 100th row. Each glass holds one cup of champagne. Then, some champagne is poured into the first glass at the top. When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it. When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on. (A glass at the bottom row has its excess champagne fall on the floor.) For example, after one cup of champagne is poured, the top most glass is full. After two cups of champagne are poured, the two glasses on the second row are half full. After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now. After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below. Now after pouring some non-negative integer cups of champagne, return how full the `jth` glass in the `ith` row is (both `i` and `j` are 0-indexed.) **Example 1:** **Input:** poured = 1, query\_row = 1, query\_glass = 1 **Output:** 0.00000 **Explanation:** We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty. **Example 2:** **Input:** poured = 2, query\_row = 1, query\_glass = 1 **Output:** 0.50000 **Explanation:** We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange. **Example 3:** **Input:** poured = 100000009, query\_row = 33, query\_glass = 17 **Output:** 1.00000 **Constraints:** * `0 <= poured <= 109` * `0 <= query_glass <= query_row < 100`
null
Tree,Depth-First Search,Breadth-First Search,Binary Search Tree,Binary Tree
Easy
94
648
6:48 replays words in English grammar 6:48 replays words in English grammar 6:48 replays words in English grammar concept core group which can be followed by some other words to form another longer work let's call this word successor for example the end followed by an ax far by other can form another word another now give me a dictionary consisting of many roots and a sentence you need to replace all the success and a sentence with the root forming it if success has many woods can form it we place of the whoop to show this length you need to help place the sentence after the replacement well example your prediction at this you have the sentence and any of this other thing okay I suppose I mean this seems like a really standard e try type thing yeah some of that is what it was where do we need a try or do can code they don't tell me where let's see told that ok so that is less than thousand just kind of thousand words okay I feel like we could actually I mean you could probably do a trifle optimization but I'm gonna try to deny you think for this and then see what happens let's see yeah I mean I still do something dumb ish but not to like I'll have one optimization hmm oh this is a list it's been to this just crystal - actors we need this way why set up I select do I guess so let's try that which my psyche I need okay I'll just put it out it's real learning lesson for me too and I bring mine every place it ashore this one wellies tell ya don't give us at least a prefix inferior you I would also say if I was like doing a competitive programming I probably just to deny even and worry about it later maybe I'm trying to figure out ways I could like things more concisely now what I expected actually not okay that's the one that before maybe I needed the other by sack well how do we expect okay some idea what's going on start with stopgap starts with a mammogram in our language tax is this you okay so that's good right sir cases also ones with multiple possible things okay Oh because it starts at cat so then it mrs. cat yeah okay that's what I get for being clever which man okay fine I just said it you is this fastener I guess we'll see okay well I guess it is fast enough it's a little slow right now you think it's good enough for the medium and it's good enough for me okay cool yeah I think the trickiest part about this one is kind of just having the confidence on the analysis on kind of bounds yeah since the entire sentence is gonna be less than a thousand characters you could get away of like n square things which is kind of yeah so as n square this open space what different end where it's just a size with dictionary of the universe and then just quite against queer look up ish roughly 4,000 that's okay and I ish roughly 4,000 that's okay and I ish roughly 4,000 that's okay and I think it's just ends up being an implementation poem after that after you have a lookup table yeah cool I mean this was a fun part yeah I might I've actually yeah I was good at I'm just thinking whether this would be a good difficulty on a interview and I definitely have actually seen that this one but very similar ones where it's like yeah given a sentence and here's like a mapping from a to b or list of mappings from A to B you know what is the new sentence look like wait so that's good so definitely I've seen those problems so definitely be prepared for that but okay I mean if you're prepared and you know this is very straightforward naturally why is a medium mmm maybe there's some clever algorithm well we want you to do I mean the less intense flowers to create a try but I didn't sir but that would probably make justify the thing on medium and temperature on an integral I would talk about your using a try maybe when to implement to try and you know you kept on end notes and that's how you know quick apart and you could and on download you could even terminate early because you know that you know you don't have to keep on checking to prefix this you know that when you look at the no there's no character anymore right so you don't continue in the next one
Replace Words
replace-words
In English, we have a concept called **root**, which can be followed by some other word to form another longer word - let's call this word **successor**. For example, when the **root** `"an "` is followed by the **successor** word `"other "`, we can form a new word `"another "`. Given a `dictionary` consisting of many **roots** and a `sentence` consisting of words separated by spaces, replace all the **successors** in the sentence with the **root** forming it. If a **successor** can be replaced by more than one **root**, replace it with the **root** that has **the shortest length**. Return _the `sentence`_ after the replacement. **Example 1:** **Input:** dictionary = \[ "cat ", "bat ", "rat "\], sentence = "the cattle was rattled by the battery " **Output:** "the cat was rat by the bat " **Example 2:** **Input:** dictionary = \[ "a ", "b ", "c "\], sentence = "aadsfasf absbs bbab cadsfafs " **Output:** "a a b c " **Constraints:** * `1 <= dictionary.length <= 1000` * `1 <= dictionary[i].length <= 100` * `dictionary[i]` consists of only lower-case letters. * `1 <= sentence.length <= 106` * `sentence` consists of only lower-case letters and spaces. * The number of words in `sentence` is in the range `[1, 1000]` * The length of each word in `sentence` is in the range `[1, 1000]` * Every two consecutive words in `sentence` will be separated by exactly one space. * `sentence` does not have leading or trailing spaces.
null
Array,Hash Table,String,Trie
Medium
208
4
Hello everyone welcome you for placement and in today's video lecture we will see medium you come offer you sorted are so return two are those two are we have to find the medium so basically we have two variables namas van and namas tu number van see can C D Length of D lms van is nothing but M And the length of D nams tu is nothing but N Okay, we have two lengths given, two mediums are given now undent The medium we have to get is date time complexity should be Oh people m + n time complexity should be Oh people m + n time complexity should be Oh people m + n ok oh people m + 1 and this we have ok oh people m + 1 and this we have ok oh people m + 1 and this we have time complexity given so you find out this you solve this medium of sorted you are like we have name van so we have two errors this First Hey Will There Be Something Like Let's Say Us First Aid 12 34 Okay End Second Hoga Date Kood Be Let's Say If I'm Taking Van Are You Find Out So This Error Kood Be Off Mode Like Lent Which Will Be It Kood Be Ours Which Its The length will be that it will be M plus N. Okay, I know this so basically we will combine these two and sorted are and form one and give from dose. If our length of D and is given, we will have 2 minutes a. Right if we have event find out d but just we know that we will just give the formula of median m+n/2 then we will get the medium but m+n/2 then we will get the medium but m+n/2 then we will get the medium but if we give that and we will get two numbers 2 and 3 like this In this case, here we have the length of D which is combined, we have two, so we have two numbers, so in this case C, you have to find out D average and then D median, it is okay, it is such a thing, so first what C Will do see will be just finding out d will you finding out and will be the median and if it is an event in date okay let's do this same you mirrors the medium of us find out the average and give us thoughts it so this is the thing for us Let's do it in the court and will see it works so in this case if I am going for this will give me the length of my second. So this is the second length of both of us together so it will be ours and it will be of our second length. It will be m plus okay till now no problem give in d next van we have to take three variables date is in equal to zero and in the form if our i &lt; name van end here we take so sort this New are in ascending order and sorted so date our new are found combined should also be in un sorted way so we will just put this in number van this new era is okay and here A will go so if our One is less and I plus doing values k plus if our will just check was if and it is and else od so if we in this case mode tu is not equal tu zero if this and not return m plus if and c will date if It is un and c will directly get d average and send out d result date is d median of median and if we don't have and then give c will be getting two digits so in date case it will be equal to these two variables 2 Will be will find c have you find out d average okay sorry completion error is just because of d naming conversion here our name van it is not number it is name van and c can directly keep this van a number it is name so thats all So let's see once we see you and the test cases so let's check the date console once 100% off the median offer you are sorted ok see you in the next video till then take care keep learning and do subscribe tu code For placement and do like this video thank you so much
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays. The overall run time complexity should be `O(log (m+n))`. **Example 1:** **Input:** nums1 = \[1,3\], nums2 = \[2\] **Output:** 2.00000 **Explanation:** merged array = \[1,2,3\] and median is 2. **Example 2:** **Input:** nums1 = \[1,2\], nums2 = \[3,4\] **Output:** 2.50000 **Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5. **Constraints:** * `nums1.length == m` * `nums2.length == n` * `0 <= m <= 1000` * `0 <= n <= 1000` * `1 <= m + n <= 2000` * `-106 <= nums1[i], nums2[i] <= 106`
null
Array,Binary Search,Divide and Conquer
Hard
null
54
hey everyone in this video let's take a look at question 54 spiral Matrix only code this is part of our blind 75 list of questions so let's begin in this question we're given an M by n Matrix and want to return all of the elements of the Matrix in spiral order Extensions by our order you start off at the top left hand side and then you go to the top right hand then you go down to the bottom right hand and then you go left to the bottom left hand and then you go up not to the same location but because we already processed it we go one location down and then the cycle basically repeats so and then we just return like the spiral order in the very end so on paint I have a another variation here so you can see essentially we would do something like this we go ahead and process this and then we would go ahead and process this and then we'll work backwards and we would process all of this and then we'll go up again process this notice how we're not going back to the start but one level beneath that and then we will essentially repeat the entire process again and so you will continue doing this until you're out of bounds or you have completed your Matrix okay so this question is actually not so hard once you realize how we want to Traverse right because that's the entirety of the question and if you really think about it like what are the things that we're doing right we're doing four steps we're going to the right we're going down we're going left and we're going up and if you think about it when I'm going to the right I'm not always going to the same location right like for example and the first time I'm doing it I'm going until this column over here the second time I'm going to this column the third time I'm going to this column so like the right hand side that I'm going it seems to decrease right the column seems to decrease similarly if you think about it when I'm going down the rows the first time I do it I go to the last row the second time I do it I go to the second last row and then third last row Etc and you can also see similarly that on the left hand side it's the same thing right so on the left hand side initially we go to the First Column but then the second time we'll go to the second column here and then to the third column Etc so if you've got to think about it those are the things that are changing right so to kind of put that in the code we have a couple of variables that we might want to keep track of and essentially what we can do is we can keep looping until I don't go out of bounds so what might that look like so what do the variables what my what might the variables be so in this case first of all let me go ahead and rename this to grid I like to keep this name grid but you can kind of see that we have four sets of variables right so we have the variable that kind of controls like this starting row here right which essentially like this left hand side it cannot like go over the starting row and then we have this variable here which contends contains like the ending column and you can see that when we're going to the right hand side we can never go like and reach the ending column then we have the this variable here that contains the ending row and if you think about it when we're going down we can never go past the ending row and then we'll we can also have something like for the First Column over here like a starting column over here and you can see that if we are going to the left hand side we can never go and touch the starting column we'll always keep going inwards so through some variables that we kind of have so homemade we Define these so first of all let's just go ahead and Define the rows and the calls which we always do length of grid and length of Grid at zero so that's the rows that's the cause of the Matrix now we have a couple of variables so the very top we have our starting row right you can think of it as starting row and this basically keeps going downwards right so we have our starting row and let me just maybe Define all of these and so then we have starting column and then ending row and then ending column okay so what is starting or starting row is the row that you start off from and you go until the ending row so if you kind of think about it starting over to ending row it will be from this row all the way to this row so in that sense kind of ending row here should actually be the last row which is rows minus one and the similarly for starting column to ending column you can kind of think of it as the starting column here we go all the way to the ending column over here so you can kind of think of that as starting column is zero ending column is calls minus one and really in order for us to keep looping or keep like going through our Matrix Aspire order we must have that the starting row is it less than or equal to the ending row and the starting column is less than or equal to the ending column so as long as we have this we can continue to Loop but if we ever let go out of bounds right like maybe let's say our array is like something like flat like this right then if I keep going to the right hand side and then I actually go out of bounds well in this case then I can go ahead and stop my iteration my for Loop or my while loop and it works the same way in like all four Direction maybe we go out of bounds here Etc so that's how we can go about doing this question now one thing I actually need to Define is my result variable here and I will just return result I guess in the very end right now what is the first thing I need to do okay so I have all of this and now let me go ahead and actually just remove all of this okay so maybe I'll keep this okay so what's the first thing we need to do well first thing is we actually need to Traverse the row right from the top left to the top right so maybe I can do something like top left top right and how do we do that well we know where to start off right like we're starting off at the starting column which initially is this column over here this is the starting column and this is the ending column and we're basically going to loop from here all the way to here so can I do I can do something like or Iron Range it will be for Iron Range starting column to ending column but actually like plus one right because we actually want to touch the ending column and so then I can add to Res these values which will simply be but what is the row well the row will just be I guess the row is like the starting row right the row is the starting row over here so starting row and on the column will be I will continue to do this now what do we need to do after we've done this well after we're done this after we've went ahead and processed this so maybe I can actually write it write my variables over here so this I can say this is my starting row and let me make it a little bit bigger I'll just write it again starting row this is my ending column this is my starting column and then this over here is my ending row if you think about this after we're done processing this first row over here then my starting column can move or not my starting column my starting row can essentially move down right because we've already processed all of this okay so we can go ahead and do that so what can we do now well now we can do from well we need to increase our starting row right so starting row plus equals one okay so now what do we need to do well now we need to go from top right to bottom right so we need to go down this path over here now you see can you can see that once since we put starting row over here then we would just go ahead and we will loop from this location all the way downwards so how can we do that well for Iron Range what will I start off at well I start off a starting row I will go to ending row plus one and then similarly I will go ahead and add Grid at what well what do the rows mean well the rows are I what about the column well you can see here that we're actually on the last column the ending column so here and a column and so that's basically it okay so now what so now we've process the right hand side and the left hand side or we process right and then we went down well now if you think about it this ending column over here we can move this inwards right because we've already processed this and then this we can move this ending column inwards and now what do we have to do is we have to go from ending column all the way to starting column backwards so how can we do that well that will be well first of all we need to decrease ending column by one and now we need to go from bottom right to bottom left so how can we do that we can do for Iron Range this will be from the ending column all the way to the starting column and I'll essentially do I think I need to do starting column minus one here and then minus one right the starting column minus one so we actually can consider the starting column and so now what will my res be well if you think about it my I here represents the row so what is my row going to be or my row it's just the ending row right it is the last row so I can keep that as ending row and my column will remain at I okay so now that we've done that we processed all of this we press all of this we process all of this now we want to essentially go up right now we want to go up now actually you notice here that like when we are going up here before that we have to actually have to move the starting column inwards by one because we have already processed so this part over here and so then all we have to do now is just go up from this ending row well actually it will be ending row minus one right because we have already processed this ending row so it'll be ending row minus one and then we will go to our starting row and we also move the starting column inwards and actually the starting column inwards I think it's already done um okay so it's not done so we have to do a starting column so move this inwards and what else do we need to do well we move the ending row upwards okay so ending row we decreased it by one and now you can essentially see here that we're modifying all four of these and so now what is the final thing we need to do final thing is from bottom right to top left and so how can we do this well it will be for Iron Range what do we need to put well it will be ending row right because we decrease ending row and then it'll go towards starting row so it'll be ending row to starting row uh ending row to starting row and again this will be in Reverse so I have to do -1 here but then basically here it'll be -1 here but then basically here it'll be -1 here but then basically here it'll be rest of the pen grid and so what will my row be here row will be I would want to column or my column will actually be it looks like it's actually still the starting column so I think I need to leave starting column over here and then I will move it inward by one so I will actually put this after this and so this will be starting column right we need this because when we're going up starting column is still over here so we need to process this and then we can move it inwards so now you can see we've modified all four of these and so essentially we will keep doing this until the condition breaks now one of the things we actually have to check for is that the condition might break after any one of these right like for example if the grid is just like one line or just like one dimensional just you know one row x amount of columns well then right after this we'll go ahead and break right like we can't even go down we can't even do any of this so what we can do is we can actually just check these conditions after all of the conditions here so we can do if any of this is true or maybe I can do if not this then let's just go ahead and break and we will continue to we will do this for all of these and I actually don't need it for the last one because after I do this then I'll check the while condition anyways but after we've done this we should break if we break anything and then we can return Reds in the very end so let's go ahead and run this now to see if I've made any mistakes go ahead and run our sample test cases I'll do it once more and let's go ahead and submit it and perfect we can see it works so what is the time here well we're just going through the grid ones right so it's basically the length of the grid times the amount of columns so it's o and m times n and for the space actually we don't really have a space here um so just constant space okay so that's this question thanks for watching
Spiral Matrix
spiral-matrix
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,3,6,9,8,7,4,5\] **Example 2:** **Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\] **Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\] **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 10` * `-100 <= matrix[i][j] <= 100`
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row. Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
Array,Matrix,Simulation
Medium
59,921
61
hi everyone before we solve this question today I'd like to thank you for watching finally more than 100 people are subscribed to my channel so for the first two months that was a tough Journey nobody subscribed my channel so but I keep uploading so now um I have a more than 100 subscribers so thank you for watching so let's get started so today's question is very simple but a little bit complicated because this is a linked list problem so rotate list so you are given head of a linked list rotate the list to the right by K places so let's see the example you are given like one two three four five and then k equal to so we have to rotate this linked list twice to write Direction like a one two so that's why output should be four five one two three so this four move twice like one and then so this for uh and reach at the end of a little bit so when this form over next so this will actually show up the first place of linked list so that's why output is like four five one two three okay so let me explain with this example like one two three four five and k equal to so first of all we have to know the position of um current uh head after rotating K times so in this case k equal to so just a rotated K times twice like a one two so this position should be a position of current head so like a in the end like a one two oops 2 3 for five so that's why output is like four five one two three so that's easy but what if K is more than a length of input linked list let's say um seven in this case also like a one two three four five six seven here but how can we know um so rotating K time after rotating K times or current hit reached to this position so it's actually simple there is a formula so k percent um length of um inverter increase so that is a position where current head should be moved so from this sample formula we get a regular zero so let's say this length of this input linked list should be five uh no seven um percent and five and uh two so that's why um in this case we have to make a move twice like one two so that's why this is a like a one two three four five that's how we can return like a four five one two three if K is more than length of inputting at least to get the length of input linked list so I create a dummy pointer initialized with hit so fast we iterate through all linked list with dummy pointer until dummy.next is with dummy pointer until dummy.next is with dummy pointer until dummy.next is no so dummy pointer.next has Twitter so dummy pointer.next has Twitter so dummy pointer.next has Twitter so move next and there is a data move next and there's a data move next and then there's a data moving X and then we reach the end of linked list so during the iteration uh of course we have to count so initialize with one and then move next and two three four five then uh after that as I explained earlier we calculate with this simple formula and then gets a position where a current head should be removed so now um head is here and the dummy pointer is here and we get the position two so what does this position mean so how to put these should be like four five one two three if oh by the way let's continue to discuss k equals seven after it's same as k equal to so in this case output is four five one two three so in this case uh we want to disconnect here then these two nodes go to the first two place here then and the rest of the first three nodes here go to the from like a solid position to fix function here so we want to cut this position um but how can we calculate the disposition so it's simple um links oops rings minus this position minus one so Y is one because if we stop this four like a one two um it's hard to disconnect this link and uh this node should be a new head node and uh this node should be a tail node and this node.next should be no so and this node.next should be no so and this node.next should be no so it's easy to handle uh the post case from this node so that's why we need to -1 -1 -1 to make program easier so in this case um length of linked list is five and at this position should be a 2 so -2 this position should be a 2 so -2 this position should be a 2 so -2 and minus 1. so which means two so now um okay we need a uh another pointer let's say um current pointer then move twice one two here and then um as I told you we have to uh disconnect this link but before that this node should be a new head so keep this node to like a variable and then um after that this current.nect next um after that this current.nect next um after that this current.nect next should be a new Messi and then um after that um we have to connect this blue area um before this letter here so how can we connect two areas so luckily um we have a dummy node here a dummy pointer here so pointing the five so that means this dummy dot next should be a um actually this one so which means a head pointer so that we can connect all nodes from like a new node so new node should be a full and uh next node should be five and then next node should be one and two and three after that we get a null here so yeah we successfully uh rotated the linked list with like a k brace yeah and this is a little bit messy very colorful but uh yeah 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 the code first of all there is a constraint about the length of input linked list like from 0 to 500 so that's why if not hit we can just hit after that um get the length of input linked list so ranks then this initialize with one and use dummy pointer in size with head and then start iteration so dummy nope next if we have a dummy.next then just move if we have a dummy.next then just move if we have a dummy.next then just move on NAMI dot next at the same time are the plus one to Links so press equal one and then after that calculate the position um so to disconnect like a link to list so position equal k percent ranks so this module should be a position where we disconnect the linked list and then but if position or for position equal zero in that case we don't have to do anything so that's why I just return head it's simple and after that um so we want to move um done until node I got before this connected linked list which means uh before new head node so first of all initialized current with head and the roof start looping or in planes and so as I told you the formula is like a length minus position minus one because we want to stop right before this um new head no new head node and then current equal current dot next and then after that we successfully stop the node before a new head so that's why new head should be a current dot next and then current go to next should be uh no so no and then as I explained earlier um we have to uh connect like a two parts so and do you remember like I left earlier and the blue area so as I explained earlier so dummy node is pointing the last note of um blue area in the uh previous explanation so dummy we have to dummy dot next we have to connect dummy dot next to head yeah okay that's it after that we got a new head so new head yeah so let me celebrate it yeah looks good and the time complexity of this solution should be order of n because I did it through all those here and then potentially I have deleted through all nodes here but the data is like a 2N so that's why time complexity should be on the order of n linear time so let me summarize step by step algorithm this is a step-by-step algorithm this is a step-by-step algorithm this is a step-by-step algorithm of rotate list step one if headache zero return head if not initialize length with one and the dummy pointer with head step two start looping to get the ranks of input increased step 3 calculate the position where we want to disconnect the nodes if position is zero then just return head step 4 iterates through until ranks minus position minus one after that new head should be a current dot next and the update current.next with no update current.next with no update current.next with no then connect two parts of linked list with dummy pointer and head yeah that's it I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
Rotate List
rotate-list
Given the `head` of a linked list, rotate the list to the right by `k` places. **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[4,5,1,2,3\] **Example 2:** **Input:** head = \[0,1,2\], k = 4 **Output:** \[2,0,1\] **Constraints:** * The number of nodes in the list is in the range `[0, 500]`. * `-100 <= Node.val <= 100` * `0 <= k <= 2 * 109`
null
Linked List,Two Pointers
Medium
189,725
437
hi guys hope you're doing great or today's question is pass some three so this is a new question that has been added on lead code and it's a really good idea to have a look at this question so you're given a binary tree in which each node contains an integer value find the number of parts that sum to a given value the path does not need to start or end at the root of will or relief but it must go downwards traveling only from parent nodes to the child nodes like that the tree has no more than thousand nodes and the values are in the range okay - of 10 lakh - plus of ten life okay so - of 10 lakh - plus of ten life okay so - of 10 lakh - plus of ten life okay so for example this is the given tree right and the sum is age so we want to find all the paths in the tree whose values sum up to eight but the only thing is that they should be traveling downwards right so for example here there are three such paths which have the sum equal to eight five and three so as you can see this is traveling downwards from five to three five two and one this is again travelling downwards and minus three and 11 which is again travelling downwards so we don't need it to like go through the root but yeah it should be travelling downwards and hence the answer that we should return should be three okay so we are going to use recursion in this because again this is a problem where we can break it down into subproblems and if we find the solution or answer to those subproblems for the child nodes we can actually build up that solution and find out the answer to the pin node and the overall answering so what we will be doing here is that yeah so since we are not dependent on the if we are not strict about including the road the path could very well also be anywhere in the subtree the only thing is this needs to be downwards so what we will do is the field take a list okay and let's say we will start from 10 so it's safe we are at 10 we first of all traverse the left and the right recursively and add that to the list okay so we add 10 to the list and then the left and the right and then we start traversing the list from the last element okay because we want to check that at any point if we reach a sum which is equal to the given target sum then that is one part that we have found right so that's why we will start traversing from the last so for example here in this case we will start in that list we will start traversing from 1 + 2 3 + 5 8 okay from 1 + 2 3 + 5 8 okay from 1 + 2 3 + 5 8 okay just as we find some 8 it means we have found one path and then we will add it to the final count okay and then we proceed so and once we have processed this node we would also remove it from the list because we don't want it to be a part of the list anymore we want the other paths to be present in that list right so we will remove it after we have processed it as a part of the recursive algorithm so I think we'll just get started and it will get better yeah so let's save our answers like them okay and we also need a saying an array list of integers right yeah we can just maintain a list of integers so we can made piggy maintain a list of three nodes but yeah we just need the values there so we can you just keep it an integer so just to spoil it anything you wanna list now with the path some right so we just have to maybe we just write a function call get some okay and to it will get give it the route at the Sun okay and then we can just return the count maybe let's see okay so let's implement this method now or to get some and it has got three node root and to scholarly tu some yeah okay so now in this first of all if the root is null yep okay now the return type of this will be void because we are not going to return anything okay so if it's null then he just returned first of all yep put it down right and otherwise we want to add this to the list right so you just I do not value to the list and then we yeah so and then we just call this get some recursively on the left and the right boat right so you just do a get some on the left okay and we do we'll get some on the right yep and after this we will just take my view and because we will start traversing through the list now so we only start from the last of the list because the path needs to be built downwards so we start summing up the values from the last element in the list and if while doing that summing up we find that there is a path which is equal to the sum that's required then we have found a path right so that's what we're trying to do you the typical for you okay and we just want to get the value at this point and we just want to add it to em right so we just store let's not get i right because we just have maintained or inserted the value in this value of the node so we don't need a dot value anything we just add it and then every time you add a value to the temp we just check that is my time equals to some right if yes then you found one path and we just increment count okay so once this is done we all we need to do is that we just want to remove the last element that is the one that we just added right now over here so we just do a remove and we try to get its size minus one so that will remove the last element from the list right okay and we have not written anything from this so it should be good and then count is a global variable so we just updating count and then we should be able to return the count from here as well yeah okay so let's see that works hmm oh yeah we need to provide it to some as well so it says that the inductions indexes minus one is going out of bounds we have mentioned just one why let's see okay yeah that works okay all right so this works and the time complexity is off n because we are using like they just traveling through the nose once but the space complexity is also of n1 because of the recursion and second because of the list as well right so yeah the time complexity and the space complexity for this question ro of N and I hope you guys find this video helpful if you do please like share and subscribe keep pouring and take you guys
Path Sum III
path-sum-iii
Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`. The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes). **Example 1:** **Input:** root = \[10,5,-3,3,2,null,11,3,-2,null,1\], targetSum = 8 **Output:** 3 **Explanation:** The paths that sum to 8 are shown. **Example 2:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22 **Output:** 3 **Constraints:** * The number of nodes in the tree is in the range `[0, 1000]`. * `-109 <= Node.val <= 109` * `-1000 <= targetSum <= 1000`
null
Tree,Depth-First Search,Binary Tree
Medium
112,113,666,687
1,921
hello and welcome to another video in this video we're going to be working on eliminate maximum number of monsters and in this problem you're playing a video game where you're defending a city from a group of n monsters you're given a zero indexed array of distances and speeds and so the distance is a starting distance from a monster for a monster away from the city and the speed is the speed of the monster and they walk towards it at their speed all the time and so you have a weapon that can shoot one monster and once it shoots it takes one minut minute to charge and the weapon is fully charged in the beginning you lose when a monster reaches a city and if a monster reaches a city right when your weapon is ready to fire that's considered a loss and you want to return how many monsters can you kill before a monster reaches the city so that can be all of them that can be none of them and so on obviously it's never going to be none of them because your weapons ready right away but let's kind of go over at these examples so in the first one you have three monsters that are 134 away at speed 1 one1 so your gun is ready at time zero so you can kill this one then your gun is ready again at time one so you can kill this one and then your gun is ready again at time two and so like it says you have enough time to eliminate all three because the first one takes one second but you can kill it the second one takes three seconds but you can kill it and the third one takes four seconds so in the second example you have two monsters that are both one away and then two monsters that are two and three away so here you can only kill one because once you kill this first one then the second one reaches the city at time one and your gun just recharged so you kill the first one then you lose so you can only kill one and in these third one so let's take a look the distances of monsters 324 you can eliminate the first Monster so you would kill this one right here and then the second one reaches the city at time roughly like 1.5 and you have time to roughly like 1.5 and you have time to roughly like 1.5 and you have time to kill uh do you have time to kill let's take a look um let's see this you first after a minute this so the monsters are all right so after a minute uh oh right so I misread that so this one will take less than a second to reach the city and this one will also take less than a second to reach the city because the distance is two and the speed is three so the time is uh distance over speed so the time here would be like roughly um 2 over three which would be like 2/3 of a over three which would be like 2/3 of a over three which would be like 2/3 of a second so essentially we can write this down so the time it takes for a mon to reach the city is distance over speed so for example if you're at four traveling at speed two it would take you 2 seconds right so what we first want to do is we want to take our distances and speeds and I'll kind of show you like a few ways to solve this problem and this is going to be the easiest way so we can take our distances and speeds and divide them to get all of the times for a monster to each a city so let's just say we have some number random array we have like one two three four five let's say and they'll have speeds like say like 54 3 2 one or something so essentially what we can do is we can get an array of times and then we can sort that array and then we'll kind of have like a way to know when the monsters will reach the city and obviously you're just going to want to shoot the monsters by whichever one shoes the city first that's other thing the problem is a little bit confusing it's not like they're in a line like a monster in the back can reach the city first so you might want to shoot that one first so essentially for an array like this let's say these are the distances and these are the speeds let's calculate how long this takes for all of these roughly so for the times so we have 1 over five so this one will roughly reach the city at uh 02 then we have 2 over four so roughly at 0. five and we have three over three so roughly at one and we have four over two so roughly at two and five over one so roughly at five so these are the times they happen to be sorted but you're going to want to sort your times right so you get some times you sort them and then you just simply go through one by one and you just figure out like when will my gun be ready so your gun is ready at zero so you can shoot this one and then you just keep going through the rest of it and anytime your gun's not ready that means you lose right so your gun's ready here so your result will be one then the next time your gun is ready is you add one so it'll be ready at one but here you already have a monster at 0. five so you lose right here let's say I didn't have these for example let's say I didn't have these two I just had these three times then what it would look like is you would shoot this one at zero right then your gun's ready at one then you come here and your gun's ready at one but the monster comes at two so you can shoot this one then your gun is ready at two and then you this monster comes here and so you are able to shoot this one so you are able to shoot all three and your three but essentially the idea is just get times sort them then just go through times and if gun is ready before the time then result + one before the time then result + one before the time then result + one otherwise fail and return result and the gun for the gun being ready so whatever the state it was so if the gun was ready at like one then you know if you shoot it then the gun is ready at one plus one and two plus one and so on right so it takes one second to recharge so you literally just go through all of them and then if you can shoot it update the gun to be ready at the next second then keep checking is the gun ready before the monster gets there and the gun has to be ready before the monster gets there and you just return the result so pretty straightforward that's one solution now another very similar solution is instead of getting this times and sorting you can actually get all of these times and then you can heapify so it's very similar almost the same code the get times heapify and then you just instead of sorting you just keep heat popping the minimum out of the times and you keep checking is my gun ready that way and so sorting would be n log n right but heapify is still worst case n log n but it might be a little bit better because you might break earlier we're sorting you're doing like all the work up front and even if like you fail right away You're Still sorting the whole thing but heapify to do the actual heapify would only be o of N and then you might like only have to pop like one or two elements so your actual practical worst case would be a lot better so those are the two ways of sort or heapify uh that you can like very easily do this where you just sort by the first Monster each your city and you just check one by one do I have time enough time to shoot this one if I do when will my gun be ready again do I have enough time to shoot the next one and so on so that's one way to do this problem now we are going to go through another way to do this problem it's actually better in theory but it actually has a worse runtime in lead code so let's go through that so the idea behind this problem is we're going to do a bucket sort and basically if you look at these constraints the biggest number you can have for distance and speed is 10 to the 5th and remember time is distance over speed so the biggest number we can have for time is 10 to the 5ifth right so distance would be uh distance would be 10 the 5ifth and speed would be one that's the biggest number we can have and notice that's about the same as the length of the array right so the time it takes to go through every single possible time is about the same length as the length of the AR now if this was a lot smaller then this would be a way better approach like if this was like a 100 this would be a lot better and if this was a lot bigger like if this was 10 to the 9th and this was really small then this would be a lot worse and I'll kind of explain the time complexity and why that is but essentially instead of sorting our times what we're going to do is we're going to actually create a hash map of time and the number of monsters that arrive at that time now this is a little tricky because you might think like well the time is distance over time and the problem is these can be like all kinds of decimals right like 1.89 of decimals right like 1.89 of decimals right like 1.89 2.76 how do I actually like there's way 2.76 how do I actually like there's way 2.76 how do I actually like there's way too many times to check here right if I just check manually time by time and so if you think about it let's say the monster arrives at 1.89 and the gun is ready at some time 1.89 and the gun is ready at some time 1.89 and the gun is ready at some time well because if when the gun is if the like let's say the gun's ready at two for example so if the gun's ready at two this would the monster would get there first right what if the gun was ready at one then the gun would be ready and if the gun was ready at three then this would be uh then the gun would be too late so no matter what we can actually take our time and round it up to the nearest whole number and then we can kind of do the same thing where if it's a tie between the gun and the monster then you lose and that basically so let's say the gun's ready at two that means that anything 1 to2 is the same thing right 1.01 to2 is the same thing right 1.01 to2 is the same thing right 1.01 to2 means the gun's not ready in time so any number you can just round up to the nearest whole number and it's basically the same comparison so we are going to get our times we are going to round them up and then for every single time we are going to check how many monsters arrive at that time so now that we have our all our times we can go through this whole array get a dictionary of time and number of monsters so let's kind of walk through maybe an example of doing that so let's say we have uh some times and kind of like what we're going to do so let's say we have uh some array so just have take some random numbers 2 4 One 58 with some speeds um of like say one two one maybe okay so let's get our times and then what we're going to do is we're going to actually remember we're going to round all these times up and then we're going to store the count of monsters that arrive at that time so in our times dictionary let's take a look so for our first time it will be at time two right distance over speed so at time two there is one Element at so that's this one right here at the second time what's the time here so the time is two again so now we have another element so we have two then we have one over one which is that time one so one there's one element this one here 5 over two which is 2 and 1 half but we round up so three there's one element and then finally at eight there's one element so essentially this will tell you like these are all my arrival times and I just want to keep track of like while I do this I just want to keep track of like what's the maximal time I got so I know that I got eight so I can just loop from one to eight you can maybe even keep track of a Min time if you want to it doesn't really affect it that much so if you want maybe that's like a slight optimization but essentially keep track of the maximum time and you're just going to say okay I'm going to Loop through all of my times now manually one through eight I don't know which ones are in the dictionary because I didn't sort anything but I'm literally just going to Loop through all my times and then depending on the number of monsters I'm just going to see how many times I have to fire my gun and what my result is so the gun is available at zero and the result is zero so let's kind of walk through what's going to happen here so essentially we're going to check for time equals we're going to Loop from time equals 1 to 8 and we're going to say okay well for the gun at one is there time is there a monster and how many are there yes there's one so that means for the number of monsters like let's say at one there were two monsters for example then we'd have to Loop this many times and see if we can kill them all or how many we can kill but in this case where there one but let's say there were two so we'd have to Loop two times so we'd say like okay well the first Monster like we'd have to see like how many we'd have to reload our gun and see how many we can kill that uh arrive at time one so we'd say like okay we can kill the first one for sure so this would be one and then my gun would be ready at one but now for the second one it would also arrive at one and my gun's not ready so I just return so essentially for every single key you just Loop value amount of times and you see like for your gun how many can I kill and if I can't kill all of them then I just return right away but luckily for us there was only one so we could kill it so we're going to kill it our gun is ready at one our result is one then we are going to check at time two is there anything and there is something at time two there are two monsters so let's see how many we can kill there so we're going to Loop twice so can we kill the first one so our gun is ready at one time and the monster arrives at two so we can kill that one now our gun will be recharged at time two and there's still one more Monster at time two can I kill that one well our gun's ready at time two and the monster arrives at time two so I lose right so I killed two total and I return so essentially you are let's write WR this down Loop from one to Max time for each key that we find or for each time that we find loop I times where I is number of value C how many we can kill by updating gun right so we're kind of like doing the updating gun kind of the same way where we're just saying like Okay our gun is whatever it was let's just keep updating gun see how many we can kill and then if we can't kill them all return when we can't otherwise go to next time right so we were basically manually looking through times and just checking if they are in our hashmap so we're not going through our keys because we can't go through our keys because in order for this to work going through our keys we'd have to sort our keys and then we're sorting so that's n log n so we're not sorting we're just manually going through like times one to Max time so we're guaranteed going through a sorted order but just a lot of times might not be there right like let's say one wasn't here and two wasn't here let's say these Keys weren't here so you'd say like okay I'm at one there's nothing here okay let's go to two there's nothing here okay I'm at three now there is a time and then you just keep track of like when your gun was last fired and your result and the idea is yeah so we just do this and this is better because to get all our times that's going to be o of n where n is the length of the array and then to go through our dictionary so how many keys do we have so we have o of M where m is the biggest time but if you look at these constraints if we scroll up the biggest time is like I said 10 to the 5th and for each constraint you have to Loop through some numbers but how many values are there total so the value the number of values there are total is o of n so it's O of M plus o of n would be the solution and so if this was like 10 5th times or plus 10 5th that would be the runtime here worst case where in the Sorting solution it would be log 10 5th times uh 10 5th so I know this was kind of confusing and like I said if you don't like this one you can just totally do this easy time sorted solution where you just get all the times you sort the times and you just go one by one is my gun ready before that time so that would be like the very or like the easy medium solution this one's a little bit trickier but just like I said especially if this was if this number was way smaller than 10 the 5th let's say the biggest number was like 100 or 200 this would be way better right because then M would only be 200 in this case they're equal so it's better but not too much better and then obviously if this was like 10 to the 9th this would be a lot worse so this depends highly on constraints which one's better the bucket or the Sorting this array here but I just wanted to show you something new um kind of rarely used algorithm so let's actually code this one up because I'm not going to code up the just a sort and going through the sorted times because that one's like really straightforward okay so we're going to get our times dictionary and we're going to get a Max time and we can even get a Min time if we want so we'll say Min time let's just say Min time let's make it like Infinity or something right let's make it Infinity our Max time will make zero and then we can sort from Min time to Max time so we'll say gun ready is already at zero and then we're essentially going to Loop through all of our distances kind of like we would to get all the time so we' say 4 I in range length time so we' say 4 I in range length time so we' say 4 I in range length distance let's say the time is like I said we're going to sealing it because if something is already at 1.8 if a if something is already at 1.8 if a if something is already at 1.8 if a monster arrives at 1.88 we can say it monster arrives at 1.88 we can say it monster arrives at 1.88 we can say it arrives at two and it would be the same uh it would work out exactly the same way so we'll say sealing of and this also ensures that our times you know we don't have like a billion times right if you have a whole bunch of decimal times you wouldn't be able to Loop through them so we're going to say distance over speed ceiling and then we're going to say if time in not or not in times so if time not in times if this is a new one then we'll say time equals 0 and then regardless if it's in there or not we will update by one now time plus = 1 and then here we'll time plus = 1 and then here we'll time plus = 1 and then here we'll say Max time equals Max of Max time and we'll say Min time equals Min of Min time and time okay so now that we have our dictionary of times and how many monsters arrive in that time now we're just going to man manually uh loop from Min time to Max time until we uh until we either get all of the monsters or we break some so we don't know where the times are we're just manually looping we don't know where the keys are we can't sort them because that would be slow so we're going to say for I in range Min time Max time + time Max time + time Max time + one if oh we do need to have a result yeah so we're going to have a result equals zero so we'll say if the result equals the and let's actually make another variable like D or something equals length of distance so if the result equals D that means we've killed every monster so we should just return and then if the time is not maybe we can call this like better name so we'll say for time yeah if time is not in times that means it's not in our dictionary so let just go to the next time so let's continue here and now we have to check how many monsters are in that time and for every single one we have to see can we fire the gun if we can we'll keep adding to the result if not we'll return straight away so we'll say for we don't need to use this in range times time for however many monsters there are in here if gun so all these monsters are going to arrive at time but we have to keep firing our gun and seeing can we kill it right so if gun ready is greater than or equal to time that means the gun's not ready in time so then we would have to return however many monsters we killed otherwise we will say gun ready plus equals one so we'll recharge it and we will add one to the result and finally we can return the result here so kind of to walk through this one more time essentially Max time and Min time are going to have the uh you don't really need to have these two like if you wanted to you can just loop from like 0 to 10 to the 5th but if your numbers are like way smaller this kind of saves some time essentially they're just going to be the constraints of the times we're searching for so every time we get a time we will say is it the m is it the Min time or the max time and this will make our this Loop uh run faster and so our gun ready is ready at zero and our result of monsters is zero D length of the dictionary so we get all of the times and we in we add them to the times dictionary so the times dictionary will have a time where a monster was killed and a count of all the monsters that were killed in that time and then we are doing ceiling just to make sure that we can bucket them into times because if you have something like 1.66 1.77 1.88 and so on you want to 1.66 1.77 1.88 and so on you want to 1.66 1.77 1.88 and so on you want to bucket all of those into a integer number and then finally we Loop through all of our times from the mintime to the max time and we say okay if we've killed every single Monster let's return if we if this time is not if there are no monsters killed in that time let's uh continue otherwise for every single Monster that was killed in that time let's see if I can kill it or sorry not killed but arrives at the time for every monster that arrives at the time can I kill it if not let's return the result because I failed if yes let's shoot and then let's update our gun and add to the result let's see if we have a solution we do so yeah I think this actually runs slower on Le code than the uh like sort easy solution just kind of funny so yeah it actually runs slower but in theory this is a better solution so uh so yeah let's think about the time and space for this one maybe run it uh I am curious also let's see if we just like get rid of these if it runs faster I am curious about that so if I just hard code like I think the max time is like 10 to the 5ifth so if I just say like zero 10 of the 5th or something this I have to get rid of this okay yeah so either way it's about I'm going to leave it um in here but in theory this should be faster in practice it's just about like the leak code tests so I think when I did the sorted solution um yeah I think this is like the sorted solution it was like a little bit faster but in theory this is this has better time complexity so it's just literally about the lead Cod test for so here we have o of n plus M where n is the length of the array and M is the maximum time I can have um and then the space is O of so it's just going to be o of n uh it's actually going to be o of M here so yeah it's going to be o of M where yeah this could be better um like once again it depend it all depends on what your time is and stuff actually is it o of M no it's not o of M because you will only store things that arrive at some time so I think this is actually o n still yeah I think this is oven because for every single Monster you count its arrival time but in practice it's going to be smaller than this because you'll have a bunch of monsters that arrive in that time so it'll be something like this um yeah and I think that's going to be all for this problem so hopefully you liked it and like I said it runs slower on leak code but in practice it's a better Sol or in theory it's a better solution so hopefully you did like it and if you did like it please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
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
191
lead code problem number 191 number of one bits so this problem gives us a unsigned integer and the goal is to return the number of one bits it has in the integer right so for example we have this long integer so there's only three ones so the approach will be to iterate through the numbers here and then if it's a one we get we plus one into our account otherwise we continue on right so my approach to that problem is exactly that but I'll be using some operations so let's talk about this uh 10% operator first so this basically 10% operator first so this basically 10% operator first so this basically means if I have let's say I have this and okay so if I were to apply the end operator here so what this end operator means is so what it means is if both of it let's if both of it is one then I get a one right so since both neither is one even if one of them is zero for example here this will become zero as well right so 0 Z and then this will be one so by comparing this with the with one so we know that in binary one would be 001 so this number is actually one two three four five this is five right so we know five and if we end this so this will actually give us uh one right because after using the end operator we will get one right even if the rest are ones as well we will still get one because only this is one what this means is there is a one in our current number the current bit that we are at right so if this was to be four for example so for will be like so this will give us zero and the resulting will be zero right so again if it's five there a one then we get a one so that's why you see here my count will plus equals to whether or not this number is a odd number right so if it's an odd number meaning there a one at the back if it's even there's no ones there's a zero then we don't then this will be zero so count will plus equal zero next we have this operator this bit shift so basically what bit shift is doing is so let's say I have this bits right and if I were to shift one that means I'll be removing this number right so I be shift one more time removing this number right like so there is also another one which shifts it to the left so it does the same thing I remove the bit on the left instead right so one more time again it doesn't have to be one it can be two let say I shift it to the right two times again so it will be one two and minus okay so one thing you should note when shiting bits is let's say I have this right if I were to shift it to the left by one so doing that it would be0 1 0 so this from one you become two right I sh it again so now this will become four right so and I shift it again then you become eight right one two three so you can also count it yourself like I have been because I'm not really that good in uh managing your bits but pretty sure is four Prett sure is eight right then it'll be 16 and 32 and so on so basically this what is doing is times two to the bits we have so same thing were to something from four if you were to shift the bits to the right by one Zer here then this will turn into two Shi it again turn into one and we shift it again then it will be zero okay so that's basically what these two operations are so let's go through the code so I have a count here something zero and let's say the integer we have is one11 right so while n is more than zero so right now n is the same as believe this is one two three four five 6 7 8 9 10 11 this is 11 by way the value of n doesn't really matter because we know zero would mean that it's all zeros so let's keep that so n is one11 so while n is more than zero which it is so count plus equals n with the N operation with one so in case this is a one right remember if you were to do this will give us a one right so count will plus one after that we shift the bits to the right by one ENT again this is still give us one two shift it again now this is zero right because right now this n value is two doesn't really matter in this case but it's a even number so there's no one here so we leave count as is and shift the bits and we reach the last one we get another one shift it again and now 10 is zero right there are no bits left in N so n is effectively zero and we return the count which in this case is Tre you can see it matches the output given in the example okay so this is a fairly simple question with a fairly simple and straightforward approach to this obviously you can do this without using the bit wise operations right you can just do and modulus to right and then here you just D equals two right obviously you can do this is the same thing but at the end of the day it's it is what it is okay so that's all I have to show thanks
Number of 1 Bits
number-of-1-bits
Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)). **Note:** * Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It 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 3**, the input represents the signed integer. `-3`. **Example 1:** **Input:** n = 00000000000000000000000000001011 **Output:** 3 **Explanation:** The input binary string **00000000000000000000000000001011** has a total of three '1' bits. **Example 2:** **Input:** n = 00000000000000000000000010000000 **Output:** 1 **Explanation:** The input binary string **00000000000000000000000010000000** has a total of one '1' bit. **Example 3:** **Input:** n = 11111111111111111111111111111101 **Output:** 31 **Explanation:** The input binary string **11111111111111111111111111111101** has a total of thirty one '1' bits. **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
Bit Manipulation
Easy
190,231,338,401,461,693,767
1,793
hello and welcome to another video this video we're going to be working on maximum score of a good subarray and this problem you're given an array of integers zero index and integer K and they tell you the score of subarray and this is a little weird the wording is defined as Min of num's I to J * Jus I + 1 and so a good subarray is J * Jus I + 1 and so a good subarray is J * Jus I + 1 and so a good subarray is a subarray where K is between those return the maximum possible score of the subarray and so in the first example they say the optimal subarray is this whole thing with a Min of 43 74 5 which is three and then the indices are 5 - 1 is three and then the indices are 5 - 1 is three and then the indices are 5 - 1 + one so essentially it's this subray + one so essentially it's this subray + one so essentially it's this subray here and in the second one we have to include zero so the optimal sub rate is 0 through 4 which is this one right here with a Min of four and length of five so that should be 20 Yeah so basically in this problem the way we're going to do this is we're going to figure out like what do we have to have and then how do we proceed and also note that num's n length is 10 the 5th so we can't have like an N squ solution so we have to have an N log in or better solution so this is actually going to be very simple once we figure out like the trick to it so let's just take some array like this one is fine so let's say we have 143 745 we can even add more numbers if we want to like 62 or something doesn't really matter and let's say that our K value so let's actually also draw out the indices here so this is index Z 1 2 3 4 five 6 7 and let's say for this array just to make it simple K is three and we have to figure out the answer so what we know from K is a good subarray K is between I and J and it has to be right so whatever we pick has to include K so if we know to include K which K is right here what we're going to do is instead of including K we'll just build out a subarray from K and we're just going to pick the biggest number at every iteration and that's going to give us the optimal solution so and then we're going to try it for these problems as well but let's kind of look how that's going to work so essentially what's going to happen here is let's just say we pick like we're going to have a left and a right they're both going to start here so we'll have in a left and a right we'll just draw these boundaries they're both going to start here so at first our value is just going to be you know K uh times the length of this uh of this array and the link of this array is just one element it's actually instead of drawing left and right we're just going to represent it with this blue line I think it's going to make it easier but we are going to have a value so the value is going to be seven right length one so now essentially we can either expand it by going left or going right and obviously to maximize K we're just going to want to always take the bigger value right because the bigger value we have a lower minimum so we're just going to say like do we want to go left or do we want to go right and in this case four is bigger than three so we're going to want to go right so what's the minimum here the minimum is four and the length now is two so then we have eight as our length so we have eight now instead of seven which is bigger so we're going to replace this seven with an eight now what do we want to take the five or the three well obviously the five is better so now we have length three and the minimum is four so now we have 12 which is better now do we want to take the six or the three obviously the six so now we have the minimum element is four and the length is four so now we have 16 which is better and now we want to take the three or the two we want to take the three the minimum element is three and length five so we have 15 so 16 is better so we're going to keep that now do we want to take the four or the two we want to take the four and now we have length six minimum element three we have 18 so 18 is better so we're going to replace now do we want to take the two or the one we want to take the two so we have two length seven so that's 14 so 18 is better than 14 and now we take this last one minimum health is one and 18 is better so essentially at every point we just figure out like what is the element that's going to make our array bigger and we just always take the greedy solution where like we always want to take the bigger element because let's say there is something down the road that's better so let's say we have something like seven and then maybe we have like some big element and some small element let's say but after the small element is something like or let's say actually let's do this let's say we have 20 so we have like 10 here and like 15 here like no matter what even if after this 10 we have some like good element and something and after this we have some really bad element like one and we start here we're always going to want to take the bigger one because we can always then pivot back and be like okay well this one's really bad so let's just take this one and then let's take this one right so because we can pick every time where what we want to take there's never going to be a case where we don't want to just be greedy and take the biggest element that's basically going to be the solution to this problem so let's kind of walk through these examples and let's get these so for this we have 1 143 745 and k equal 3 so 0 1 2 3 so this is the one we have to take now we're just going to write out our result and value so here we have seven now do we want to go left or right we want to go right so we have 4 * 2 which is 8 okay so we have 4 * 2 which is 8 okay so we have 4 * 2 which is 8 okay so we have eight now do we want to go left or right well we want to go right so we have four uh * 3 which is uh * 3 which is uh * 3 which is 12 then we can't go right so now we just have to keep going left so we have 3 * 4 have to keep going left so we have 3 * 4 have to keep going left so we have 3 * 4 which is 12 which is the same and we have to keep going left so we're going to take 4 and now our small El is 3 * 5 to take 4 and now our small El is 3 * 5 to take 4 and now our small El is 3 * 5 which is 15 which is better and then we have to keep going left no other way to go and that's 1 * 6 which is 6 so we did go and that's 1 * 6 which is 6 so we did go and that's 1 * 6 which is 6 so we did get our optimal answer and in this other one we'll just do that one really quick as well so we have five 4 five 41 one so we have to take this element here so our value is going to start at five we're going to increase now we'll have 10 we're going to increase our small element is four length three we have 12 it's better four length four 16 four length five 20 and now these are going to be worse right cuz it's going to be one length six 1 one so our best solution is 20 which is correct as well so it's literally just start at the middle or whatever K is and expand out and always take the biggest number first and that's going to guaranteed give you the best result possible so pretty straightforward maybe a little difficult to find but not too bad like it's reasonably straightforward once you realize I've take the middle element and then I'm just going to pick the best one every time okay so now we can code it up so we're going to have a result it's just going to start at nums K and then we need to keep track of like current minimum value so we'll start that at nums K as well then we have to have a left and a right and we'll start those at K as well and so the left and the right are going to represent like the left and right bound of our Ray now we just have to make a while loop to make sure they're both in Bound so while left is greater than Z or right is less than minus one and essentially the reason that left has to be greater than zero and not equal to zero because if left is equal to zero then we can't go left anymore right and if similarly if right is equal to l nums minus one we can't go left we can't go right anymore so we have to be able to go left or right so if left equals z that means we can't go left anymore or right is also valid so right is less than length nums minus one which means we can go right and the right value is better so nums right uh plus one right the next one is greater than nums left minus one the previous one so this is the case where we want to go right so we're going to take the right value and we're going to expand right and we're going to update our current Min to be the Min of uh Min of current Min and the right value we just took similarly this is going to be very similar on the other side essentially I think I screwed this up actually feel like I did all right we need an equal sign and we don't need this so now that we finish the left we have to do the right so it's going to be very similar so we're going to go left now and right if we're going to go left we're do left minus equals 1 and then this is basically all the same thing so current Min except we're going to compare it to left now and now we have to actually update our result right at the very end so we're going to say result is the maximum of the old result and current times the length of the array which is going to be right- left + one and going to be right- left + one and going to be right- left + one and finally we need to return and that's actually pretty much it so let's see if that worked and did and there we go and I can sub this a few times I guess but this is basically As Good As It Gets for this problem so this is um this is going to be like let's go through the time in the space for this one I guess so for the time this is going to be o of n because we are just literally looping through our array one time which is very efficient right like essentially we're just expanding out from K until we're out of bounds on both sides and for the space it's going to be a one because we just have some variables and yeah that's going to do it for this problem so hopefully you liked it not too bad of a hard problem definitely a lot of harder ones this week and this month so but yeah if you like the video please like it and please subscribe to your channel and I'll see you next one thanks for watching
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
1,239
everyone welcome back and let's write some more neat code today so today let's solve a problem from the daily challenge or whatever it's called we don't usually do that but maximum length of a concatenated string with unique characters we're given an array of strings and a string s uh aka a concatenation in this case is defined as basically a sub sequence of this array so let's just take an example this array down here a subsequence is basically just choosing a subset of the strings for example we choose this one and this one but we don't include the middle one then the string s is just going to be a concatenation of these strings uh maintaining the order of them right so u n and u e that's kind of what a subsequence is in this case but order doesn't really matter in this case at all but the thing that does matter in this is the concatenation of these uh you know taking this example u e and u n it cannot contain duplicate characters it has to be unique characters and in this example that's not the case right we have a u character in both of the substrings so if we could concatenate them together we'll have two of these characters so that you that doesn't qualify as a valid concatenation and so basically what we want to do is find a concatenation from this list such that the length of that string s is maximized if you know anything about subsequences in this case the brute force is you know for each subsequence or for each substring in this case we can either choose it or not choose it so we have two choices for each of these right we can choose it or not choose it all right two times two for however long this array happens to be in other words let's say n is the length of the array then the time complexity is going to be to the power of n so it's a very brute force approach if we want to actually get every single you know possible string s and actually that's how many string s's there are to actually build it is going to be however long each of these strings is right the average length maybe it's m or something like that so even though this isn't super efficient this is about as good as we can do for this problem so i guess the solution is actually pretty simple but implementing it might not be simple uh the main approach i'm going to be taking is backtracking recursively but there's actually multiple ways you can do this you can sort of use you know a bit mask to kind of come up with every single subsequence from this if you were going to use like a bit mask or just bits in general you know the main idea here is you know suppose in this case we have three strings right let's say x y z and we want every possible subsequence from them well a way a possible way to do that is just iterate through integer values going all the way from 1 or you could even start at 0 all the way to 2 to the power of n where in this case n is 3 because that's the length of our array here we would iterate from 0 to 8 and the reason is if i just draw it out it'll be pretty simple so if we start at 0 right 0 is basically choosing not to include this string not this string and not this string or we could do one which is this right we don't include these two strings but we include this one or we could do two right zero one zero include this one but not include either of these and we'd go all the way until we got to the integer value eight which i think is this and actually this is an 8 this is 7 but 7 is the last one in this case where we do include each of these three sub strings right so if you do that you'll obviously you won't have the binary representation necessarily you'll have the integer right from 0 to 1 to all the way to 7 in this case and if you actually wanted to build each of those subsequences right the concatenation of the strings you'd have to go through this integer which in this case is one and just go and basically get each bit from it and if the bit is zero you don't concatenate this portion of the string if it's a one in this case you do concatenate that so that's one solution but i usually try to avoid bit manipulation and stuff like that if i can avoid it so i prefer the recursive backtracking solution the logic is pretty much exactly the same we're still going to enumerate every single possibility but the uh backtracking you know the visualization is slightly different because we have kind of a decision tree that i'll be uh going over remember how i said for each of these strings on the left we can choose to include it or not include it that's basically what we're going to do as a decision tree right so we include the first string u n or we don't include it which leaves us as an empty string right so then the next string iq we include it right if we include it then we'll get u n i q and if we don't include it we'll remain as u n here if we choose to include iq we'll just have iq because in this case we didn't have any we didn't actually include the u n string right so we just have iq or we cannot include iq if we do if we add one more level to this i won't draw it just to keep it short but if we add one more level including this last string u e uh it'll basically give us all possible combinations uh that we can have and then we're going to look at each of these strings and then make sure that they have unique characters right in this case all of them have unique characters so we're going to return the length of the longest one in this case the length is four and that happens to also be the solution in this case on the left if you read the description of this so this is the longest the length of it is four and that's what we can return so without further ado now let's jump into the code so to save time i already wrote out the entire code but if you've been following our channel at all you know that we've solved a lot of backtracking problems we have a backtracking playlist and i usually solve them the exact same way because backtracking problems are very similar and this problem is no different we've solved many problems just like this one so let me walk you through the logic so i like to have nested functions you can see i have a function down here called backtrack i put it inside this function because then we don't have to pass in every single parameter so you can see out here i have a char set a hash set basically of the you know this is to make sure that we can ensure that we have unique characters right that's what this set is for and we don't actually have to pass that set in every function call because this function is defined inside of the outer function so with recursive functions in general we know that there's always going to be a base case of course the base case in this problem is if we you know have gone through the entire array basically if our index is now out of bounds then we can return what are we going to return though what value are we going to return we've created some subsequence right some concatenation and we reach the end of the array so we want to return okay of our concatenation so far how long is it right and there's many ways you can return that length the easiest way the way we're doing this is just by taking the length of that hash set right because this hash set will tell us that all the characters so far are unique and by taking the length we're just telling we're just saying okay this is how many characters we have so far in the concatenation right that's what we care about so that's what we're returning as the base case if we don't reach the base case then we still have some decisions to make right we have two decisions right one decision is that we include the substring at index i right you can see that's what this first if statement is about but this if statement looks complicated but it's not so we can make a choice of including this string at index i but we can only include this string at index i if it doesn't have any duplicate characters of the characters we have so far this char set out here defined out here tells us what characters we have so far in our concatenation so i also wrote a helper function basically that will tell us okay our current character set that we have so far and the new characters that we want to introduce do they overlap and when i say overlap i mean are there duplicate characters between them if there are duplicate characters then this if statement is going to evaluate false and we're not going to execute this statement because then we of course we're not going to want to choose to include this a string but if these are not overlapping then we are going to choose to add this substring to the concatenation and you can see that's exactly what i'm doing this uh for loop here is just going through every character in this array and adding it to the character set once they have been added then we are running our backtracking function saying okay we already made the decision at index i now let's continue backtracking starting from index i plus one and then we're storing the result of that which will tell us okay what's the longest concatenation we were able to create that'll be stored in this variable which was defined out here and then we're basically doing our clean up from the backtracking right we added all these characters now we want to remove them because we don't want these characters to be included when we make our next decision which is on the following line but this logic is important and i basically brushed over this overlap function i defined it as a helper function just to keep things organized but you can do it however you choose you can see i kind of have a pythonic way that i did it but i also have the commented out basically you know the more manual way of writing it out if you prefer that you know we could do it either way depending on what the interviewer would want and whatever you're comfortable with but the logic of this overlap function is important because there is an edge case associated with it we want to count the occurrences of each character that we've already have before adding this uh string s because we want to know does this string s and the char set overlap so we want to make sure every character included between these two is unique and how i'm doing that is just saying that the count of each character cannot be greater than one if it's greater than one we return true indicating that they overlap if it's not greater than one that means they don't overlap but one thing you also have to make sure to remember is the string s itself here could even have a duplicate right like maybe our char set so far is empty right it doesn't have any characters included yet but the string s does not overlap with the char set right it has maybe two b characters right this means that s is not overlapping with our character set but the string s itself has duplicates right it has two occurrences of b so therefore if we add it to our concatenation then it will not have unique characters so this will evaluate to saying yes that they overlap that's one edge case that i actually missed when i was coding this problem this morning so that's explaining the overlap function and getting back to backtracking remember we had two choices i went over the first choice where we do include the string at index i of our array the next choice is if we do not include it and it you know calling that is the exact same we're just calling backtrack at index i plus one just like we did at this line the only difference is when we call this function our char set will not have any of the characters from the string at index i right because we did that clean up before we call this function but once we call this function we want to take the max of it and the max of our result so far right which could be 0 or it could be some number from this line of code if the if statement does execute and we want to take the max that and then return that and that is the entire code of course we have to call our backtracking function starting at index 0 the beginning of the array and then just return the result of that and by the way you can see this code for yourself using the link in the description if you want to do that and so i'll run this just to make sure that it works so it runs quicker if we actually comment uh this and then we use this portion so i'm gonna do it like that but it works in both cases i guess it's about if you want short code or if you want more performant code but it works in both cases let's just run it to make sure that it works and as you can see on the left yeah it's pretty efficient so i hope that this was helpful if it was please like and subscribe it supports the channel a lot consider checking out my patreon if you would like to further support the channel and hopefully i'll see you pretty soon thanks for watching
Maximum Length of a Concatenated String with Unique Characters
largest-1-bordered-square
You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**. Return _the **maximum** possible length_ of `s`. A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** arr = \[ "un ", "iq ", "ue "\] **Output:** 4 **Explanation:** All the valid concatenations are: - " " - "un " - "iq " - "ue " - "uniq " ( "un " + "iq ") - "ique " ( "iq " + "ue ") Maximum length is 4. **Example 2:** **Input:** arr = \[ "cha ", "r ", "act ", "ers "\] **Output:** 6 **Explanation:** Possible longest valid concatenations are "chaers " ( "cha " + "ers ") and "acters " ( "act " + "ers "). **Example 3:** **Input:** arr = \[ "abcdefghijklmnopqrstuvwxyz "\] **Output:** 26 **Explanation:** The only string in arr has all 26 characters. **Constraints:** * `1 <= arr.length <= 16` * `1 <= arr[i].length <= 26` * `arr[i]` contains only lowercase English letters.
For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).
Array,Dynamic Programming,Matrix
Medium
null
766
hey everybody this is Larry this is uh date 31st the Halloween episode of the Nico day challenge hit the like button hit the Subscribe button join me on Discord oh trick or treat 10 Bitcoins uh yeah hit the like button hit subscribe and join me on Discord let me know what you think about today's Vlog so today uh it is Halloween in the states I don't know whatever celebration uh so I am a gingerbread dude gingerbread Larry you know uh the same as the icon I guess but you know hello I am gingerbread Larry I don't know uh we just have to be here I guess uh it is very hot in here uh so we'll see also you can see the header Loop and maybe I don't know that looks way creepy hello everybody I am a gingerbread dude okay anyway that's enough uh let's do today's file um yeah today's Farm is 766 toprates smell your tricks hope I'm saying that way you have an M by n Matrix return true with the topaz topitz uh otherwise return Force how do you pronounce toe points let me it why did is there a one minute video on this hang on German tablets third bits third pits German tablets triplets okay today we learned something new not gonna remember next time though so maybe another time okay so a matrix of every diagonal from top left to bottom right has the same elements what does that mean one two three five nine and four okay that seems pretty straightforward uh does it have to be from top left to bottom right It's Only One Direction and The the thing that I always do I know that if you're well practiced you could probably memorize this right but you have zero and then it goes to one and then two so of course this is just if I is equal to J or I minus J right or x minus y is how we're going to index it by um yeah and we can probably do it in a couple of ways like for X in range of R for y in range of c and you can if you're really uh if you really try you could probably do it in a one-liner but I am lazy do it in a one-liner but I am lazy do it in a one-liner but I am lazy I'm too lazy to make this any shorter put it that way and then here um how do we want to do it right so if Matrix of X Y is equal to let's say the top row version right so I was going to debate also doing a set but we can do it this way so here um let's see how do we want to think about it so it is going to be so what did what is the X element right X element is just going to be x minus y element and then the Y is oh well it's just gonna be zero well okay the first of all is going to be there and then this is going to be this right uh and this is not the case then this is going to be false and then otherwise return true I think that's pretty much it um I might have gotten some of the indexes wrong is very easy to get at one but conceptually oh I see what's happening here is that so this is going to be good for um in this case the one two three and four but the five and the nines are probably doing that's wrong that kind of confirmed this because I think I didn't do it that way um yeah maybe we can um we can probably just split it up so yeah five is what it prints so we can probably just straight up in two cases which is that if Y is greater than or equal to X uh then we do this otherwise if x is greater than or just strictly and Matrix of X Y is not equal to in this case now we want the First Column and then you have x minus y uh return false right maybe those are the two cases if I could do it in a slick away but I'm gonna do it this way uh looks okay in the two cases but that you know that doesn't mean anything it's just too small of a whatever but I am lazy so I am lazier than I am whatever so let's hopefully for good and yes uh apparently I did this three years ago almost uh oh October whatever badge nice um did it oh I did it the other I did the loop the other way I guess that makes sense too but yeah um cool I mean this is going to be linear uh well yeah it's gonna be linear time that uh constant space uh when I say linear of course I mean that it is going to be the size of the input which is R times c um so or M times n depending how you want to say it but that is linear because that's the size of the input and you have to look at everything once that's pretty much all I have though so let me know what you think um we don't use any extra space other than like you know a couple of variables so yeah let me know what you think um hope you y'all have a happy Halloween that's you know do the next month strong and let's get it going well with 944 today Street going and I am sweating like crazy so I'll see you later stay good stay healthy to good mental health I'll see y'all later and take care bye
Toeplitz Matrix
flatten-a-multilevel-doubly-linked-list
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._ A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements. **Example 1:** **Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\] **Output:** true **Explanation:** In the above grid, the diagonals are: "\[9\] ", "\[5, 5\] ", "\[1, 1, 1\] ", "\[2, 2, 2\] ", "\[3, 3\] ", "\[4\] ". In each diagonal all elements are the same, so the answer is True. **Example 2:** **Input:** matrix = \[\[1,2\],\[2,2\]\] **Output:** false **Explanation:** The diagonal "\[1, 2\] " has different elements. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 20` * `0 <= matrix[i][j] <= 99` **Follow up:** * What if the `matrix` is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once? * What if the `matrix` is so large that you can only load up a partial row into the memory at once?
null
Linked List,Depth-First Search,Doubly-Linked List
Medium
114,1796
229
Jhaal Hello everyone in this video will see the question that is maturity element to end win T20 video bhi har saal tak hai that was similar toss maturity element 125 suggests you have cent soldier question so I will suggest you to solve this question objective question for husband Calls it is the best politician and a guy likes her will be impatient will be us has force intelligence Roshni most of all you to water will appoint Arvind shift so let's get into this question to it's meaning of question agency and active in the interior of science in This Will Help You Find All The Elements Setup Per Month In Three Times As Floor Value In This Question Well And Want To Times When Most In The Amazing Or Diploma In Elementary Schools Like And Share With You A Friends Or Spirit And Violence In This Being Added To Be Environment And White Fitted To Inger A Great You Pension Approved C Tabs Classes Give 120 Filter Element Which Is Yes Monitor Dentist Hind Size Paste 2068 Wife Bj Subscribe Element Which Is Beach Mode On Instagram And Cases And At Times Internet Questions In The Given There Must be given may switch off the mode of the element in the interest of elements of death and the can consume more near china puja treatment suicide note police station and how will post on this question friends this last interview suicide in no interview with this Question is will have to off and lag UFO subscribe and subscribe the Channel and Aki Narula for every element and subscribe button adhi0 plus 2 and every element which we can do you do subscribe and subscribe our element and subscribe Guru and its complexity yet off But Not Sure Thing Viewers Keeping The Conflict Which Will Have To Find For Android 3000 Interview Laxative Optimized Raw This Question Adheesh Udayveer Way To Like This Question Is But This Note's Value Key Elements Of Obscuritism Note These Subscribe Our Channel Subscribe This Video Give 182 Acid was less than this point tree students of will and live with settings her loud letter and spirit times when they can edit ult ₹10 real ko of and when they can edit ult ₹10 real ko of and when they can edit ult ₹10 real ko of and powerful login time according to were and is stable in r languages ​​issues to and this stable in r languages ​​issues to and this stable in r languages ​​issues to and this context e Will Also Increase Co Se Zinc Festival Loot Gayi Schiff And Poor Pardes Me Butter Dash Lucknow Interview Kunwar Optimizers Complexity For The And This How Time To Mix This Text Message To Off And So I Will Let You To Like For The Question More Efficient Hi Sunavai Withdrawal to su ko switch from here so after every situation will keep checking the lid and return suno let's get into the land of surakshan approach which where scene or center visit element to problem hai to is par you have and secret video episode 202 whatsapp video hu This The Means of Tenses Algorithm Is That Video Link Website How They Can Solve This Senior Liye Balwant Space Suit Debit Unmute Hairs For Him Fijul Mein Puri When The Will Invitation For This Is Amazon Maturity Elements Who Will Increase M2 Posted In Fact Sutak Hunter To 1000 Episode Vanshi 250 Small Element and Possibly Be Amazed at Most 220 Treatment Se Zing 125 Whammy Note Element to End Quantum Computer Online Quiz Question Give One Variable and Like and 8.2 Phase Subscribe User's Se Percentage Tax f-18 Subscribe User's Se Percentage Tax f-18 Subscribe User's Se Percentage Tax f-18 Mix of All Languages ​​Use Zoom Jis Mix of All Languages ​​Use Zoom Jis Mix of All Languages ​​Use Zoom Jis Elements Of This Element At Index Regret For Every Element In Edits That This Element Is Due To Maturity Element 120 Presiding Officer David FlashLight Of World First Avenger More Than 150 Subscribe Shyam Jis Vishwas Video Ko 2018 19 2012 Subscribe Like And Subscribe This Acid Band Ajay Devgan Juban SMS Jo Treatment and Increase Se Kaun Classes Current Affairs Us Vagya Us Gas Ko Medium To Interest In The And Values ​​Will Come Into This Element To And Values ​​Will Come Into This Element To And Values ​​Will Come Into This Element To subscribe to the Page if you liked The Video then subscribe to the Page Five End Values ​​Issues Difficult to Follow This Five End Values ​​Issues Difficult to Follow This Five End Values ​​Issues Difficult to Follow This Particular Sector and Weakness Element 2012 Tabs Account Solution Note Directly More Questions Will Depend On Facebook Twitter And Suddenly Started Beating The Counter Se Zinda Corpse What is the Mutilated Note See The Same To The Inventor Pear On Shul Simple Department Contact Details Contact You Know Video Come To Liye Earthquake Hans Evolved Maggi Hybrid Traction Hacks Pallu 2361 Speed ​​Come Tourist Kallu Sunao Pinch Ek Kaha Speed ​​Come Tourist Kallu Sunao Pinch Ek Kaha Speed ​​Come Tourist Kallu Sunao Pinch Ek Kaha That Yashwant Problem Example Of Wave Subscribe Now To Receive New Updates Reviews And News Problem Is Frequency Lallu Is Notification And Not A Good 2012 Encounter Voice Note 0 Green Village Spot Switch Simply 2000 A Specific Mr Account 240 I Will Come To The Point And You All End Activities 709 Is Fever Remedy 22222 Subscribe Now To Receive New 2018 Don't Forget To Subscribe New Elements Which Element Subscribe Nor Will Again Autumn Fun Listen Vacancy Eye Edit Footer Maximum Induced Election Beach Twitter Answer Su At This Time 28-12-2011 Loot Twitter Answer Su At This Time 28-12-2011 Loot Twitter Answer Su At This Time 28-12-2011 Loot All Teachers Is It Is The President AND NOT A HOBBY CLASSES MAINTAIN DUAL SIM LEADERSHIP CONFIRM DATE FIX LAG IN R NOT DEPEND ON THE COUNTER INSTANCE MERGE FROM ACCOUNT ONE AND ACCOUNT TO AND WILL COUNT AND SENSE OF THE BEST UNIVERSITY COURSE WILL LEARN TO CARRY AND WILL COUNT HOW MANY TIMES BY MAKING MORNING August 2002 Away With Three And Workers Of Maturity Element Worker Seats Election Topic Which 020 Thin More Test Super Difficulties Adversities Cases Have Got 1st Element In This Is An Answer Final A Victim Part-2 Result Are And Samsung A Victim Part-2 Result Are And Samsung A Victim Part-2 Result Are And Samsung 1222 Basically An Interest In This Algorithm Voice -guided Wishes Viewer Algorithm Voice -guided Wishes Viewer Algorithm Voice -guided Wishes Viewer Welcome to Your Traces Factory These photos are written by CEO Vikram and author Ult Window Something Kaise Andheri Ye Kaise Edison Particular Like Wind To ABES Manorath Element Ko See The T-20 Cancer 9th May Element Ko See The T-20 Cancer 9th May Element Ko See The T-20 Cancer 9th May Attainment Of 108 Elements Cancel 5 Minute Element Morning Placement The treatment is sent in the election Duty World Editors Smooth in this time it will come in sir neck centers or pardon particular shifted in the water cooler window improved maturity element near favorite 20 minutes misser and of the rhythmic quality element will cause and effect the inheritance mitthu Improvement The Counter Affidavit For Treatment Counter For 10 Minutes Anil Increment To Its Value Shoulder Singh Vacancy Reduce Induction C Prithvi Canceled Decade Hair Defective Point To Cancel The Counter Ofton At This Point But Again And Want To Work Harder This Servant He Guys Want The Like Reserve Bank of Baroda Mode That Time Sonth Meher Mode On Amazon President YouTube Strokes And Slave Mentality And Attainment Of Aggression To That Statements Of Witnesses In The Circulation And Left Side Per Code And Exit Poll Report Anjali Ko Doli Swami Vishnu Lots Of Patience And Definition And Not Court You Can Refer To The Description Inquiry Area To Trample Videos Adaptive Sweet End From Where For Any To Default So Let's See How Will Give And Factors Of Numbers Simply Return To This Mystery After This Is Why One Should Sacrifice In Thanks Sentence Last 20 Minutes Yaar main chhoti element to infection account village to celebrate inquiry system you can see in c plus lut singh sisodia editing and visiting this is great epic is good for atleast one week and preventive and contain all what is same to the should kishore and you can see PCOD Election Will Set Counter Welcome To And Who 205 The Computer In The Number Of Incident Is Mitti Screen Shift Animated Images In This Instrument And Give Them Into Excel Data Is 2012 And Will Check The Code One His Great Grandfather And Debit Or Size Peth Three Cases Of Activa E Think This Should Be Performed On Maturity Elements Will Simply Year Later This Way Loot Result Addiction Photo Jhalar Mist On Twitter Account Admintools University Result And Written Words Just Pure To Death Sentence Difficult Is This 10 Minutes And Her Emphasis Attach Sentence Active To Close Loop Withdrawal Versus Observations and But Replacement Balance subscribe 98100 subscribe The same Name of The Amazing spider-man 98100 subscribe The same Name of The Amazing spider-man 500 to 1000 subscribe The Video then subscribe to subscribe our YouTube Channel and subscribe the Channel Please Share Thank you
Majority Element II
majority-element-ii
Given an integer array of size `n`, find all elements that appear more than `⌊ n/3 ⌋` times. **Example 1:** **Input:** nums = \[3,2,3\] **Output:** \[3\] **Example 2:** **Input:** nums = \[1\] **Output:** \[1\] **Example 3:** **Input:** nums = \[1,2\] **Output:** \[1,2\] **Constraints:** * `1 <= nums.length <= 5 * 104` * `-109 <= nums[i] <= 109` **Follow up:** Could you solve the problem in linear time and in `O(1)` space?
How many majority elements could it possibly have? Do you have a better hint? Suggest it!
Array,Hash Table,Sorting,Counting
Medium
169,1102
409
That in this problem when suffering and virat yudh characters of latest information rom subscribe button for using the giver subscribe related to which is the longest born subscribe our channel and subscribe this video plz subscribe kare the sweep series report times you can see a proof tense Switzerland This Is Ringtone Times Also Remove And Syringe Four Times And Injuring Two Times In All Its This Velvet So Before Android Hanif Two Types What Is The Length Of The And Length Ki Sudhi Possibilities A Villain That Us Like This A B C D Khayal Center Will Brave Chief Water Will Change Its ABC Lead Or One More Subscribe And Central Character Ki Ambulance CBI J Show What Is This What Is The Take Away From subscribe this Video like Share and subscribe the Channel subscribe our And All Players Are CR And Here Na Account Of All Character Series Win In Hair Vice President Hair Subscribe A Cream Even Number Times A 's Birthday Riya Central Character Artist 's Birthday Riya Central Character Artist 's Birthday Riya Central Character Artist Weaver Times Swift This Cut Hair Including Morning Hair Oil Suzy Bring Two Times In The Center Three Times All The Actors Will Be Given So All Players If And Even Number Of Times That And One Character Central Character Workers And Number Of Times I Surat Will Oo Will Keep A Map Person Balbir Will Continue To Solve There Kabir Wikinews All Characters And Even If That Is Tree Alert System Character By Doing This Number Times It's A Tough Times Be Crush Six Times By Learning Three Times And Makes One Time Chief Will Take Everything 200 Divider Mikoli Two In Decided In This Site Has Been Decided In This Site Nau Huff Us Chapter Number One Can be no like or comment pick one up the Video then subscribe to the Video then main entry of share that and all rate factors including episode number times remove and subscribe doing all events aplus that function of all old accounts - one will refer from each of all old accounts - one will refer from each of all old accounts - one will refer from each And Justice Appointed Swiss Roll Number One Neck Blouse Key Central Railway Central Subscribe Is So All Even Content Baby Text All Old Accounts vfx1 From His Side Amit Khuli 100 Years In Alarms - 118 Subscribe 2018 Live From Wall And Length Every One Will Be Conditional This will depend on weather any character of doctors printer not formally be sworn in at least one count subscribe The Video then that Anuvivagha to Seervi and Dir and that dish to so just Mandi Sudhijan Dash to take care and subscribe our from 0 to Be doing so will totally 98100 what is the 2nd id m id dc subscribe and subscribe ki electronic producers kar do hua hai kar do ki surya account maps ready nobody will do result will 202 ki and wool mode on morning 5252 ki and wool mode on morning 5252 ki and wool mode on morning 5252 this Vitamins Tubelight 119 Happened I and Boys Have Swiss Bank Account Sudhir Person Minute Festive Active Interest in Judging Account And This Any 0 Prohibition Edit Voice Mail CBSE Board Money Lord From Which Comes True That End Result Plus Equal To Also Subscribe Vanshdhar Tweet One all maximum possible even after rans and finally e that is and phone is dumb v81 a hua hai according to shani se accepted to sudhar time complexity hai software testing and actor and input singh sudesh mix ko finish the number question district governor this is for the Number Of Units Tractors Dividend And These Weak Only You Need Character Certificate Unit Character Questions Page One End Time Evolution Nor Will Do Something In Java End Item And Then This Dish Character Winning Start For The First Time Daily Twitter's Default Value 104 The Effects Already Present Minister Of State Bank Account Add 125 Increments Account And Estimate Result Is 90 Tomorrow Morning Just Interested In Values ​​And Tomorrow Morning Just Interested In Values ​​And Tomorrow Morning Just Interested In Values ​​And They Can Get Good Turing Values ​​That They Can Get Good Turing Values ​​That They Can Get Good Turing Values ​​That And This 2016 Sunny Deol Sex Updated On Following Five Minutes Seconds That Nor Will Write The Same Thing In Python Hua Hai Improved Value Second One Account Do That Sudhanshu Raw Milk 0 Ki Bone Mud Share Investors Updating Account This Account C Yesterday Morning Getting Addicted To Win But They Are Not Getting Down In Problem Nine Wickets Installation Instructions for International
Longest Palindrome
longest-palindrome
Given a string `s` which consists of lowercase or uppercase letters, return _the length of the **longest palindrome**_ that can be built with those letters. Letters are **case sensitive**, for example, `"Aa "` is not considered a palindrome here. **Example 1:** **Input:** s = "abccccdd " **Output:** 7 **Explanation:** One longest palindrome that can be built is "dccaccd ", whose length is 7. **Example 2:** **Input:** s = "a " **Output:** 1 **Explanation:** The longest palindrome that can be built is "a ", whose length is 1. **Constraints:** * `1 <= s.length <= 2000` * `s` consists of lowercase **and/or** uppercase English letters only.
null
Hash Table,String,Greedy
Easy
266,2237
3
hi this is josh from late dev where our goal is to explain lethal problems as simple and concise as we can today we're going to answer the question longest of string without repeating characters in this video we'll learn another crucial algorithm that we'll be adding to our tool set that will come in handy in cracking your next coding interview so without wasting any time let's get started given a string s we want to find the length of the longest substring without any repeating characters what this mean is for example given this string right here you have an output of three and the answer is abc well alternatively it could also be bca as you can see there's another b right here which would be a repeating character and also c a b is also another valid answer and another one is a b c that's why we have an output of three in example two we have a string of b's which would give us the longest substring of b in example three we're given this string one thing the example tells us is that the answer is w k e with a length of three and pwke which is pw ke is not answered because it is a sub sequence and not a substring so we only want continuous strings which in this case is wke and of course in example four were to admit an empty string which would give us zero makes sense so let's figure out how we can solve this problem the first way of solving this problem is to use a proof board strategy we can check every substring to see if they are valid and we'll keep track of the longest string we find for example we start at i at a and then we have j and we just check every substring as we iterate through our string a b abc aba and so on and so forth and we would check everything of these substrings using a set to keep track of any duplicates that we encounter if we don't encounter a duplicate in the string then it is valid and we keep track of the length of that substring to be our max value otherwise we skip it and we continue searching alone this would give us a runtime of o of n cube because we need to scan through all the i elements which is of n and for every i element we scan through another o of n j element and then finally to check all the substring in between i and j we need to do another scan which gives us another o of n so of n times o of n times l of n gives us om cubed the space time complexity of the solution would it be o of n because worst case scenario we need to store all elements inside the given string now all of n cubed is pretty big so let's see if we can do better as mentioned before unfortunately having a of n cube solution just won't cut an interview you'll get asked to see if you can do better luckily we can and we can't by building it from our naive solution instead of checking each substring to see if they have unique characters we can actually just move that set up and use it as we build our string for example instead of checking if the substring abc is that is unique we can just build that set while entering through our j loop and then when we move to abc a we just check to see if a is in our set and if it is we break from our j loop and move our i index to the next one and repeat the cycle this will save us of n because we no longer have to scan through all the substrings between i and j another optimization that we do is as follows another optimization that falls is notice that when we find our first duplicate for example when we get to abc a we would start over and we would move b over here and then we would start our nested for loop over again checking the substring b bc bca well in this example we don't really need to start our j over we already know that there are no duplicates for our next i value up until j so instead of starting over if we can just contain where we left off this would help us save another o of n runtime and this is the intuition behind the sliding window algorithm the sliding wind algorithm is an array algorithm that uses two pointers to keep track of a range that meets a certain condition in this case our condition is that our substring has unique characters when our condition is true then we move our right pointer until it is no longer true and then when the condition is false we move our left pointer until the condition becomes true and we continue doing this until we reach the end of our array one powerful benefit of using this is that we can skip making redundant checks to every substring when we know they won't work bring us from a of n squared runtime down all the way to a o of n runtime that's powerful now let's go through a quick walkthrough of our example with the sliding window algorithm now back to our example problem we're going to use the sliding window algorithm remember our condition is that our substring has unique characters if our condition is true we will move our right pointer which is j until our condition becomes false which then we move our i pointer until the condition becomes true again we have a set that we will use to store all the unique characters that we encounter identify if our condition is true or not and of course we have an answer variable that will store the length of the longest substring without repeating characters so to start off we have i and j currently our set is empty so we have a substring of unit characters so we will move our right substring we have we are at index 0 and we have a so let's add a into our set and because a is as unique characters we will continue moving our right pointer to b we see that b is in our set so we add it and we continue along see same thing oh we're also updating our answer so right now our answer is two and we continue along and now we're at c also not on the set so we add it in and then we update our answer to be three and then we move along and then we get reach a b c a and this is the first point where we have a duplicate in our set the a specifically at this point now that our condition is no longer true we need to make it true again by moving our left pointer which is i so we would move i to b and then we would also remove a from our set because it is no longer part of the range that we're looking at and now that we move the left pointer and our condition is true again we resume looking at our set at our right pointer and we see that a is no longer in the set so we add it back in and then we continue moving it we reach b once again we see that b is a duplicate in set and that's not allowed so we move our left pointer until b is gone so we remove the left pointer remove b and now our left pointer is at c a and we resume our algorithm once again b is in the no longer in the set so we add it back in and updating our answer which is still three so we don't do anything and we just can continue on doing this move 2c find a duplicate condition is false so we move our left pointer to a and remove that from our set now that c is normal in the set our right pointer can add it back in and then we continue moving along we find b he's in the set so we move i out and we see that and we move a from our set now we're at b because b is still in the set we need to move our eye again and we will remove b once again from our set and now that we have unique characters again we can continue moving our right pointer or we add b specifically first and then we move our right pointer to another b which then makes our substring no longer true so we move our left pointer to the x value we see another root c out of our range so now we're back at b once again b is a duplicate so we move this again and now b is no longer in our set and now we can start moving our right pointer again our right pointer adds the b back in the set specifically this b not this b which we were at before and then we move i to the end or j to the n and then since we've reached the end of our array we have our answer which is three which we calculated earlier on and that is how we would use the sliding window algorithm now let's see a live code example let's get started the first thing we need to do is we need to define our variables specifically our set our answer our left pointer and our right pointer since we'll be moving our right pointer we want to keep running our sliding window algorithm until our right pointer reaches the end of the array or string in this instance now going through our array there'll be two things that we'll be doing there is the case where we where our condition is true which in this instance is when our set has unique characters so in this instance we're looking at the our right pointer we're looking at the character at right which is currently at index zero and if our set does not contain this character that means that we have a new character and we can keep and we can add it to our set and keep and continue parsing through our string and while we're also doing this we can update our answer variable if we have a value that's better than our existing one and we do that by using the size of our set and then of course we increment our right pointer so this example we would start at our at left equals zero right equals zero because a is not inside our set we add it in and we check our to see if zero is bigger than the size of a set which is the number of unique characters that we have which is one and it is less so we update our answer be one and then we increment our right index b1 and we contain this algorithm we add b in we update our answer to b2 we move to c a b c add c into our set because it's still because it's unique update our answer to b three because three is bigger than two then we increment our right pointer our right index and then now we our condition is no longer true and we have to do something else so like we talked about earlier if our condition is false we would remove the character on our left index and then increment it forward by one so following that logic we would first remove the character in our set that a that our left index is currently at which is a then we increment our left pointer now our set no longer has a and so because the number has a we can add a back in we compare to see if bca is larger than our biggest answer which is three it's not they're the same and then we move our right pointer one more and this algorithm basically goes like exactly like we talked about in our example walkthrough so i won't go through the whole process again so at the end we eventually make it to the end of our string with our right pointer and then all we need to do is return our answer now let's submit our answer and see how we do and there we go and that's how we would solve the longest substring without repeating character problem hopefully now you have a good idea of how to use the sliding window algorithm now if you like this video please like and subscribe to get weekly updates otherwise if you have any questions or comments leave it in the comments below bye and have a nice day
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,365
what's up guys i'm xavier elon your favorite future facebook amazon google software engineer today we're going over how many numbers are smaller than the current number it's an easy problem on link code and let's jump right into it so i just recorded this entire video and i realized my microphone was off so let's do it again round two so given in the array nums for each numbers if i find out how many numbers in the array are smaller than it that is for each number of i you have to count a valid number of j such that j does not equal i and num to j is less than numbers of i so that's um pretty uh confusing description in my opinion so we just re return the answer an array um what they're trying to say is just read the title how many numbers are smaller than the current number that's all you need to know um this is very like convoluted so how many numbers are smaller than eight in this array well all four of these so we put four at the index where eight is in a new array or actually we could do it in the same array um so how many numbers are smaller than one zero how many numbers are smaller than two well this nut well two is not smaller than two so there's two so we have to account for duplicates um so there's three one and eight so we put um no sorry there's only one we're doing smaller than two so we just do one and that's it so let's think um let's go to the whiteboard i'm going to pull it up how would we if this is our input how what's the easy way to calculate this how many numbers are smaller than the current number um why don't we just sort it so if we sort it we have so sorted is 1 2 two three eight and then if we loop through all the numbers to the left so all the numbers to the left of one are smaller than one so that would be zero then we get to two all the numbers to the left of two are smaller than the current number which is two so it would be one number smaller we just have to count the numbers this way but then we also have to account for duplicates so for this we would have to for this two we would have to account for this two so that makes it a little tricky and also just counting is that way is um harder than it seems and we already just sorted it so that's already n log n time so let's try and think of something different we already have it here but what if we just combine these two what if we have a count instead of just sorted so what if we created an array so i'm gonna do an array from oops so i'm just going to go from 0 to 8 because 8 is the highest value in this array so let's do you know 0 1 2 three so these are where we're going to keep a tally of how many of those numbers are in our array six seven eight so how many let's loop through the input so let's start at eight how many uh we just increment eight by one um and we're just going to loop through so we increment one by one so we did these two and now let's do the twos so we have one and then two and three so the rest are just zeros and so now let's think how can we so how many numbers are smaller than the two well it's just the sum of all the numbers to the left of it so we just need to calculate the sums of all these numbers which is just one but an even easier way to do this if we do the sum in a new array so let's do that we just add the sums from left to right so we're going to have zero still one plus two is three plus one is four and then finally five so this is eight this is zero and then one two three four so i don't want to fill them all out but you guys hopefully you guys understand that and so then now when we go up here we're gonna loop through this array and find the corresponding value so and then we just want to go one back there's four numbers less than eight is that what we had um yeah so that's the correct number four we want to look one back so we the eight is gonna be so let's fill out our output array so we're gonna match now we're doing the corresponding index so we already said four for eight and what about one let's go to one well the value to the left of one is zero so zero and two i'm just going to go through this real quick one and then we have three so three is right here so let's grab the three there three and does this match our answer yes it does so let's just code that out now i'm gonna keep the white board up so that we have something to look off of i know i didn't write pseudocode but i hope the visual helped uh so let's create our output array or i'm like it's not going to be output it's i'm just going to call it smaller and new int and so what we're going to want to do is look at the constraints the value is from 0 to 100 so let's create a 101 array all right so the first thing we want to do is we don't need to sort it we want to do the tally so for ins i equals zero i less than numbs out length we're gonna just loop through nums and i plus we're going to do smaller numbers of eye we want to find we want to get the value and we're going to increment it so and now we have this array filled out but now we want to create the sum so let's go ahead and do that the only difference is we have to start at one because we have to calculate the sum with the one behind it so for this one we're gonna add this one to it we're gonna add these two numbers but for zero we can't go back we'll be out of bounds so we start at one so i less than another thing is it's 101 so we created an array this array actually goes to 101 i didn't obviously draw it out so that's why we're doing that and i plus so um smaller of i is just plus equal to the number before it r minus one okay so now we're going to loop through it one more time we're going to reference these values from here to here and input them into nums so for int i equals 0 i less than we're just looping through nums this time okay so let's grab the position so we're saying the position of this well this is the position technically or the index equals numbers of i so the one thing we have to account for is if the position is zero um since we're going we're gonna check one before it if the position is zero we just wanna write zero set it equal to zero so numbers of i and we're going to store everything in nums of i we can't change the smaller array because we might have to reference again when there's duplicates so let's just change nums we don't need it once we already set the value we don't need that value anymore uh and then else so nums of i equals uh smaller so we want to go position minus one so we gotta go one backwards and then let's just return numbers that should work submit it run it test it cool so it actually runs really fast 99 so it's um linear runtime because we're just using the for loop um i guess you could say it's a linear space complexity i don't really know because it's such a small array it's so limited um i don't know if it would be o of n or constant um so let me know what you guys think about that and if you guys have any questions just leave some leave them in the comments below i'd like to hear from you guys if this video helped smash that like button and that's all i got for you guys i'll see in the next video you
How Many Numbers Are Smaller Than the Current Number
how-many-numbers-are-smaller-than-the-current-number
Given the array `nums`, for each `nums[i]` find out how many numbers in the array are smaller than it. That is, for each `nums[i]` you have to count the number of valid `j's` such that `j != i` **and** `nums[j] < nums[i]`. Return the answer in an array. **Example 1:** **Input:** nums = \[8,1,2,2,3\] **Output:** \[4,0,1,1,3\] **Explanation:** For nums\[0\]=8 there exist four smaller numbers than it (1, 2, 2 and 3). For nums\[1\]=1 does not exist any smaller number than it. For nums\[2\]=2 there exist one smaller number than it (1). For nums\[3\]=2 there exist one smaller number than it (1). For nums\[4\]=3 there exist three smaller numbers than it (1, 2 and 2). **Example 2:** **Input:** nums = \[6,5,4,8\] **Output:** \[2,1,0,3\] **Example 3:** **Input:** nums = \[7,7,7,7\] **Output:** \[0,0,0,0\] **Constraints:** * `2 <= nums.length <= 500` * `0 <= nums[i] <= 100`
null
null
Easy
null
382
hey everyone welcome to Tech quiet in this video we are going to solve problem number 382 link to list random node first we will see the explanation of the problem statement then the logic on the code now let's dive into the solution so here we have taken the first example from the liquor website so we need to select any node from our linked list with equal probability right we need to select any node you can select any node and we need to return that node at the end but we need to select that particular node with equal probability and we are given a head of a linked list where get random function will be called so whenever the function is called we need to select the any node from our linked list with equal chance right now we will see how we are going to do this so initially I will be having three variables one is Count which is initialized as 0 then result variable which is initialized as none then I will keep my current pointer as the head node right then I'm going to use random dot random function to generate random integers with a given range and here count is inclusive right so for example if I have a range one to two right I need to select one between 1 and 2. so what is the probability of selecting one between one and two which is 0.5 right we are giving equal chance is 0.5 right we are giving equal chance is 0.5 right we are giving equal chance that's what we need to do so whenever we select one we are going to place that particular node as my result right so what I mean by the node it can be any node the current pointer is pointing that will be my result right so the result will be different for everyone it can be any random node from the given linked list I will show you guys how you are going to do this so first I will increase my count will be 1 now right so now I need to select one between the range one and one so obviously I'm going to get one so when I get 1 I will update my result as the current node that is 1. right now I will move my current pointer to the next node so our count is one now then again I will increase my account my count become 2. now I have a range 1 comma 2. so between 1 and 2 I need to select one so basically we are giving equal chance of selecting 1 and 2 to select one so each integer has a probability of 0.5 so each integer has a probability of 0.5 so each integer has a probability of 0.5 to get selected right equal chance assume our Rand int function gives 2 not 1. we are not going to update our result right but I will move my current pointer to the next node this is my current pointer now I need to increase my count now it becomes 3 so my range increases my range is now one two three so between three numbers one two and three I need to select one what if our Rand in function gives 1 right then I will make the current pointer node as my result node and I will move my current pointer which is none I am going to written result we are done with the linked list right so we need to return the result variable finally right so what if we have got three we were having one nasty node right at the start we have to return one so everyone gets the different answer we can select any node that's what the problem is right now let's see the code so before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially we need to initialize head right then we are initializing count variable as 0 at the start then result will be none then we are going to have the current pointer which is pointing to the head node at the startup then we are going to I trade through the link to list right by moving our current pointer so first we will increase our count which is basically we are increasing our range so I'm going to check whether the integer that has been selected with an equal probability between 1 and count range is equal to my one if the function selects one then the current node value will be the result and I am going to move my current pointer to the next node and each and every iteration so whatever node we have selected that will be our result right I think it's fine let's run the code so the time complexity will be order of N and space is constant space thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future also check out my previous videos keep supporting happy learning cheers guys
Linked List Random Node
linked-list-random-node
Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen. Implement the `Solution` class: * `Solution(ListNode head)` Initializes the object with the head of the singly-linked list `head`. * `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen. **Example 1:** **Input** \[ "Solution ", "getRandom ", "getRandom ", "getRandom ", "getRandom ", "getRandom "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, 1, 3, 2, 2, 3\] **Explanation** Solution solution = new Solution(\[1, 2, 3\]); solution.getRandom(); // return 1 solution.getRandom(); // return 3 solution.getRandom(); // return 2 solution.getRandom(); // return 2 solution.getRandom(); // return 3 // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. **Constraints:** * The number of nodes in the linked list will be in the range `[1, 104]`. * `-104 <= Node.val <= 104` * At most `104` calls will be made to `getRandom`. **Follow up:** * What if the linked list is extremely large and its length is unknown to you? * Could you solve this efficiently without using extra space?
null
Linked List,Math,Reservoir Sampling,Randomized
Medium
398
55
another day another problem so let's Solve IT hello everyone I hope you are all having a good day today we are going to solve the jump game problem this problem can be solved using dynamic programming and also greedy algorithms so I will show you both Solutions first let's get started by reading the problem and try to understand it you are given an integer array numps and you are initially positioned at the arrays first index and each element in the array represent your maximum jump length at that position so return true if you can reach the last index or false otherwise the first information that we have is that we are starting at the first index of the input array for example in this list we're starting at 3. the second information is that each element in the array represent your maximum jump length at that position means that the first value at the first index which is three can be the maximum jump that we can reach another example for one the max jump that we can take is one step means the next position so for zero we can not jump any step because it is zero step so basically each number inside the list represents the steps that we can jump the question is are we able to reach the end of the list by starting at the first index for this example the return gonna be false because we cannot reach the end of the list let me show you using this little jumping map the first index at the list is gonna give us three steps so the max reach gonna be at zero which is index three the second number gonna be two so the max step that we can jump is two steps so the max range is zero the next number is one and one gonna be the maximum of Step that we can jump so we reach the next number which is zero the next number is zero and zero means zero steps so we cannot reach the end of the list after that we return false the first solution gonna be using dynamic programming this technique is used to solve complex Problems by breaking them down to smaller sub problems and solving them one at a time that allows you to avoid having to solve the same problem multiple times so let's say we have this example can we reach the end of this list so we have two at index 0 we have three at index one and we have one at index two and we have one at index three and we have four at index four starting at index 0 which have the number two so how many steps can we Jam so we can jump one step for that we're gonna reach the next number and also we can jump two steps so we're gonna reach the number one after that we move to the next index the value gonna be three so we can jump three times the first jump gonna be the first now the first next number the two steps gonna reach the second number two means index three and three steps gonna be at the last index mean we reach the end of the list then we move to the next number which is one gonna take one step to the next number also the next number gonna be taken one step and after that we return true because we reached the end of the list so to solve this problem using in dynamic programming we're going to create status positions arrays that gonna have a list of Boolean that have the same length of the input list and the first value of the status positions array gonna be true since we can always reach the zero step and after that we're gonna initialize two variables called I and Max rich and we're going to be starting at index one and I gonna be the start index and after that we start checking if one of this number can reach the last index of the input list and each time update each position inside the status position array to true if we reach it if not we keep it false and we move to the next index Until the End once we reach the last index one time we can add a break statement so we don't need to continue because question is asking us if we can reach the end of the list after that we return the last Boolean of the status position if we are reaching the end it will be true otherwise it will be false foreign okay so the time complexity gonna be off and square and the space complexity is going to be off and because we are creating a new array for the second solution using greedy algorithm agreed the algorithm is an approach for solving a problem by selecting the best option available at the moment so for this problem we're going to start at the first index iterate throughout the list and each time selecting the maximum of length that we can reach and the most important condition that we're gonna add is if we pass the reach that means that we have a value equals zero so we cannot jump anywhere so the variable I at the end gonna not be equal to the length of nums for example for 2 the maximum steps that we can take is two so jump two steps and we update the max range to B2 we move to the next index one that have the number three so our index we can reach it's going to be index 4 because index 1 plus value 3 is going to be equal to 4 so we update to reach the maximum range and we continue until the variable e it's equal to the length of the list if it's true will return true because if we reach the last index and for this example we update the maximum range to be eight at the end of the iteration so we're going to increment the variable I by One at the last iteration so that's why we're gonna have the variable I equal to the length of the list and that's it guys hope you have understand how to solve this problem if you face this problem during coding interviews so for the time complexity is going to be all fan because we're iterating throughout the less one time and for the space complexity is going to be off one because there is no extra space thanks for watching see you on the next video
Jump Game
jump-game
You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position. Return `true` _if you can reach the last index, or_ `false` _otherwise_. **Example 1:** **Input:** nums = \[2,3,1,1,4\] **Output:** true **Explanation:** Jump 1 step from index 0 to 1, then 3 steps to the last index. **Example 2:** **Input:** nums = \[3,2,1,0,4\] **Output:** false **Explanation:** You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 105`
null
Array,Dynamic Programming,Greedy
Medium
45,1428,2001
93
good morning friends today we will solve a question of lead code that is restore IP addresses a valid IP addresses consists of four integers separated by a single Dot and each integer should be in the range of 0 to 55. and it cannot have any leading zeros let's see the example for better understanding like we see an example of 0.1.2.2031 it has been separated by a 0.1.2.2031 it has been separated by a 0.1.2.2031 it has been separated by a DOT and there are four in this is like 0 1 2 and 201 similarly for 192.168.1.1 it is a valid IP address but 192.168.1.1 it is a valid IP address but 192.168.1.1 it is a valid IP address but if we see in 0.011.255.245 we have a leading zero 0.011.255.245 we have a leading zero 0.011.255.245 we have a leading zero that occurred in this integer so it is not a valid IP address also the range should be in 255 0 to 255. and we cannot have anything else than a DOT and integers values so it is also not a valid IV address now the question states that we will be given integer s string s and we need to find how many IP address how many valid IP address that can be generated from that string I hope the question is now clear to you moving to the examples that are given to us so let's start with example number three that is one zero two three now for this string we haven't multiple options like we can put first dot here then here and here like this so I but as we can see in a valid IP address there are only three dots and also the number should align between 0 to 255 so if we see first integer that is one that is given in our string if we put the first dot after it we have remaining two dots so there is an option to put it in this way or here and here like there are many options so what we will do we will place our first dot at first position or a position and then we will check for the rest of this thing that um that the dots can be placed on or not so for this string now we have placed the one dot so we are remaining with two dots so what we will do we will try to place the two dots here and make a valid IP so if we place the one dot here similarly and then check for it and then we have one dot left checking in this type of entry in this type of in this string basically so if we place a one dot let's suppose first we will check for here so if we see there is a leading zero so it cannot be a valid IP address so what we will do we will not take this ipn backtrack to the previous and now please rather than placing the dot here we will just move forward and place a DOT here now we can see that we have completed our three dots and also all the integers like let me write the IV here one point 0.10 0.23 this is a valid IP address because 0.23 this is a valid IP address because 0.23 this is a valid IP address because it do not have any leading zero and all the integers that are separated by dots are in a range of 0 to 25 to 55 so this can be put it in the answer block that is here and if you see there is an IP this IP has been already computed so this IP after that moving the type into the answer vector or any Vector array you take now we have an option okay rather than moving the dot here we can also move it here so we will just place it here and now the string that has been computed will be one zero one point away sorry yeah there will be point and 0 to 0.3 you can see will be point and 0 to 0.3 you can see will be point and 0 to 0.3 you can see also this is a valid IP address with all the integers from 0 to 255 and three dots so also we can place it here we will push back in the array or vector and then move back now after this was all when we pushed the dot here now let's suppose if we do not put the dot here you put the dot here now for this string we have one dot left and we need to place it either here either have so putting the first dot here so the ipv will get or the string that we will compute is zero one zero oh let me alphabet one thing that yeah we need to also check if we are placing the dot somewhere so the string that we are getting should not have any leading zero so if we see this element we will have a leading zero so that cannot be takes so we will not run or we will not do the recursion for this particular string because it has a leading zero not replace this here now if we move it is no there is no way or no any possibility if we do move the word forward then we can remove the zero so what we will do we'll just backtrack back to the first zero that we have taken like here so now we have an option of putting the zero here similarly we will compute for this string and after Computing the district they will again backtrack and come and put a dot here now the question arises how many chances would be like if we take this dot here we will we have to move everywhere in the spot like this it is a catch like if you take you are you need to only take limit is 3 because any string that is 999 or any string that comes it cannot exceed the three little because 2 5 it has only three amount of it so the number of Loop in which we can put the dot is should be three or the minimum of the string length or the string line that is left let's suppose if we reached here we cannot because there is only one string left one character left so we have do not have to we do not have to move the string forward because only 3 and this length of the string is one so our Loop will be running from 3 to the minimum length of the string that is left that is one so the loop will do one because we have only one possibility to put the number of dots I hope the explanation uh is pretty clear to you and now we will move to the code that will make a little bit Clarity in the recursion so if we see we have a function name button that is our equation function that we will use in this we will check if number of dots count has been exceeded 4 because we should have only three digits three uh dots in this and if it limits it exceeds four then we need to return because it cannot given valid IP address and if we have reached to the last index that the index has been reached to the last element on the end of the string right the string has been exhausted now we have to check if the number or dot is equal to 4 like we have 4 dot please so what we will do we will push back the answer from 0 to size minus 1 like removing the last element I will show you in the code how why we will remove the last element you know we have it a for Loop running from the index like if we have reached to 2 let's suppose we have reached to 2 so we have an option from placing the string after this 2 5 or 5. so we will be going from index to index plus 3 or the size of the string that is left let's suppose we have reached to 3. now we have an option of only placing the dot after 3 or after five so the string length Remains Two so that is with the minimum of that string or the three count only that much amount will be only that iteration will have iteration will be done for the loop so if this string that is S Subs I have taken the substring let's suppose if you are standing at two a point place at 2 and 5 and 2 you take this string so it will check if it is less than 256 or not because that way it is valid if it is greater than 255 then it is not valid so if it is less than 256 or and there is also one condition that it has it cannot have any leading zero so if the index is equal to J let's suppose in this example we have taken 0. so 0 dot so 0 can be taken if the index and the position we are take uh placing the knot is equal so we can place it or there is no issue or if the readings there should not be any leading zero like the starting element of the headline should not be zero then we need to call the reservation function with the index plus 1 that is we need to compute for the next indexes and that count on dot should be plus one also now what we are doing here we are if we are managing the string that contain all the type IP address that computed till that point let's just substring that we have computed just now and adding a DOT afterward if when we reach the last element there is always we have one dot X star remaining at the loss of the element because we are just placing the dot after the substring so that's why we are removing by removing the string removing that dot by doing the minus 1 and we will hold an answer array to just push back uh the answer that we are getting now in the main function we will declare an answer and yeah there is also one thing that there are four integers and maximum value that can be have it has 255 that contains three letters or digits you can see so 4 into 3 is 12 but if any how we get a string that is greater than 12 that there is no case that we can make a valid IP from that so we will just return the empty answer or else if it is not the case when then we will run our recursion Loop and compute the answer and then return it now running the test cases on all the test cases has been accepted now we will submit the code as we can see our all the case is that it was selected and our answer has been accepted that's all for today and if you have any doubt regarding the explanation or any suggestion please write it in the comment box or if you have any another question from any another platform feel free to uh paste the link in the comment section I will provide the code or with the explanation as soon as possible also this code has been given in the description uh below with the GitHub link you can also remember it there thank you for watching the video
Restore IP Addresses
restore-ip-addresses
A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros. * For example, `"0.1.2.201 "` and `"192.168.1.1 "` are **valid** IP addresses, but `"0.011.255.245 "`, `"192.168.1.312 "` and `"[email protected] "` are **invalid** IP addresses. Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order. **Example 1:** **Input:** s = "25525511135 " **Output:** \[ "255.255.11.135 ", "255.255.111.35 "\] **Example 2:** **Input:** s = "0000 " **Output:** \[ "0.0.0.0 "\] **Example 3:** **Input:** s = "101023 " **Output:** \[ "1.0.10.23 ", "1.0.102.3 ", "10.1.0.23 ", "10.10.2.3 ", "101.0.2.3 "\] **Constraints:** * `1 <= s.length <= 20` * `s` consists of digits only.
null
String,Backtracking
Medium
752
165
Hello hello everybody welcome to my channel let's all the problem compare version numbers to compare version numbers version 1.2 compare version numbers version 1.2 compare version numbers version 1.2 from January this year grade to be happy return wave in this version 101 210 be happy and minus one drops return after worry you are not alone in All States End Daughter Not Represented A Point End Use 2.5 Inch From Second Number Point 9 And Half And Guest 2.5 Inch From Second Number Point 9 And Half And Guest 2.5 Inch From Second Number Point 9 And Half And Guest When Skin Level Off The First Level subscribe for Live One Number 205 330 Quick Revision Numbers Of Three And Four For Its First And Second Level End Veer 1000 Likes Third Floor Butter And Didn't Give One Example February 02 2012 - Subscribe example2 Example February 02 2012 - Subscribe example2 Example February 02 2012 - Subscribe example2 Seervi 670 He But To N320 320 Happy Return Minus One Because His Verses In 1000 Dot Will Be The Number 90 Everything Seems You Will Receive the lite version from 1000 500 to 1000 years I want to three 204 and one so the effigy of compare every level from Amazon.in will effigy of compare every level from Amazon.in will effigy of compare every level from Amazon.in will be split this bestwap.in be split this bestwap.in be split this bestwap.in 154 spirit will get rid of numbers basically string to solve 123 low and 1234 Violence Ke Tweet Warning 30 And One Sunao Will Start Comparing This To Luxury All Same Again In The Toursim Dushwaar Same But When They Are Comparing T-20 Is Aushadhi Flat To Comparing T-20 Is Aushadhi Flat To Comparing T-20 Is Aushadhi Flat To Dec-11 And Dec-12 Dam Will Return This Dec-11 And Dec-12 Dam Will Return This Dec-11 And Dec-12 Dam Will Return This - Subscribe Will Not Heart Problem - Subscribe Will Not Heart Problem - Subscribe Will Not Heart Problem Subscribe And One More Important Subscribe Chief Hai Version One Daughter Split Sonth Special Characters Perusal End Subscribe Will Be Split Into An Agreement Between Two Brothers Will Not Make Us Of Force One To A Hai Na And Billu Power For Max Planck From In Tie Ko Suzy Profile 10th Maths Languages ​​And A Plus Know Will To Check If Languages ​​And A Plus Know Will To Check If Languages ​​And A Plus Know Will To Check If Ludheshwar Software Will Find Its Way Into Every Fire Every Spirit The Part Where Every Level Will Be Default subscribe Video give Parts Interior Shots In The First Period You For Using String The Video then Pizza Condition No Will Simply Compare Is One Is Great Amazon Simply Plus One Panel Will Be Two Will Return - Subscribe Panel Will Be Two Will Return - Subscribe Panel Will Be Two Will Return - Subscribe Otherwise Indian Hidden From All Evil Returns Of The Day Ki Vikram Submarines Cutting Correct Answer So Let's Tried To Submit This A Needy Section And So this piece of mind of what we can also represents beginning of this user internal light interior Clash of Clans compare method for me two different designs in danger of cheating setting stop this and Vijay simply this hair check gift I also come pressure computer int I also come pressure computer int I also come pressure computer int yes this company is no need to include isi jaisa dam par mehak compare to subah user compare 25250 98100 subscribe to and compare easy try been written hair compare and will continue with its quite amazed compare to and jis computer scanner printer symbol Return computer system gender is this shesha correct compare to listen this the state has accepted so what is the time complexity of solution software to install max like this is plated 500 depend upon how many specific have maximum express is not specified what's the 6 and subscribe My channel thank you for watching see you tomorrow
Compare Version Numbers
compare-version-numbers
Given two version numbers, `version1` and `version2`, compare them. Version numbers consist of **one or more revisions** joined by a dot `'.'`. Each revision consists of **digits** and may contain leading **zeros**. Every revision contains **at least one character**. Revisions are **0-indexed from left to right**, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example `2.5.33` and `0.1` are valid version numbers. To compare version numbers, compare their revisions in **left-to-right order**. Revisions are compared using their **integer value ignoring any leading zeros**. This means that revisions `1` and `001` are considered **equal**. If a version number does not specify a revision at an index, then **treat the revision as `0`**. For example, version `1.0` is less than version `1.1` because their revision 0s are the same, but their revision 1s are `0` and `1` respectively, and `0 < 1`. _Return the following:_ * If `version1 < version2`, return `-1`. * If `version1 > version2`, return `1`. * Otherwise, return `0`. **Example 1:** **Input:** version1 = "1.01 ", version2 = "1.001 " **Output:** 0 **Explanation:** Ignoring leading zeroes, both "01 " and "001 " represent the same integer "1 ". **Example 2:** **Input:** version1 = "1.0 ", version2 = "1.0.0 " **Output:** 0 **Explanation:** version1 does not specify revision 2, which means it is treated as "0 ". **Example 3:** **Input:** version1 = "0.1 ", version2 = "1.1 " **Output:** -1 **Explanation:** version1's revision 0 is "0 ", while version2's revision 0 is "1 ". 0 < 1, so version1 < version2. **Constraints:** * `1 <= version1.length, version2.length <= 500` * `version1` and `version2` only contain digits and `'.'`. * `version1` and `version2` **are valid version numbers**. * All the given revisions in `version1` and `version2` can be stored in a **32-bit integer**.
null
Two Pointers,String
Medium
null
997
today's problem is lead code problem number 997 and it asks you to find the town judge and we will see what is the definition of town edge so this is a town where these five people are there can be more people so here this green person denotes the judge and these yellow people are the general public and this blue line denotes the trust an arrow denotes that this person trusts this person but this is not known to us beforehand we will determine it based on what arrows are going towards what persons so the condition is that the judge let me call it with g and these are different people p1 p2 p3 and p4 so judge does not trust anyone so there should be no arrow going out of this is not allowed so this is the first condition and the second condition is that all the every person in the town trusts the judge so for any p there should be one trust going in this direction if there is one spare person uh from which there is no arrow coming in this direction that is this person does not trust this person then this person will not be judged and it's possible that there is no judge in the town in that case we will return -1 the town in that case we will return -1 the town in that case we will return -1 otherwise we will return the index of that person there is a number for each person a level so you will be given n where n denotes number of people in the town and their level are from 1 2 all the way up to n so each person has a unique level and one of these levels will satisfy this condition for which everybody trusts him but he does not he or she does not trust anybody else so how we will find that so this was a positive example you see there are 5 people n is five and four people are trusting this person they can also trust somebody else also this does not violate the condition but this judge should not trust anyone so if we add arrow like this it will be false so in this case we can safely return this but let's take a negative example so here you see this person trusts this person so this is a candidate for now and this is no more a candidate because he has trusted somebody but the condition is given that there is no outgoing arrow from judge that it just does not trust anyone so this cannot be judged because you trust somebody else but this is still a candidate and its count is one here also n is five this person also trusts him so this is also not a candidate but its count becomes two this person again count becomes 3 very good and this is not a candidate and this trusts even this person for this count becomes 1 and now i find that this judge also trusts this person so now its count becomes 2 and after we have assigned all the counts we have looked through all the trust arrows we see that none of them have count of 4 so count should be 4 i will write it tc for trust count this should be equal to n minus 1 for any person then that will be the judge so what approach we will follow is that whenever a trusts b i'll keep a count track of the same size n levels corresponding to each so one two till n so this is a trust count array for n initially they will be zero every person has zero trust count and we will be given a pair of this a list of this trust pairs so a b then maybe c b and a big list like this so this is itself a list it has some pairs so we iterate this list bigger list we see that a trust b so whatever is the level of b let's say it's the level of b so we make its value plus 1 and its value minus 1 and y is minus 1 required because maybe that everybody trusts this person so its count will become n minus 1 but this person also trusts somebody then in reality this should not be judged because judge does not trust anybody so in that case we have to decrement its count so it will become n minus 2 so automatically it will violate our condition everybody trusts him that's fine but he also trusts somebody so we decrement it and we keep that invariant and then c trust b so again we count increments and c is called decrement and we do this for all of this and finally we will i trace iterate this trust count array and we will see for which index the trust count is equal to n minus 1 that will be the judge if we don't find any such value in this trust count array we will return -1 return -1 return -1 so let's write the code for this in c plus list then we will write the same thing in java and python and by the way what is the time complexity here it will be of the order of whatever is the number of trust pairs in this trust list so if you think of n as the number of people then it may not be order n because this list this pair can become very big so when i written here order and this may be misleading so n if n is the number of person then the maximum number of pairs can be n square and specifically it will be n multiplied by n minus 1 by 2 this is the maximum possible pairs where there is a trust between every person this trust this and this one trust this so this even 2 will not be there so there can be n multiplied by n minus 1 such arrows in a complete graph if you think of it as a graph of 5 nodes there can be 5 times 4 that is 20 such edges so it this input itself can be n square length so time complexity will be order n square and space complexity will be ordering since we are using a trust count array and one space for each of the n person in the town so space is order in but the time complexity will depend on the input so input itself is this is the input if input itself is a big number of the order of n square then time complexity will obviously be that but you can think of it as a linear algorithm because you are just iterating the input once but the this is a slight confusion here since n is the number of person and this pair can be the input can be as big as n square so let's write the code for this so these are some of the examples these are simple so uh so let's keep a vector int and we will call it trust count and its size will be n and initialize to zero just count to zero initially then we iterate this trust is a vector of vector this thing so this each vector is of size 2 which denotes an edge as going from a to b so these are smaller vectors and this is the larger vector trust vector so what we will do t 0 will denote the person who is trusting and t 1 will denote whom the t 0 is trusting so what we will do trust count 0 t 0 minus because this person is trusting somebody so we decrement its count and trust count t1 plus and now this will populate the trust count array so our next job is to look for a trust count equal to n minus 1. i less than n plus i if just count i is equal to n minus 1 then return i plus 1 y plus 1 because here the numbers are levels are always from 1 to n not 0 to n minus 1. for example here we have 3 person and you see levels are 1 2 3 and it's even given somewhere so the levels are from 1 to n and not 0 to n minus 1 but the array indices are from 0 to n minus 1. so we return plus 1 we are starting from 0 going till n minus 1 and if we did not find anything we return the result or -1 so let's try this uh run time error okay this these trust vectors will also give it levels like this so it can have a value of n and this n is not a valid index so here also we will do minus 1 otherwise we'll it will we will be accessing a value an index which does not exist and this works so let's submit and the solution is accepted in c plus list now we will do the same thing in java everything else would remain same let's try and this works so let's submit and the solution is accepted finally we will do it in python 3. and this works so let's submit and the solution is accepted in python as well
Find the Town Judge
find-the-town-judge
In a town, there are `n` people labeled from `1` to `n`. There is a rumor that one of these people is secretly the town judge. If the town judge exists, then: 1. The town judge trusts nobody. 2. Everybody (except for the town judge) trusts the town judge. 3. There is exactly one person that satisfies properties **1** and **2**. You are given an array `trust` where `trust[i] = [ai, bi]` representing that the person labeled `ai` trusts the person labeled `bi`. If a trust relationship does not exist in `trust` array, then such a trust relationship does not exist. Return _the label of the town judge if the town judge exists and can be identified, or return_ `-1` _otherwise_. **Example 1:** **Input:** n = 2, trust = \[\[1,2\]\] **Output:** 2 **Example 2:** **Input:** n = 3, trust = \[\[1,3\],\[2,3\]\] **Output:** 3 **Example 3:** **Input:** n = 3, trust = \[\[1,3\],\[2,3\],\[3,1\]\] **Output:** -1 **Constraints:** * `1 <= n <= 1000` * `0 <= trust.length <= 104` * `trust[i].length == 2` * All the pairs of `trust` are **unique**. * `ai != bi` * `1 <= ai, bi <= n`
null
null
Easy
null
1,727
hello everyone let's the today's lad Cod Challenge which is largest sum metric with rearrangement so here in this problem we are given a my binary Matrix of size M crn and we are allowed to rearrange the column of this Matrix in any order and what we have to return is the largest submatrix within this Matrix where every column of the submatrix is one after reordering the colums optimally okay so let's say in this given example we can rearrange these columns and in any order so that we have to like get the maximum area with each one in it okay let's take this example and discuss further on over this problem 0 1 so uh like how do we calculate the area in this so maybe we can start from any row maybe from each row one 1 by one and whenever we get one we will also track the height over height from that element so maybe uh in this example it is 0 01 if it is a one we will just tag the height and we'll capture that we have to capture the result in a like square or U rectangle order so this would be our candidate from the first row which is having area as three okay so from second row from here we can go till one from this one we can go till uh Zero from one we can go till one and above as well so like how do we do that so maybe like we have to check for all the possibilities from this one or maybe from all these two pairs or maybe using all three elements and checking all the scenarios wherever we can form a rectangular Square so this is going to be uh like n Cube solution so we have to S think of something else like which is a better in sometimes in terms of time so like why don't we just make all these rows independent because uh in the previous approach like uh here we have we haven't reordered the column optimally we are just uh trying to solve the problem straight away so if we have to rearrange the column that is also going to add too much complexity so like uh why don't we just uh make the rows independent in the starting 1 0 1 if we have to make these rows independently why don't we just like uh make it from the starting like starting row is anyways going to be the same for the second row like we have to calculate the area so why don't we just precompute uh how many ones we have already visited from the starting so the first row will become something like this one and two because it is representing the height like uh the number of ones before it okay so now for the third row what would be the uh result like uh 2 0 and three is representing that uh height of ones in this case and two is representing height of one in this case okay so now we can process these uh rows independently so for the first row the answer is one for the second row answer is three 1 we will take for the third row either we can take this height or this height which is three but we are also given that we can optimally sort or arrange these columns so if we make these two column together let's take for the third row 23 if we let's say rearrange it in a manner like 0 2 3 so these two and three will be together so now in this case our area will be four so which is more than three so by rearranging the column we can get a better result and how do we do that like make arranging all the items in the column in a fashion uh where it will be having minimum difference between each element so maybe in short we're just going to sort these elements so firstly we did is firstly we will make all the rows independent and then we will sort each row and calculate the answer so by making the row independent we will use the previous row every time and sorting we can do uh by any inuu function and calculating answer is like uh let's say for the third row it is 0 2 3 if we are at this index it means we don't need to do anything if we are at this index it is representing that all the in all the elements after that is having height at least two or maybe height more than two okay so how can we calculate the area base into height so height is two for sure every element is going to have a height of two so the base length can be calculated like n minus I is the current element which is 0 1 2 let's say I is 1 here and N is 3 - 1 = to 2 which is two elements so 3 - 1 = to 2 which is two elements so 3 - 1 = to 2 which is two elements so two is height and two is base which is equal to 4 so for each index we will calculate the answer using uh I element into base length okay now let's try to code this problem firstly let's capture the row value and column value Matrix to length Matrix I dot length we are given that it is of size M cross n okay let's Al also store our answer to capture result later on now we have to iterate over this Matrix for I = to 0 I less than m i for I = to 0 I less than m i for I = to 0 I less than m i ++ j equal to Z J less than n j ++ j equal to Z J less than n j ++ j equal to Z J less than n j ++ okay uh now like we don't have to do ++ okay uh now like we don't have to do ++ okay uh now like we don't have to do anything with the first row so it should be greater than zero and whenever it is one we are going to change it if it is a zero we are not going to process it if Matrix of i j is equal not equal to zero or maybe equal to one in this case Matrix I j+ equal to Matrix IUS 1 and J okay so now we have calculated the current row so why don't we just process it because we uh this row is independent so we can process it right away so let's take it in a different integer current row because we are going to sort it later on matx of row dot clone Now sort this row current Row 4 in K = 0 K less than n k K = 0 K less than n k K = 0 K less than n k ++ this row is sorted we just have to ++ this row is sorted we just have to ++ this row is sorted we just have to capture the answer from this row how do we calculate that current element current row K into length of this window which was n minus K okay now we have calculated the answer as well we can just directly return it let's try to submit over simple test cases Matrix I do L should be Matrix Z is missing it was a closing Loop for four we have to return answer here some submitting the problem sample test are passed submitted successfully okay thank you guys
Largest Submatrix With Rearrangements
cat-and-mouse-ii
You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order. Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._ **Example 1:** **Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\] **Output:** 4 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 4. **Example 2:** **Input:** matrix = \[\[1,0,1,0,1\]\] **Output:** 3 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 3. **Example 3:** **Input:** matrix = \[\[1,1,0\],\[1,0,1\]\] **Output:** 2 **Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m * n <= 105` * `matrix[i][j]` is either `0` or `1`.
Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing.
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
Hard
805,949
49
That we will solve the question in Haj Badi, if there is Gram thing in the group, then see the question, you have got the link, the reason is mixed like this is ABC that Tricolor's CBC A B C D E F C I is actually COD that DOEACC BBA BCA BBA ESC AIDS Patient, you will get all the grams today. Ghr So both of these are there and it has to be free with these days and also these two have to be included and if you have to call these two together then your answer will be that or that ace register first in the middle ABC or ACBC Dishoom and you will see that on the left and this report has been prepared and on the other hand, within the default, these two should be together BLDC and A B C D and this B C D I and in the third jewelers these two should be together. In DB and BCA BBA then if they subscribe then you are taking it Jhaal stored laptop has made this list hey guys are really in which subscribe like this we subscribe village subscribe to turn off frequency is only two spoons cross India the white house I will use it as in your reply and if you use it as the last rinku value, then the first one was created in your pregnancy, you appointed it inside you, then you subscribed to this, now you appointed it in front of the school, then the same frequency again or this already. If it is lying in a big shop, then this trick is in front of it and if you added it and processed it, then you got pregnancy my 12231, otherwise you passed it in front of Liuji, then if you did not subscribe to it, then you passed it in front of him, then this is what we have here. Use in front, you are subscribed to appoint, the question here is whether you can put anything in the country, whether of this movement or of the gap in the cheeks of the new hit song, then first stuffing. I ca n't put everything in it at any time, I can't put it on time, I can put it, what I can't do, you will add it to someone else, I can become someone else's accused, so I made this. Then I have put a loop in my ring. Hello friends, Namaskar. I have taken out a SIM inside it. Now I will make the frequency here. On the other side, Chapter Vs in Teachers Recruitment, so this is very simple or 120 Sanjay Singh Dot Nick Pickles, we have made it many times. And it is difficult for him and her that it has been cut out and has its own discretion in frequency. If I am already there, then friend will be made. If Palace is not there, then I will be added to the front. You must have read the rationalization of I will use get notification, so that in the conference. If the leader is not lying then it will give zero and if you are braiding then only the fence will increase. If there was no balance in front then it will change. Now I will see if there is a job gap that he can read this frequency map. Controls whether he controls it or not, if not then it is not for the first time. He told the duration of MS Word list to- not for the first time. He told the duration of MS Word list to- not for the first time. He told the duration of MS Word list to- do list, he added this trick to the list and in a big way, the frequency has been fitted in you, hence in front of you. If it is already there, then now we will cut it, I will put a bigger map grate, I will get the list with you and I will keep doing this for the rest of the list, then these big ones will start running to me saying that this-this is like you have subscribed. And here is the list of string, okay, well, these scientists, gap, subscribe to WW Sangh all the night, the result is equal to the new year list that has been reduced, okay, I that has been reduced, okay, I that has been reduced, okay, I run the temple, I submit it again. One thing that has to be considered, I have to repeat it again or this either looks fine, Sameer Vikas comes, then I will do that tiger is the correct answer for you, so now we are in this, here I have made which and nothing else, nothing. It may or may not be possible, we will talk about it. Now whatever you want, subscribe. Thank you.
Group Anagrams
group-anagrams
Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** strs = \["eat","tea","tan","ate","nat","bat"\] **Output:** \[\["bat"\],\["nat","tan"\],\["ate","eat","tea"\]\] **Example 2:** **Input:** strs = \[""\] **Output:** \[\[""\]\] **Example 3:** **Input:** strs = \["a"\] **Output:** \[\["a"\]\] **Constraints:** * `1 <= strs.length <= 104` * `0 <= strs[i].length <= 100` * `strs[i]` consists of lowercase English letters.
null
Hash Table,String,Sorting
Medium
242,249
1,850
Hello gas so today we will be discussing question number 1850 code minimum andersen swaps is the smallest number of reach you can understand the question what is it quite an interesting problem although it is medium but according to you it is a problem ok so let's see what is And first of all, there is nothing in this, we are given a number, this number is ok, so first of all, what do we have to do, we have to generate its next permutation, then next is the mutation, famous problem on late code description, I will give the link of the problem and its I have discussed the problem in the video, first okay, so what to do is that if we take all the permutations of this number and arrange them lexicographically, then the position at which this number will be, its next position will be at that number. This number will be okay, these simple trumps or what we have to do is just make the next greater element from it [ or what we have to do is just make the next greater element from it and it should be the permutation of this number in this number, so how can we make such a number in this available formation, now he has How many minimum adjacent swipes will it take for us to go from this number to this number? Give it very carefully. Minimum adjacent swipes means we will not be able to swipe five and one. Do you understand Okay, so let's see. How does that happen so this is that number right this is our original number okay and this is our destination number latest call this SRC source and let's call this destination okay you let us reach from here to here we just have adjustment allowed we How will we do it? Okay, so what will we do? Okay, so it will remain like this, what will become of this number 412. Have you understood? If you have not understood, then look again at the question. Sometimes there is a problem in understanding the meaning. There is so much complex problem, there are many of them. There are all the approaches to be done, so I will discuss one approach with you and that will be Giridih Rose and how to approach it, why are we doing that, we will see all that with full clarity, okay but before watching this video So let's So let's So let's start in the next approach, then before our algorithm, we will learn some concepts and even before conceptualizing it, first of all we start and complete the basic formalities that the proposal is to give us a cake. I will run the look of one more till four and we will call the function of the next permutation on that permutation, four times, okay, so that our source gets converted into destination, okay, how many minimum adjustments, be very careful about this, minimum. Adjustment is fine, you reach from SRC, then destination, so before that, let us see the concept. In version number, then we will see the concept. Van, you are three, four, five. It is fine, this is ours, this is our ideal number, no, it has quarters. After the van, you come, you are After three comes 4. After 4 comes five. Now we have another number given, van three four tu five. Okay, whatever it is a permutation of the same number and it is different and what are the digits in it? Isn't their order different, so how is it that after Van, there is three A. Okay, after three, there is 4 A, after four, Tu is A, after Tu, there is five A. Now when we compare these two numbers. If we do, then the elements which are out of order, date it, de-invention number, date it, de-invention number, date it, de-invention number, which is our main, let's do it, this is the ideal number, okay, this is what we are considering, this is our ideal number, so we are comparing this number with this, that in this Which digits are out of order in this comparison? This ideal number is correct. In this number, after van, you are right. There is no problem right now. Is there 4A after 3? Han is 4A after 3. Okay, okay, before 224, A is there, 24, okay, in version number, van means neither, and okay, what comes after 32, Han, but here, A is before 32, so now if our and let's see the order. It should be correct, if we have a number of elements n1 and this N2, let me define it a little mathematically and there is a left rust, it should be correct, it should come after i, if it has to go after i, then children should also come in it, not like this. It should happen if it becomes Jai, then this is this in version, the aversion number in this is our in version number, it will be van in this, if we got only one leg in this and our we are comparing this to this and you are fine with N2. Our idea is and we are considering that this is some fake number, such a man is running it and we are seeing what are the falls in it, then how should it relate to the question, what will we do in this? We will learn the thing, okay, what kind of thing will we see in this, we will see how the order is changing here and if the order is changing, then how is the effect of this version number, so if we understand it in detail, then let us write back to the example. is 1342 51234 ok now here we have understood the order of tu and four ok tu and four are out of order here a is after 24 and this is the photo ok if I clear both then what is the number Will become 1324512345 Did you and four come in the right order? Did the aversion become less than 1, but what else is ours? What is this adjustment? So if I am talking about adjustment in the whole question, then I will make adjustment because I will make 4 more. I will not consider 3. I will not consider this you and this you. I will consider this three and this you. Now I will not swipe. I will consider these three and I will swap because both of them are adjusted. If I subscribe to these two, will the inverse number be reduced by one? 1234512345 Look, the numbers have become the same because this version number is reduced by one more, meaning now this number of ours was our ID number, okay and this is ours, we call it fraud number, okay, how much was the version number earlier, inverter number was two. How much does it become, zero, okay, so the important concept of ours, the important concept that we have to take is the number of mines of one in version, okay, let's go to man, this is our left part of D, this is a number, okay, there is a digital in it, so it has I. Man, Jai Man, take one like this, 51234, by doing this left part is complete, this whole right part is done, okay, I have made it right, okay, I can also swipe, my adjustment is allowed and the left is still from There is no difference in the order of I and Left. There is no difference in the order of I and Right. There is no difference in the hotel of I and Right. Not only in the order of I and K. And this reduced the request number by only one, so one adjustment Only Okay, Only Okay, this is a very important point, okay, so what do we do if we assume that we are given, we are ours, okay, so if we get this version number of our source. If I was like this will be equal, you are the number, then how many swaps will we need, so we will get that many aversion numbers, so our whole concept is that we have to get the universal number, nothing else has to be done, okay, we have seen that. Brother, how did it come, we have understood the meaning of the key, it is visible, not the order, we will have to follow the process, we will have to follow an algorithm, we will have to follow some steps, we will understand it easily, we will understand it, okay, so we have This is the destination and some given K is some positive number ok so we have fork the next permutation we have called ok this is the times and reached the destination swaps if we want to exit then reach src then destination statement ok this is if we want to exit then let's start We will start where we should be. Okay, so far I have got the sim. Five after you, five after you is right. We will move forward on these two points one by one. Here we come here, we got different numbers. You are watching and sex, now what does it mean that we will find sex somewhere further in SRC, we will find it somewhere further, let's find it, do you know what it means, this phone and this is 7, we will find it somewhere further, we will find it in this version number. Will be done and sex is allowed. Okay, so now let's do our address and swap here. So this will be done. Now the aversion number has become 7. That's what we get next. The destination date is here and your number has become zero. Swipe back. After doing okay so far we've set up and we're like okay then got separated what is this okay so what we do is look for 3 as far as we got our two back to finish If so many numbers will be in front of the van at the destination, then this many numbers will be our number again on this version. Two and which legs will they go? If I want to finish van and four, what should I do? And four will be these. I have swiped these. Version number is zero medicine. Understand it again. If you do n't understand it well, then it is okay to watch the video again. It is a little long but it has a lot of concept. The questions given in it are correct. If the concept of this version number is correct then watch the court. If you want to know how to do it, then this is the example given by me which is written in the comment, you understand and here we will do it. Which string permutation do you want, then here we have the destination, we have to give dot, till where we want test, okay. So what are we doing in this, we are starting from here, both are okay, name of I is not equal, you are not equal, destination of I is okay, understand that we get the destination, we have to start from there, so we will start from there, okay, so If it comes within 2.0, okay, so If it comes within 2.0, okay, so If it comes within 2.0, then now we will start from here, let's assume that we have got here, we will start looking from here, if we start looking from here, then we will find it, how the name of J is not equal to destination. Off I will not stop until we get what we want, we will get the jail, we will do as many swaps by applying the condition that J is greater than I, it has as many functions as it does, Name of J - 1 So here we understand that all the JI will be equal then we have to break it because otherwise 5 and 4 will also get swiped, we will return our result variable which is swap, we will try it ourselves, sorry. Gone Wrong Accepted Miracle's See and It's Gone Thank You
Minimum Adjacent Swaps to Reach the Kth Smallest Number
minimum-length-of-string-after-deleting-similar-ends
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, when `num = "5489355142 "`: * The 1st smallest wonderful integer is `"5489355214 "`. * The 2nd smallest wonderful integer is `"5489355241 "`. * The 3rd smallest wonderful integer is `"5489355412 "`. * The 4th smallest wonderful integer is `"5489355421 "`. Return _the **minimum number of adjacent digit swaps** that needs to be applied to_ `num` _to reach the_ `kth` _**smallest wonderful** integer_. The tests are generated in such a way that `kth` smallest wonderful integer exists. **Example 1:** **Input:** num = "5489355142 ", k = 4 **Output:** 2 **Explanation:** The 4th smallest wonderful number is "5489355421 ". To get this number: - Swap index 7 with index 8: "5489355142 " -> "5489355412 " - Swap index 8 with index 9: "5489355412 " -> "5489355421 " **Example 2:** **Input:** num = "11112 ", k = 4 **Output:** 4 **Explanation:** The 4th smallest wonderful number is "21111 ". To get this number: - Swap index 3 with index 4: "11112 " -> "11121 " - Swap index 2 with index 3: "11121 " -> "11211 " - Swap index 1 with index 2: "11211 " -> "12111 " - Swap index 0 with index 1: "12111 " -> "21111 " **Example 3:** **Input:** num = "00123 ", k = 1 **Output:** 1 **Explanation:** The 1st smallest wonderful number is "00132 ". To get this number: - Swap index 3 with index 4: "00123 " -> "00132 " **Constraints:** * `2 <= num.length <= 1000` * `1 <= k <= 1000` * `num` only consists of digits.
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
Two Pointers,String
Medium
null
1,642
welcome to april's lee code challenge today's problem is furthest building you can reach you are given an energy array heights representing the heights of buildings some bricks and some ladders so you start your journey from building zero and you move to the next building by possibly using bricks or ladders while moving from building i to i plus one if the building's height is greater or equal to the next building you do not need a ladder or breaks so what that means is if the next building is smaller or equal you can just jump off and fall down you don't need any bricks or ladders to climb up now if the buildings is less than the next building's height then you can either use one ladder this ladder can climb up the building no matter how tall it is or you can use bricks uh the bricks you have to use though is uh h plus one minus h1 so say that building this height is five and this one's gonna be ten you have to use five bricks so our decision is to use whether we should use number of bricks or we should use a ladder one ladder to travel to the next building now we want to return the furthest building zero index the index that you can reach if you use the given ladders and bricks optimally okay so there's a nice little graphic here you can see that from uh building one we're building zero we have a height of four that we can fall uh we don't need any bricks or ladders we can just fall here then we can climb using five bricks to climb to the third building as you can see it's graphic that just travels nice little graphic here with the code okay so great so they give you a couple hints and um assume that the problem is to check whether you can reach the last building and you'll have to do a set of jumps what they mean by jumps i think is like decline and you have to choose whether to use rope or bricks or the lateral bricks it's always optimal to use the ladder for the largest jumps so that makes sense right if we have a bunch of jumps that we need to make and each one being different amounts we want to use the ladder for the largest heights difference right the rest we want to use with bricks so the smallest ones we want to use with bricks and that's going to be how we can optimize our use of the ladders and brakes now they tell you to iterate on the buildings this isn't very helpful to me but initially i thought this was going to be very simple all we need to do is find the differences from each building to each building and the ones where the building next building is higher sort that out and see if we have enough ladders to take care of the largest ones and then see for the rest of the heights do we have enough bricks to cover those um but that's not going to work here because we actually don't know uh well first off that's not the question isn't can we reach from the beginning to the end the question is what's the furthest building that we can reach giving given our ladders and bricks um so with that in mind that kind of changes the question then we have to figure out well what's as we iterate down our journey what is going to be our optimal um use of these ladders and bricks right so okay so let's begin by first initializing n to be the length of heights and what we're going to do is iterate down our buildings for i in range of n minus 1 because we only care about the differences and the difference is let's call it h is going to be equal to the heights of i plus 1 subtracted by heights of i now what we're going to do is we already know we have some number of ladders and some number of bricks as we iterate down this um we're going to use a greedy approach and what we'll do is have some sort of data structure that stores the difference in number of difference of heights now in the beginning we'll just assume that we'll always use ladders like if we only have three buildings that have some amount of heights then we'll just use the ladder if we have three ladders and we don't really care about bricks right so we can assume that as soon as we find that we don't have enough ladders to cover any of those differences what we'll do is have some sort of data structure what i'm going to use is a heap here and we'll pop off the minimum height difference okay because for that minimum height difference we'll use bricks for that the rest will use ladders and we'll just build this kind of like almost like a sliding window we'll be popping off the minimum height difference and seeing if we have enough bricks to cover those while we're covering the rest with ladders and if we do then we could return you know the length of or the last index number of this buildings but if we can't as soon as we find that we don't have enough bricks or and ladders to cover it we already know we optimized using our formula right so at that point we'll just return the index that we have so i'll show you what i mean the first thing we want to do is check to see if the height difference from the second one to the last one is positive i mean if it's less then we don't care about it because we don't need bricks or ladders so if h is less or equal to zero we'll just continue because we don't care okay now what we're going to do is we'll check to see if we have enough ladders or not to cover so if length of heap well first we got to add to our heap right we're going to add heat push onto our heat this height and if our length of heap is greater than ladders the number of ladders that we have then we need to pop off the minimum one so call this min h you pop off our heat and we'll subtract this minimum height from our bricks now finally we want to see do we have enough bricks still left to continue because if our bricks is less than zero or i should say less or equal to zero well then we're done we don't have enough bricks and ladders to cover anymore so we can just return our i at this point otherwise if we're able to fill this entire loop we'll return n minus one so let's see if this works here so looks like it's working let's go ahead and submit that okay so i got the wrong answer see what i do wrong what's gonna happen is we use our ladder then three one ladder bricks 3 i actually feel like my answer is right here because we only have five bricks and we'll use our ladder here then we'll use two bricks 3x no actually never mind maybe it's less like this okay there we go so that's accepted so um no why did that not work lester equals zero i'm not totally sure but um i guess it's only when we have negative amount of bricks that we need to return the eye i suppose since we're at the all right because we're at that previous index you know we used all our entire amount of bricks it's only if we have less than that amount that we need to return that i at that point right okay so that makes sense all right so time complexity wise is going to be of n and we do use o of n minus 1 space because of our heap um and actually think about it's not going to be n it's going to be n because of our heat thing is going to be n log l which is going to be the number of ladders we have the n log l okay all right i think that's uh pretty self-explanatory um self-explanatory um self-explanatory um not an easy question i definitely had to look a lot of this up um but hopefully you get the intuition behind it i think the main thing here is to make sure to use your ladders on the largest heights and make sure you use the bricks on the smallest ones okay thanks for watching my channel remember do not trust me i know nothing
Furthest Building You Can Reach
water-bottles
You are given an integer array `heights` representing the heights of buildings, some `bricks`, and some `ladders`. You start your journey from building `0` and move to the next building by possibly using bricks or ladders. While moving from building `i` to building `i+1` (**0-indexed**), * If the current building's height is **greater than or equal** to the next building's height, you do **not** need a ladder or bricks. * If the current building's height is **less than** the next building's height, you can either use **one ladder** or `(h[i+1] - h[i])` **bricks**. _Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally._ **Example 1:** **Input:** heights = \[4,2,7,6,9,14,12\], bricks = 5, ladders = 1 **Output:** 4 **Explanation:** Starting at building 0, you can follow these steps: - Go to building 1 without using ladders nor bricks since 4 >= 2. - Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7. - Go to building 3 without using ladders nor bricks since 7 >= 6. - Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9. It is impossible to go beyond building 4 because you do not have any more bricks or ladders. **Example 2:** **Input:** heights = \[4,12,2,7,3,18,20,3,19\], bricks = 10, ladders = 2 **Output:** 7 **Example 3:** **Input:** heights = \[14,3,19,3\], bricks = 17, ladders = 0 **Output:** 3 **Constraints:** * `1 <= heights.length <= 105` * `1 <= heights[i] <= 106` * `0 <= bricks <= 109` * `0 <= ladders <= heights.length`
Simulate the process until there are not enough empty bottles for even one full bottle of water.
Math,Simulation
Easy
null
461
hello everyone so in this video let us talk about a easy problem from lead code the problem name is hamming distance so let's start so the hamming distance between two integer is the number of positions at which the corresponding bits of both of the numbers are different so you are given two integers x and y and you just have to return the hamming distance between two of them so let's take an example so as you can see that x can be represented as this in the bitman like bit uh representation as well as four is represented like this now if you just match every bit position the number of bit position as with both the bits are different you just have to count all of those positions and the count of them is actually the hamming distance so this is different at this position this difference at this point they both are same so the answer is that there are two different positions answers to and that's the whole problem now how you can do this now it just required weight manipulation if you have some knowledge about bit manipulation then you can easily solve this problem out let us take one example so that it will become okay to you i'm not writing down the actual number but let's say that bit manipulation of any number with representation is like this the next number is so this is let's say x y in the bit manipulation now what you can do is you just have to iterate over every bit in x and y how you can do that you can just do an and of the part so let's say and one left shifted i times at each iteration and i goes from 1 like 0 till 32 now what i've done here is just bit manipulation if you want to just find out that whether any bit is set or not any bit is one or not how you can do that you can take for x and just take one left shifted i number of times so let's say i want to find out whether the ith bit is set or not now so let's say i want to just check five fifth bit is sent or not so just take one left shift it five times so five time is that one left shift fighter means that you have added five zeros after this and now you have x also so let's say that x is like this in the bit manipulation x is like this now if you do an and operation of this number and this number is this and x is this if both the numbers have the same bit at the same position this will be some positive value which is like this okay or else if it is zero then it will be zero so the simple way is that if x and one left shift of i times if is a positive number then that particular is bit is set if it is zero then which means that the input is not set that's the way to check that a particular bit is set or not so you can just iterate over every i bit of x and y so you can just use this instead of x you can use y so the first up like expression is one left shift i times the next is y and one left shift items now this two operations will tell you that whether both of the ith bit in both the numbers are set or not and now you just have to check that they should be of different parity if one is one the other should be zero if one is you know there should be one and how you can check that zoro operations so our patients can be like they are uh zoro patients are this operation in which the turns out to be one if both the bits on which you are doing the zoro operation are of different parity if the same priority it will give zero if it is of different parity if you give it will give you some positive integer so you will just do an azore operation of both of these particular values and if this turns out to be a positive number then the answer is that both the bits are of different type if they turns out to be zero which means that the both the bits are of same type you don't have to count them and you just have to do this for all the bits from let's say zeroth position to thirty one position okay because as you can see that the maximum number is up to 22 31 so you can you could go from zero to 31 bits so which means that 31 bits and you just have to check that whether every bit is like this condition satisfying or not so moving on to the code part so what is the total number of uh having distance that how many bits are different if you have a from zero to 32 then you have written these two expressions you can like do this in two different variables also i can just have done this in one like one expression so x and one left shift i this will give you one expression this will just tell that the first and the ith bit in x is set or not similarly with the ith bit in y is set or not if they both whatever is the status just do a zord operation on another and if it gives a positive integer this if condition will turns out to be true and this will like increment the total variable and then just return the total amount of variables that has dimming distance greater than uh like that have different and just return the hamming disc so that's the logic and code part for this problem and uh the overall time complexity is o of n and n is very small like a total number bits actually the total number bits in the number uh that i'm talking about n and it is 32 so o of 32 that is actually just constant time so o of one only because we are just always doing 32 bit so o of one that is the overall time complexity of this problem as well so if you still have any routes you can mention in the coin box thank you for watching this video till the end i will see you in the next one till i keep quoting
Hamming Distance
hamming-distance
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given two integers `x` and `y`, return _the **Hamming distance** between them_. **Example 1:** **Input:** x = 1, y = 4 **Output:** 2 **Explanation:** 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different. **Example 2:** **Input:** x = 3, y = 1 **Output:** 1 **Constraints:** * `0 <= x, y <= 231 - 1`
null
Bit Manipulation
Easy
191,477
299
hey guys welcome back to another video and today we're going to be solving the leakout question bulls and cows all right so in this question we're playing the game of bullets and cows with one of our friends so you write down a number and you ask your friend to guess what the number is each time your friend makes a guess you provide a hint that indicates how many digits instead gets match your secret number exactly in both digits and positions and this is what is called a bull all right so in other words just to make it simple a bull is when let's say the number i guess is one and the actual number is one in that case i have a bull which means that the two numbers match exactly and even the position which they are in also match okay and the other thing we have is a couch all right and this is how many digits match the secret number but locate in the wrong position so in this case you have maybe two numbers which are the right numbers but they're not in the right position okay so your friend will use successive guesses and hints to eventually derive the secret number write a function to return a hint according to the secret number and friends guess so a is going to be used to indicate bulls and b is going to be used to indicate cows please note that both secret number and friends guess may contain duplicate digits and one more thing we should note is the fact that you may assume that the secret number and your friend's guess only contains digits and their lengths are always equal the fact that their lengths are equal can help us quite a bit all right so let's just take a look at an example so finding the bulls is actually the easy part so a bull is when uh let's say for example over here 1807 and seven eight one zero the eight is both in both the places it's in the same place there it's the same number and it's in the same position so in that case it's one both so that's why we have one a and everything else is considered as a couch so we have three b which is three cows and why is it a couch so we have one zero seven in that order right one eight zero seven but over here we have seven eight one zero so seven one and zero and one zero seven they're all the same numbers but the only thing is they're all in different positions so finding out about the bowls is pretty simple but how do you actually get the cows so to do that let's take a look at how we can do that so this is the same example as our question so we have the secret number on the left and then we have the guest number over here and what we're going to do is we're going to use a bucket okay and this bucket is going to consist of 10 zeros so what i'm going to do is let's just write the index of each of them and why the number 10 so you can just think of 10 being represented for the number zero through nine so this represents the number zero then one two three four five six seven eight and nine so that represents each number and that's also its index so how can we actually use this for our benefit so let's actually take a quick look at that we're gonna go through our numbers one by one so first we have one over here and we have seven over here and obviously one and seven are not the same so in this case it is not a bull but it could be a count we don't know yet so what we're going to do is we're for the secret number we're going to go to the first index since the number is one we're going to add a value of one so this is going to end up becoming one over here and one more thing we're gonna do is we're gonna go for our guess we're gonna go to the seventh index which is here and we're gonna subtract it by one so this is going to end up becoming negative one and the purpose of this is actually going to become clear really soon so now we're going to have eight and eight over here so they're both the same so that means it's a cow so let's just create a variable called cow and we're gonna add one to it used to be zero now we have one cow cool so now let's go to zero and one so we're gonna do the same steps so for zero we go to zero we're gonna add by one since it's from the secret number and this is going to end up becoming one now we're going to go to one right so we go over here and we're gonna subtract it by one so currently the value is one and we do one minus one this actually ends up becoming zero so what actually happened there so in simple words you can kind of think of it as so first we encountered a number in our secret number and when we encountered it in our guess number we subtracted it so with the value of one first being one and then subtracting and making it zero that's telling us that they both contain the number one just in different positions and if they were in the same position we wouldn't be doing the step at all we would just increase the cow by one so hopefully that makes sense and let's just uh continue with this so finally we have seven for secret and zero for guess so we go to 7th index and we increase it by 1. so again this negative 1 ends up becoming 0 since negative 1 plus 1 is well zero and all that's telling us is that 7 exists in secret and in guess the only difference is that they're in different positions similarly over here for guess we have zero so we're gonna go to zeroth index minus one is zero and we end up with zero so what is this telling us this is telling us that all the numbers in our secret place are also there in guess except that these three numbers are not in the right position this is going to be the number of cows we have okay sorry i made a small mistake let me just double check okay so a bull is when they're in the same position and digit okay so this is supposed to be bull really sorry about that so this is bull and these are the cows so we have three cows over here and the number of cows is well three and how do we actually get the number of cows so the formula for that is going to be we're going to take the length of secret so that's going to be 4 and we're going to subtract that by the number of bowls we found so in this case it's going to be 4 minus 1 and that actually gives us the value of 3 and we're also going to subtract it by the sum of whatever is greater than zero so in this case for our bucket so in our bucket we don't have anything greater than zero so in that case it's just going to be minus zero giving us a value of three so real quickly let's just look at a second example over here so let's look at this example over here one two three and zero one all right so let's just run through this real quickly so first we have one over here and then we have zero so we end up going to one increase it by one and then we go to zero decrease it by one since it's from guess then over here we have one and one so it's the same number and the same position so we're going to increase our bull value so now it's going to end up becoming one so now we go to two and increase it by one so this becomes one over here and we go to one decreasing it by one so this ends up becoming zero and finally we go to three over here increasing the secret value so we increase it by one and then we go to one over here and we decrease it by one so this actually ends up becoming negative one so now we got the number of bowls and we also now need to find out what the number of cows are so let's find out the number of cows so the first step is going to take the length of secrets so which is four and subtract that by the number of bulls we have so this is the maximum number of cows we can have so we can have a maximum of three cows but that is actually not the case so what we're actually going to do is we're going to take a sum of everything which is greater than zero and in that case this only corresponds to these two values which have a value of one and so that's going to be two so one plus one two so we're gonna subtract that so four minus one minus two which is four minus three which is nothing else but one so that means we have one cow and well how does that actually even make sense so let's just look at this so first let's just cross this out over here so that over there is our uh bowl right so we can just ignore that so what is the cow so the secret number has two and three and our guess does not have two or three which is why if you go to our bucket over here and you look at the values of two and three they both have a value of one which means that those numbers are there in the secret but they are not there in our guess right so that's why we subtracted the number of cows by two since we did not make a guess for the numbers two and three at all but we did make a guess for the number one over here instead we actually make two guesses so we have one over here and we also have one over there and either of them can be considered to be the cow which is why we have one cow which is over here and if it doesn't make sense why we subtract it by two is because the values of two and three have not been called in the guess at all which is why that we're decreasing the number of cows and if you look at entire if you look at it in terms of the game you would want to have more cows which means that your guesses are more accurate so this is how we're actually going to solve our question and let's just go back to our example and you can see that we got the same answer so 1 a and 1 b that's the answer we got and now we'll see how we can actually implement this in code all right so let's start off by defining our few variables so we're going to have the number of bolts so it's going to start off with a value of zero and we're also going to have our bucket so to form our bucket it's going to be a list of zeros and it's gonna be ten zeros right so uh 10 in the cents to represent the values zero all the way through nine so that's why we need ten so that into ten that gives us a list full of ten zeros okay so now that we have this we're gonna iterate through our secret and guess so we can do that by two ways we can uh we know that they're gonna be the same length so we can iterate through the index or we can just uh zip out or we can use zip in order to get each of the elements so i'll just use zip so let's just do for s to represent the secret comma g for guess in zip uh secret comma guess okay so now that we have this we can go inside for loop and over here we're going to check if they are the same value so if s is equal to g then in that case we know it's a bull so in that case we're going to go to our bolts value and we're going to increase it by 1 and we're done but if this is not the case there is a possibility that it could be a count so what we're going to do is we're going to go to our bucket right and we want to go to whatever is at the s index and this actually secret is actually a string which is why convert this into an integer since we want to go to that index so we're going to go to uh integer s so we're going to go to that index and this is for the secret and for the secret we're going to increase it by uh similarly for our we're going to go to bucket then int and then we want to go to whatever is at the for the guess right and for the guess we're going to decrease it by 1. it's the same thing as we did before and now we're going to keep going through our for loop and at the ending of this we're going to get the number of bulls uh for sure so by the ending of the for loop we do have the number of bulls so let's just uh see how we can return so we're over here we're gonna have the number of bulls and we already stored it in a variable over here so let's just give that so we have bolts and after that bulls corresponds to a so this is the format so uh the number of bulls a number of cows b all right so we're going to give it the variable volts and then that's going to be a sorry capital a and then afterwards we're going to have the number of cows right cows and then capital b so how do we actually calculate the number of cows so let's just do the calculation over there in place so the number of counts is going to be the same steps as we did earlier so we're going to find the length of our secret list or sorry string so length of secret and we're going to subtract that by the number of bowls we have so that is the maximum possible cows that we can have and now we want to remove whatever we did not uh call in our guess so how do you do that so you go we're gonna find the sum of everything inside of the bucket which has a value greater than zero so to do that we can just do x for x in a bucket and we're gonna give it a if condition so if this x value is greater than zero only then are we going to consider it and we're going to take the sum of everything which is greater than zero and we're going to end up subtracting that and that's going to be it for our kaos value and afterwards we're just going to give b over here and that should be it so now let's submit this and let's see what happens so submit and as you can see our submission did get accepted and finally thanks a lot for watching guys do let me know if you have any questions or if there are any specific legal questions you want me to solve and don't forget to like and subscribe if the video helped you thank you
Bulls and Cows
bulls-and-cows
You are playing the **[Bulls and Cows](https://en.wikipedia.org/wiki/Bulls_and_Cows)** game with your friend. You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info: * The number of "bulls ", which are digits in the guess that are in the correct position. * The number of "cows ", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls. Given the secret number `secret` and your friend's guess `guess`, return _the hint for your friend's guess_. The hint should be formatted as `"xAyB "`, where `x` is the number of bulls and `y` is the number of cows. Note that both `secret` and `guess` may contain duplicate digits. **Example 1:** **Input:** secret = "1807 ", guess = "7810 " **Output:** "1A3B " **Explanation:** Bulls are connected with a '|' and cows are underlined: "1807 " | "7810 " **Example 2:** **Input:** secret = "1123 ", guess = "0111 " **Output:** "1A1B " **Explanation:** Bulls are connected with a '|' and cows are underlined: "1123 " "1123 " | or | "0111 " "0111 " Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull. **Constraints:** * `1 <= secret.length, guess.length <= 1000` * `secret.length == guess.length` * `secret` and `guess` consist of digits only.
null
Hash Table,String,Counting
Medium
null
1,877
hello guys and welcome back to lead Logics this is the minimize maximum pair sum in an array it is a lead code medium and the number for this is 1877 and I'm sure that it will be a easy question for you if you watch the video till the end so in this question we are given with an array nums of even length and we have to uh divide the given array in such a way that the maximum pair sum so maximum pair sum is minimized now what is actually a pair sum suppose we have different pairs 1 5 2 3 4 so if you sum both the elements you will get like six from here five from here and eight from here so you have to minimize this sum the maximum pairer sum so in this the maximum pairer sum is eight so you have to divide the array in such a way that the maximum possible pair sum is actually minimum so for this there is only uh one possible way that you pair up the largest element of the array with the smallest element with of the array because if you choose any other element other than the smallest element to pair up with the largest element it will form a greater pair sum rather than the pair some formed by using the minimum and the maximum element so in this case we are sure that we want to use the smallest and the largest element and uh we can use something as a frequency table or a hash table to count the frequency of the minimum possible elements and the maximum possible elements and one by one pair all these like take first take a minimum then take a maximum pair then take another minimum take another maximum pair it and from this whichever maximum sum is coming just simply return that now we are sure in this case that the maximum sum obtained from here is actually minimum why because as I already told you any other number pair paired up with the largest element of the array will give a greater sum ra rather than pairing up the largest element of the array with the smallest element of the array so I was also designed a like dry run of the solution let's see suppose we have a example 3 5 2 3 so many pairs can be form from here like three and five can be formed two and three can be formed but the minimum possible maximum pair sum will be if you join the seven if you join the five with the two then we you will have a seven and three are paired together so as you can see the minimum is to be paired up with the maximum in this case also so first of all you will take a hash table count the frequency of each element and then take a minimum value at the minimum element and the maximum value at the maximum element and start pairing up the minimum and the maximum values and as soon as you complete the pairing up of the uh entire array you can return the maximum of the possible sums of the pairs so you can see I have created here under iron so the low was two and the high was five so the maximum pair sum was updated to seven and for the rest of the array it was greater so we have not taken it so let's start with the coding section but before that please do like the video share it with your friends subscribe to the channel so first of all uh we need to take the maximum element initialized with integer minimum then the minimum element initialized with the maximum value and then a hash table to count the frequency of the minimum and the maximum elements what's the constraints 10 power 5 so we'll take 1 2 3 4 1 according to the constraint we have taken the hash and iterate through the array take the count hash of num Plus+ update the max with the max comma the num update the minimum with the minimum comma num and now we have to take the low equal to Min and then we have to take the high equal to the max we have taken and we have to start pairing up the minimum with the maximum and the we can use the max variable to count the maximum possible sum because the function of Max is done till here now we can use it for other purpose so we'll count the maximum sum in the max variable while low is less than high I think we can do it less than equal to because 3 three pair is also possible so first of all check if hash of low equal to Z that it does not exist so low plus count of low is actually zero then do a low Plus+ Plus+ Plus+ else if the hash of high equal to Zer then do a high minus okay otherwise if both are present a low is also present a high is also present we have to do Max equal to mad. Max of the Max and the low plus High just pair up the lowest with the highest element to Hash of low minus do a hash of i+ Plus I also minus and afterwards we have to Simply return the maximum pair sum so now let's check it if it's runs okay seems fine try to submit it okay the solution is accepted quite a good time complexity the memory is actually this because we have used a count of this size uh rather than if you use something like U maybe a hashmap or a PRI VI you may get a better memory but this is more convenient and easy to understand that's why I used this uh you can also do is that one thing you can also do is that you can instead of initializing with such a large number you can take the length of nums + nums + nums + one and then you may get a less memory in that case so coming to the time complexity is actually the algorithm iterates through the array on so the time complexity is off n and the space complexity is uh you can see this like although this may be counted as a constant only we are taking a constant space but since the N can be of this size so you can you may say that the space complexity of the solution is O of n therefore the time complexity and the space complexity both can be is O ofn so I hope you understood the video like first of all we are taking the minimum and the maximum then we are trying to pair up the MA minimum element with the maximum element and storing the maximum of the minimum and the maximum sum so this was my solution approach for today's problem I hope you understood the logic thank you for watching the video please do like the video have a nice day okay
Minimize Maximum Pair Sum in Array
find-followers-count
The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs. * For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8`. Given an array `nums` of **even** length `n`, pair up the elements of `nums` into `n / 2` pairs such that: * Each element of `nums` is in **exactly one** pair, and * The **maximum pair sum** is **minimized**. Return _the minimized **maximum pair sum** after optimally pairing up the elements_. **Example 1:** **Input:** nums = \[3,5,2,3\] **Output:** 7 **Explanation:** The elements can be paired up into pairs (3,3) and (5,2). The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7. **Example 2:** **Input:** nums = \[3,5,4,2,4,6\] **Output:** 8 **Explanation:** The elements can be paired up into pairs (3,5), (4,4), and (6,2). The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8. **Constraints:** * `n == nums.length` * `2 <= n <= 105` * `n` is **even**. * `1 <= nums[i] <= 105`
null
Database
Easy
null
1,507
hey everybody this is Larry hit the like button to subscribe and join me in the discord let's go over today's problem which is reformat date so this one is the easy on the reason it called contest and ideal here is just this parsing it's making sure you get everything right and I don't think there anything really tricky about it the only thing that's a little bit tricky maybe no I mean I think this is okay and I even did it a little bit weird I think what I should have done is just chop up the last two characters but yeah it's just getting the month the day in a year in a very consistent way and the year were always before digit that's the observation month will always be three characters that get defined in this array and then the day is just the first or so I you just chop off the last two characters ends okay I mean I did it this funky way and then the only other thing to notice is that you have to pad it so that is two digits and yeah and that's all got to do it for this problem cool and I'll show me typing this life afterwards cool I hope you had a good time watching this video let me know what you think hit the like button to subscribe when trying to discard and I will see you next farm bye
Reformat Date
check-if-there-is-a-valid-path-in-a-grid
Given a `date` string in the form `Day Month Year`, where: * `Day` is in the set `{ "1st ", "2nd ", "3rd ", "4th ", ..., "30th ", "31st "}`. * `Month` is in the set `{ "Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec "}`. * `Year` is in the range `[1900, 2100]`. Convert the date string to the format `YYYY-MM-DD`, where: * `YYYY` denotes the 4 digit year. * `MM` denotes the 2 digit month. * `DD` denotes the 2 digit day. **Example 1:** **Input:** date = "20th Oct 2052 " **Output:** "2052-10-20 " **Example 2:** **Input:** date = "6th Jun 1933 " **Output:** "1933-06-06 " **Example 3:** **Input:** date = "26th May 1960 " **Output:** "1960-05-26 " **Constraints:** * The given dates are guaranteed to be valid, so no error handling is necessary.
Start DFS from the node (0, 0) and follow the path till you stop. When you reach a cell and cannot move anymore check that this cell is (m - 1, n - 1) or not.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
null
51
hello everyone welcome to my channel coding together my name is vikas oja today we will see another lead code problem that is n Queens so let's read the problem statement the end Queens puzzle is the problem of placing n Queens on an N into an chess board such that no 2 Queens attack each other given an integer n written all distinct solutions to the end Queens puzzle you may return the answer in any order let's talk about the constraints as stated in the question so suppose if I place the queen at this cell so I cannot place the second Queen in this cell or all the cells highlighted by cross because we cannot place two queens in the same column or in the same row or in the same diagonals because Queen can attack vertically horizontally and diagonally so I can place the next Queen in these locations right so we'll use backtracking to solve this question because we have to try all the possible solutions right and we have to backtrack as soon as we see that the possible candidate of the solution is not going to lead to a valid solution place the first queen at this cell because at the start all the cells are empty right and there is no Queen so first we'll place this queen in this first cell of the First Column we'll go column by column right if we have placed a queen in the First Column then the second Queen We Will place in the second column third query in the third column and fourth query in the fourth column so I have placed the first query in the first cell of the First Column right now for the second column the second Queen for the second column I cannot place the queen at this cell right because they would be in the same row I cannot place the queen in the this cell because they will be diagonal I can place the queen in this cell so I'll place the queen in this cell now for the Third column for third Queen for the third column I cannot place the queen in this location right because it will be uh in the same row as one of the queen right so this queen can attack this queen if I place this now I cannot place the queen in this cell because it will be attacked by this queen I cannot place the queen at this location right because it will be attacked by this queen and I cannot place the queen at this in this cell because it will be attacked by this queen so for this column there is no place for any Queen so we have to backtrack because this will not lead to a feasible solution right because we have not placed any Queen for the third column and as we know we have to place at least uh four Queens for a four by four board so means we'll backtrack so when we backtrack we have to remove this Queen right will be we have to remove this queen because if we Place Queen at this in this cell we were not we are not going to have any solution so if we backtrack we have the queen here and we will not place the queen here so as we know we cannot so we have tried these three options right these three Soul positions so I'll place the queen at this location because this will not be attacked by the first queen right now for the third column and the third Queen I cannot place the queen in this location but I can place the queen in this location right because this will not be attacked by this queen and this queen will not be attacked with this queen so none of the three will attack each other now for the fourth column I cannot place the queen at this location I cannot place the queen in this location I cannot place the queen at this location right so because I cannot place the queen for the last column I have to backtrack so I have to backtrack right so this position of the queen for the third column is not correct right so I have to try another position so if I remove this position of the queen position the next position no because this will be attacked by the queen this queen and I cannot place at this position and at this position so I have to backtrack again right I have to remove this position as well so as this is the last position right as this is the last position we have to backtrack again it will backtrack again right we'll backtrack again and we'll change undo the last position so we have to mark this as cross right so this is also marked coin and this is the last cell of this column so we have to backtrack and so this means if I Place Queen here in the first cell it will not lead to a possible solution so we have to remove this cell as well so now we have to place the queen in the we have to try placing the queen in the second cell so we started with the first cell or the First Column now we'll start with the second cell of the first column right so if I place the queen in the second cell of the First Column can I place uh for the second column right I cannot place the queen at this location but I can place the queen at this location if I place the queen at this location now for the third column I can place the queen at this location right because it will not be attacked by this queen and it will not be attacked by this queen now for the fourth column I cannot place the queen at this location but I can place the queen at this location right it will not be attacked by this queen and this queen so this is our valid solution so this is our possible solution now we have find our feasible solution so we'll backtrack so when we backtrack from this column to this column now I have to try from apart from this cell the other three cells that we have not chosen so can we put so if I started from this now I had for this with the queen plays at this cell we had a possible feasible solution now we have to try with this cell can we place the queen here no because it will be attacked by this queen can we place the queen at this location no because it will be attacked by this position and we cannot place the queen at this cell so these three other three post cells are not possible right so the only solution was this one first now will backtrack again so we backtrack from this column to this column now we'll backtrack now as the queen is already placed at the last cell so there is no possible solution so we'll backtrack right we'll backtrack now though solution that we have to try is placing the queen in the next cell of the First Column so we'll place the queen here in the next cell right and we'll start placing the Queens in the next columns in the subsequent column so for the second column I can place the queen at this position for the third column I cannot place the queen here right I cannot place the queen here but I can place the queen at this location for the fourth column I cannot place the queen here right I can place the queen here right because if not it will not be attacked by this queen nor it will not be attacked by this queen and it will not be attacked this by this coin so this is the other feasible solution right so we'll backtrack to this column so as the queen is already in the last cell of the third column so we'll backtrack again so we'll see whether now here the queen is placed in the first cell so we have to try with the other three cells right so if the queen is so we backtrack from here to here right now we will see whether we can place the queen at this cell no because it will be attacked by this queen can we place the queen here no because it will be attacked by this queen so we have to backtrack again okay so when we have to backtrack now the only chances to place the queen to here to move the queen from third cell of the First Column to the fourth cell here so we will place the queen in the last cell of the First Column so can we place the queen in the first for the second column we can place the queen here yes for the third column we cannot place the queen here but we can place the queen in this location right for the first fourth column can we place the queen in this look in this cell node in this cell no we cannot place in any of the four cells of the fourth column so we'll backtrack now the Queen is already placed in this cell so we have to place the queen in the last cell so can we place the queen in the last cell no right so we cannot place the queen in the last cell right so we have to backtrack again so the queen was in the first cell of the second column right so we have to see the next cell right so for the next cell can we put the queen yes so suppose we place the queen here and we place the queen here for the third column can we place the queen here no place can we place again here no so for the third column we cannot place the queen in any place so we'll backtrack so we'll move the queen from here to we'll undo the queen we'll undo the changes we'll move the queen to the we'll see the other possible solution so can we place the queen here no can we please the queen here no so there is no choice uh so there is no possible solutions so we will backtrack so for as the queen is already placed in the last cell of the First Column so there is no choices left so we'll return there is no other choices we have exhausted all the solutions so what are the two possible solutions this and this so let's see the code part for it this is the Java implementation of the that we discussed I have created a 2d Board of character type with this rows and columns both as n and we have in I've initialized all the uh cells with the character Dot now we are calling the DFS depth first search so we are starting our DFS method so we are passing the board that we created the column so column is the 0th column that is the First Column we'll start with the first column and the result that is a list of list so if column is equal to both dot length that means we have placed all the Queens in each of the column meeting our constraint like the no two queens attack each other then we will construct the board and we'll add into the result so what do we do in the construct of the board first we convert each row of the board and we take convert each row of the board into a string right so we take each character of the cell converted into a string and add that string into the list so the complete solution is a list of string and we add that list of string into the resultant list of list now we will start the for loop from I equal to 0 and I Legend board dot length so it means we are starting for each row right we are going clock we are going column wise but we are placing the queen at each cell for row wise for each column so for the First Column we have placed we have started with the placing the queen in the first cell for the second column we place we check whether we can place the queen in the first cell second cell third cell right that is what we are doing in this with this for Loop and we are calling the validate board validate method with the board that we created I represent the row and the column so what do we do in the validate valid in the validate we check that if we place the if we Place Queen in the in a particular cell right if we place the queen in a particular cell is there any Queen uh in the same row or in the same diagonal right in the same diagonal up or in the same diagonal down right so this first Loop is for the row second Loop is for the diagonal up and third row is the third Loop is for the diagonal down right so if you see we are doing I is equal to 0 and I less than column so right if we are working on a particular column right suppose the third column so we'll check for the First Column and the second column whether in the same Row for the same row there is a queen present or not similarly we'll do row minus one we'll start with rho minus 1 and column minus 1. so when we do row minus 1 and column minus 1 it means that the diagonal upsell right diagonally up cells will move and we'll keep on moving until the I is greater than equal to 0 and J is greater than zero and if the board i j becomes equal to Q then return false means there is already a queen present there similarly we'll do further diagonal down so if the validate is true at the location I comma column then we'll place the queen at that in that cell for that column and will do the DFS again over the board and the next column that is call plus one right we'll again do the we'll again check whether we can place in the next column and once we are over with the uh either the feasible or non-feasible either the feasible or non-feasible either the feasible or non-feasible Solutions will track backtrack by placing by reverting the position of the queen at I comma call so at I comma call we place the queen so once it leads to the feasible or non feasible solution will backtrack by placing by replacing the queen with the DOT so once this DFS is over we'll return the result so yes test cases are accepted so means this solution is working fine so I hope you like this video and if you enjoyed this video please share and subscribe thanks for watching
N-Queens
n-queens
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other. Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**. Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively. **Example 1:** **Input:** n = 4 **Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\] **Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above **Example 2:** **Input:** n = 1 **Output:** \[\[ "Q "\]\] **Constraints:** * `1 <= n <= 9`
null
Array,Backtracking
Hard
52,1043
662
hey what's up guys this is Chung here today not today same day actually I just uploaded another video so but I still like would like to record another video regarde about this one to steal another tree problem here number 662 maximum with off binary tree it's a I would say the medium one I like it so I will give another up hole here so okay you're given a binary tree write a function to get the maximum width of the giving tree so what is the width right with its down the same level of the tree um the distance from the left most node and at the rightmost node so for example this one here and yeah and then the none node will also be cunning as a node right so for example here with single one of course the distance will be 1 right with 3 and 2 so the distance will be 2 here for level 2 will be 3 and 2 how about here for the last level it's gonna be a 5 to 9 right what's the distance between 5 and 9 there's a 1/2 distance between 5 and 9 there's a 1/2 distance between 5 and 9 there's a 1/2 to be a machine one here right so 1 2 3 4 so it's gonna be four that's why we have 4 here same thing for the for this one so the max level is to basically one node is all is always 1 3 is 1 but with this one 5 and the n is 3 the level will be 2 that's how we get to here right so how do we think about this right and this is the binary tree here right because okay you know I would I'll tell you guys how was I thinking so at the beginning I was thinking of you know every time I would do I would sit cuz I remember we are I did one problem is that I mean to traverse this note like vertically by the horizontal like positions I think also does that's why at the beginning I was thinking okay I would start with the root know that with zero as an axe I acts in three equal to zero he goes to zero and every time when I go to left I minus 1 and every time I go to right I plus 1 right and then in the end I just compare the lat the leftmost position and with the rightmost position but then there's that there's a issue for that let's say for example this one miners go to left so three will be all have minus one and two will have one right but even if from three we go to the right side these three will this one three will become zero right and if there's a two here if the two has a left note here I'd say I have a net left node seven here seven will also have zero have a zero position X position here so that will basically if we use this position this will have to write basically tonight we'll have to if we use zero from zero to two will catch three but then we'll be missing this seven here right so that wouldn't work so then how should we think about this if you can think about if you okay so what we should think about is instead of using that positions we should instead we should like remember the index on each level let's say here 1 2 3 4 5 6 7 right let's say for example with this 3 level binary tree here on each level the index will be 0 right this is 0 this is 1 0 1 2 &amp; 3 right if you watch if you 1 0 1 2 &amp; 3 right if you watch if you 1 0 1 2 &amp; 3 right if you watch it closely so as long as every time when we traverse this tree we can save the index along with the node and then when we do the level of the level traversal we should also be called the breadth-first search right we do that we breadth-first search right we do that we breadth-first search right we do that we can just simply get the first index and the last node in that out of that level traverse and then we simply get the distance right and then the in the nuke the question comes down to how can we calculate the nose in the nose index right I'd say this one is not there right it doesn't really matter as long as we have four hundred seven we don't care about this one stare right we equip because we have the index of seven here so with that's all we need so how can we calculate so if you would closely sit pretty it's very I think it's pretty clear so let's say for example three here right when we can we see this left node and right node you can always see here the left sub node of this current node the index will be what the index will be the previous index times - previous the previous index times - previous the previous index times - right that will be the left sub note index and the right one will be this one times two plus one right Y times two because in on the previous one each of them will have up to two nodes right that's why we when we calculate the current sub known index we just need to use the current node index and then we times two to be the left one and we then we plus one to be the right one alright you wanna keep doing it's like eight right eight nine or something right now and then here it's right in nine 10 11 12 13 right 0 1 right over here 0 1 2 3 and here so this one has an index to here rights and here at the 12 index will be 2 times 2 this will be 4 right and this one will be 5 right that will use this index times tool to be the left one and we do you times 2 plus 1 to be the right one and then I think that's all we need to calculate this thing here okay so let's try to code it here and since we're doing the row level traverse which would also be the bread first reverse right so we'll be doing will be using us a queue here we'll create a queue first collection start EQ right and then we push the root node to it and remember we want to when we push each node to the key oh we also want to record its index right and only index for the route 1 obviously therefore the root in the root know the index will be 0 so we just to uh and we need to tap over here because 0 right and then we just do a level Traverse level all the Traverse for breadth-first search right which for breadth-first search right which for breadth-first search right which ones do well while Q well Q then for levels to traverse we do this right or this right here every times get the length of the current on Q right yeah and we also have it the result here result we'll have the final result after the width of the tree to a max right because we want to keep getting the a bigger one do we do what we do like a like I said we have to kill the last one right so since the last in the last character item sorry the last element in the current queue will be our will be the last element will be traversing right because yeah we need to do it before the for loop because before doing the for loop so the other elements in the kill will be our current will be the node for the current level alright so and then we just get the last one the index of the last one and then we which is the miners the first one index the first element index right and the in the end we +1 the to be the current levels end we +1 the to be the current levels end we +1 the to be the current levels with right and then with compared with the previous result we get the bigger one right and then that's how we do this like update of the weight every time before doing the loop here and then we have to be we have to finish of course we have to keep going down to the next level here right how it's regular breadth-first it's regular breadth-first it's regular breadth-first search or level search right if right and then we will note here nobody goes to Q we pop from left right that's we do a level traverse if note have left as a left no we just append the node into the queue same thing for the right node if the right side has us at the sub node which also append the nodes to the right side nodes to the queue right simply return the root the result right so here we're not maintaining the level number because we don't care about their node we all we need is we just need to know the width right so we don't need at the level variable here to keep track of that which level is that and sorry okay alright my god I could I confused myself oh my god sorry yes so I forgot what we need to do here sorry guys yeah I just completely confused myself so like I said when we push each node we need to get the new nodes index right how right so the index will be when we pop since we're also storing the index along with the note here so when every time we pop the no current node we'll also get the Cardinals index right and like I said when we do the push here besides the note itself we also need to calculate the new notes index right for the left node like I said like we discussed it's gonna be the current index times 2 right and same thing for the right note it's gonna be the index times 2 plus 1 yeah sorry guys about artists like hi so here right I can certainly do another video but I just want to show you guys I mean the whole process maybe the how can how stupid what kind of stupid mistakes I can make right so yeah so with the index and the new index we push and then which in the end we just resolve return the real to result after we finish traversing the tree and that should do it yeah and I think I'm missing another right parenthesis here all right pass go guys real quick so look we've to read to recap so to keep the key idea here is that we need to keep track of each note index on the other heart level so the way we're doing it is we every time we have the previous know the index we just for the last one we do a index times two and the right one index times two plus one and then at the very beginning of each level traverse which updates the with is the current rightmost node and the left most node go thank you for watching the video guys all right I'll see you guys soon bye
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
336
hey hello there today I'm talking about questions 336 panel John parish their question is as follows given a list of unique words we want to find all the pairs of distinct indices IJ such that the concatenation between word I and work J it's a palindrome so the these two words has to be contending than in this order the J's word comes after eyes word so IJ is not necessarily the same as ji so the order doesn't matters and the resulting string is a palindrome basically it means that the resulting string has to be symmetric around the middle so it's something like a TP PT the Big Bang Theory so let's talk about how we solve this if we solve this in the mostest rippable way we will just do compare all the pairs of words and physically concatenating those two together and do a linear path to check for a palindrome so the total running time for this will be n square multiplied by L and it's the number for nodes number of words so when we compare all the possible pairs it's n square and the L is the linear path to check for palindrome that's a linear with respect to the size of the word so that's the proof or solution the redundancy in this brute force solution is that let's say that if we have word I to be ABCD the choice for word J we will really never consider something like a s and S or s SS L so we don't really want to actually do this condition until the linear scan we can identify those very early on because remember the palindrome is symmetric so the if we have a to be the left and most a character the rightmost character after the condition has to be a as well so if we enumerate over the prefix for the first word from left hand side and we enumerate over the prefix in the reverse order from the right hand side choice those two prefix has to match if the to prefix does not match then we don't have to consider any more because it's already violating this symmetric relationship so there will be three different scenarios when we do this prefix matching between these two words one in their left or the right order the other one in the right-to-left order the other one in the right-to-left order the other one in the right-to-left order it would be the two strings the two words of the same lands if we do the prefix matching towards the end of both words it says that they have the same lands it's basically TB and BT so the two together can form a palindrome the other choice the other situation is that the word on the left hand side is a little bit longer so we will be TB something finished the left side word the right hand side where is this BTW so the extra part on the left hand side is very important if the left hand side has a residual part that's a palindrome by itself we can still have those two words piece contaminating together to form a palindrome it's a same story similar story is the case where the right hand side word is longer so if the right hand side word is longer we want to test that the residual part is opponent or not if it's a pun enjoy the two can still be cannot conduct contaminating together to form a total upon injury in the end so that's going to be the three different cases when we do this prefix matching among these two possible choices so since that we are not talking about prefix matching the one thing we can very common data structure to use this perfect Street so let's say that we actually generated a prefix tree we got some notes the route let's increase the size a little bit and we have a TB here but it's not the end of it after TB we have a maybe something like a and another pass CeCe so if we consider a quo reward that's basically I'm sorry bTW so now we are looking at the case where the choice for the left hand side has some extra stuff so the big PT is the choice for what J the passed inside the try corresponding to the choice of what I so we do this perfect matching in the tribe we from left to right basically in the independently search term choice where J was we're doing the prefix or right to left TB much as TB so now the we got a bunch of kind of like words for what I that has some extra stuff how we go about to figure out if the residual part is the pollen do or not one thing we can do is do once we have this matching from this node and all we're going to initialize a either a DFS search of BFS search probably DFS search to test the whether the residual pass is a pawn in John myself so here a CC is a fine Joe a by yourself that's Punjab so we will basically try to find the end of word tag in this case it might be a in deceit word in to see attached to the node and just the return that number was this indices for PT so we will do a search inside the try to grab all the possible pairs now that would be okay but it will be slow on the query actually there could be something we can do in the insertion part that cost the insertion of the word things I try to be a little bit more caustic but it will speed up this you will get rid of the necessity to do a DFS search or probably DFS search get rid of the necessary to DFS search on try every time that we have the prefix match that is to basically annotate on every word from this node and on whether the residual part is a palindrome or not if it's a palindrome we just put an index word index here so the stuff on the node here is going to be the character so the stuff associated with this node is going to be the character the next character to node mapping and the end of word flag and also the list of words that from this node and on is a palindrome so if we have that once we have the TB and PT marching together here we just directly read up on all those indices indicating the word that would have a residual palindrome after this word we just directly read out those index pair those with the bt to return that so that's the case when we have the string the word on the left hand side is longer we can take care of them in this way what if in the we are talking about the other case that may be the search time is longer than the then they pass we have maybe we have TB a B T and D so we will do that prefix matching we will match it until this node a so it's a real it even simpler than that case all we need to do is after we match the TB a with TPA inside the try we will just do a partial palindrome test on the residual part for this choice of the word on the right hand side if the residual part on the choice of the right hand side is a palindrome then we can form something like TBA d abt so that's the three different scenarios the first is that we have an end of word at after the try pass that of the same size that the coil returned the other one is that the past contains some residual palindrome residual pass partial pass after this note when we after you know once we've done the prefix match the third situation is that after we done the prefix match the we exhausted at one pass in the try but we still have some characters residual partial strings on the query term then we run a partial palindrome test on that so that's pretty much the overall strategy the run time for this is going to be K square multiplied L square multiplied by M the L square is basically the time needed to insert a word inside this track data structure because it takes L time to insert the word alone but we have to annotate those note here for that for to include all the word index where after this note you will be a palindrome so that we would do it as basically when we insert a tea I will test whether the residual part of BCC is a palindrome or not because it's not a palindrome we don't put the word index off the tee but once we insert it B we want to test the residual part is C see it since it's a palindrome we insert a index number after this note B annotate that number here so for every character we insert we have to do another pass to check for partial palindromes so that's why the insertion will become L square multiplied by M but the query part will be just a motive either for n different words we want to try to follow the path here and to do the do that do the thing so use L square multiplied by n to initialize the try and M multiplied by L to do the matching to do that pair to extract all the pairs of indices so it's compared to n square multiplied by L this could be potentially much lower if we have n to be large so that's the runtime analysis for this so you're just going to solve this mister just going to try to put it code it up or quickly it's going to be quite a price on code here so are we gonna do a try note here that's the stuff of you put on the try note you know it's associated with a note value the character value it also keeps a character to child the nude mapping which is we get that by subclass default dictionary the there are two other things which is end of word flag meaning that do we have an end of word here default value is false and it also has a list of the word index that from this node and all excluding this word excluding this character but the residual string after this character of the word is a palindrome so we're gonna call this on this word index so it's going to be empty list so that's the final just going to initialize this data structure I'm sorry we can do that in the thing here so we create a root node just going to lay out the code here it's going to break into two different sections and here is the populating that try and the second portion is going to be finding the pair's so we're going to do the population fibers so we definitely want to advance more into the try and after we insert the word we will flag the word to be end of word but every time that we inserted a character we want to test whether the residual part of the word is a palindrome or not so if the word from this chase location alone it's a palindrome will annotate that on to the nerve oh sorry I should use a word index here to indicating it's the end of world I a word index so default its negative one so I'm doing and the list here the indices illicitly is the index for the word after this try note it will be a partial palindrome so let's call this list for lack of a better name I guess yeah so that's the populating of the try the only thing that's different is that we put this annotation here we have a list of all the words after this final character will be a partial panel so let's cook this year doing it did I misspelled this pollen job I'm just gonna call it word and left so the thing we do is to grab the right-hand side which is the rare loss right-hand side which is the rare loss right-hand side which is the rare loss the character in the world while this two-pointer hasn't reached in while this two-pointer hasn't reached in while this two-pointer hasn't reached in the middle we want to increment and decrement those two and just test whether it's a symmetric or not otherwise if we successfully meet in the middle it's totally symmetric so we return to so this partial polygon is testing the word from the else index and on so that's what we've been using here we insert certain characters and just annotate from this character and on the residual the remainder part is a polygon so that's where we put on the try then is the fine thing so we're gonna do this to for I word in the words let's move this thing up to somewhere space.we for every word we want to do a space.we for every word we want to do a space.we for every word we want to do a tri search and so notice that when we do the prefix matching for the possible candidate on the right hand side we are doing that in the reverse order so we reverse the word and enumerate over that so the thing that we want to test is if we have a break of the symmetric if the note the try node has a value has does not have the character or if the node is see yeah if the character is not in the trainer it's not a children for the try note that means we have already violated the symmetric requirement so we can ignore this word possible candidate on the right hand side altogether otherwise we'll just advance one more time we move on to the next land note one thing we need to check here is that if we have a word ending here that means on the left-hand side it's already on the left-hand side it's already on the left-hand side it's already exhausted all the characters but on the right-hand side we it's just a part of right-hand side we it's just a part of right-hand side we it's just a part of the right-hand side but we have some the right-hand side but we have some the right-hand side but we have some more stuff like the search time is TB ad and we have TB a and there is an end of word flag here meaning that we want to do this residual part of the search term to see whether we have a palindrome or not so that's the search case I'm talking about so let's point it here case 3 query is longer a possible J longer than a possible work I so that's indicated by that the word has index that's not negative one and we do this partial palindrome test of the candidate reverse the word from this current allocation at all if that's the case we find the TBA D I'm sorry we find that is he be a the ABT so we put this onto the result or just call this pair so the order for this is that the words index the try pass is on the leg and side and the right hand side is this J is this I we are looking at the quarry doing that's for the query word so that's the tribe search so if we don't break that leads us to the other two cases so the first case is that the TB end of word and bTW case that's that means the note after the first note inside this else condition here would be a node that has a word index that's not negative one that's not I the reason we check for AI is that well if we have something like a the search engine is also a we don't want to have that duplicate so the condition is that if no dog were index it's not negative one or it's and it's also not I then this two has to form a pair otherwise not otherwise just resuming from there we've on the test we're going to basically combine all those words where we have the residual part to be palindrome as well to pair those with the query word to form the form a pairs and push that onto the pair's so that would be extend all the pair's the notes were then the try pass is always going to be on the left oh sorry so it's the right-hand side oh sorry so it's the right-hand side oh sorry so it's the right-hand side is always the query but the left hand side is the this stuff on the list let's just call it odd way how do I do this more pythonic way mop no good item and no I'm sorry it's more complicated honest I think I'm just going to enumerate over all those pairs of nodes yeah that's it that should be it she's just gonna quickly note in here case one word I is equal to word J totally reverse together they have the same lens the perfectly mirroring each other that's taken care of here and the all the rest of the case is here Ward I it is something like ABC with patandjill SOS and where J is a query time is something like a CBA all of those cases will be comforted here so that's that and we return the pair's so let's see if it works just going to read about the code to see if we have problems so that's the try no definition we subclass the default dictionary because we want to use the child the character to the next character to the child node Association we have index word index indicating whether it's an end of word of the ice word the list is the word that from this character and on it's a the residual string as a is a palindrome partial palindrome so here is the definition for this helper function to test whether the residual part of a string is a palindrome from Al's location and all we just check for the symmetric property between the leftmost and rightmost one and to try to move them together to the middle so that's that looks right to the here we initialize this try and try to populate in that right here is enumerate for every word we enumerate over the index and word we started a new path new part new Traverse or insight try from the root for every character in the word if it's not a node inside try we will create a node and establish the character to try the Association and also just advance through the newly created link but before we do that we want to test the whether the residual string for this word from J and on is actually a palindrome if it's a palindrome we annotate the current note that hey after me the word I will contain a palindrome part so if you do prefix match with me and terminated at the disposition this word I can form a palindrome with you because it's a ABC you are ABC and in the reverse order and the word I is ABC with some pollen between so that the index on this list that will help us to do this matching a lot easier and after we finished inserting of this word we just put the word index onto the node so that's the populating of the tri seems okay then it's the actual finding part we enumerate over all the boards again for every node for every word we initialize a try search traversal the thing we do is to reverse the search time because we are consider the prefix matching from the right hand side towards left hand side so we actually physically reverse the word and we enumerate over the word character by character here is that if the try pass is the end of word so it's a non negative one we want to test whether the residual part of the search word is a palindrome so we're doing this partial ponens on test if that's the case that means you know the try pass is a be the query turn is a be SLS something if we read from right hand side to the left hand side if that's the case we just put the try password on the left hand side and the query term on the right hand side so that's this note word index and I pairs we push the push that pairs on to the result here is the test if the symmetric between symmetric and testing between this two prefix break already broke then we exit to this check so otherwise we would just try to go to the next character exam the next character if we never break that means we have perfect a prefix match there are another two cases the first one is not if the note on the try is indeed a termination note and it's also not a note that the same note as the I we're looking at then we have a equal lens symmetric marching so we push this pair on to the pair's otherwise we will look up all the word that from this point and on is a small palindrome after that and we push all those pairs onto the list as well so that's that seems right let me try to run it seems okay it's accepted but quite slow wondering why is there any place the marker that's a super slow anyway I don't see that I don't say anything that's suspiciously too slow so that's one way we can solve this by inserting the word in the right order and but when we curry we do the reverse order the other way is to insert those words in reverse order and when we query we have that we have the word in the right order I'm gonna just go try to modify this real quick too to change my solution to that because it's going to be quite important if we want to solve the follow-up to this question so to do the follow-up to this question so to do the follow-up to this question so to do that we will basically just modify a few things we've got a comment it out and annotate the decode so for the population part we're gonna insert the words exactly in the reverse order so just gonna copy this part here and anywhere we have a word I will just change that into reverse work more comments yeah you get the idea I don't want to put more text because it's already very crowded so we're gonna numerate over the word in the reverse order and to check for partial enjoy in the reversed word and do the same app and to the Sam Traverse annotating the word index the same way but the in the fine part we no longer do this reverse anymore comment this out so we actually in the query would do that I left to right and so for that reason we have to change this as well make the syllabus smaller I don't want line breaks so it's going to be word and now since that when we insert the word is the reverse order and we've worried the word in the right order we have to change the order we put this to index it has to be I and note the word index the same thing the Resta should be the same for this full branch in the else branch do we need to change anything yeah we need to change the order we append the two pairs because now the query trainers on the left-hand side the past the left-hand side the past the left-hand side the past the nodes inside the we can get from the try passes on the right-hand side now passes on the right-hand side now passes on the right-hand side now so this has to change in the other direction as well we have to put I on the left okay on the right hand side so let's see so I just want to make sure that I put the reversed word inside the population but in the actual fine I'm using the word sensor so let's give it another try is working as well if we submit it's also working so the difference beside this too is that the first one been coming at all is that we insert word in the front left or right so but the second approach is that we insert word from right to left the thing about this is that the possible follow-up is what if this data follow-up is what if this data follow-up is what if this data structure has to support online operations so the this add operation has to base on the function we don't necessarily have the list of all possible words in the upfront so there are new words coming in we're still going to populate the past inside to try for any given new words and we won't also support this query so instead of giving you new merging over possible words is this going to be a single word stirring at us and we want to look at can we form a palindrome with the words we have noticed that when we push the pairs in the first even the first diversion is always on the right hand side in the modified version the I the query terms index the query term is always on the left hand side so but thinking about forming control this query can be on either left or right and we want to actually to return all of those possibilities so just using a single try does not satisfy the online requirement so we have to basically keep to twice one is inserted in the correct in the normal order the other tried the words are inserted in the reverse order and to search so this different two tries we basically just gonna you know have this commented version on one try have this on not commented version to go with the other try so that we can make sure we have both cases where the queries on the left and the courier's on the right so have two tries will support the online requirement to kind of follow up or to this question it's getting too long I have to cut off the video but you get the idea I think you get the idea if you really follow this one alright so that's the solution and a brief talk about how we can have to twice to handle the follow-up question okay that's it for follow-up question okay that's it for follow-up question okay that's it for today
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
1,750
hey everybody this is Larry this is day five of the Leo daily challenge in March hit the like button hit the Subscribe button join me on Discord let me know what you think about this PR uh yeah sometimes you see me click on contest because I remember but here today just happy lead coding so you quick you get 10 coins I don't know what they do but you know it's fun uh I'm not going to lie I'm a little bit tired right now a little bit uh yeah I'm 70 hours into my dry fast I feel okay actually to be honest but um I'm not going to lie uh I mean the point I mean point of the dry fast is that uh it's just hard to talk because my mouth is very dry um but I have only two more hours before I start drinking water and then tomorrow morning I'm going to start eating so I'm really excited for that uh man I am pumped and I um and just kind of a update for people who care about it um you know I don't have it on today but I had high blood sugar a couple weeks ago or you know I took a physico got but high blood sugar so then today I uh man I cannot be coing uh I'm not kind of put together but yeah but uh but I think as a result of this fast and just like I've been cutting uh the last month or so um I've actually kind of visibly see losing a lot of we under my sixpack like the fat that's next to all the uh all the organs the fat that's causing all the butt sugar issues probably so I'm definitely very excited about that it's uh yeah the RIS fat is I think what they c um so you got rid of a lot of that so I'm very excited to kind of um uh well one ye again and then bulk uh and also put in the CGM again and kind of see how every fits together and you know at the end of the day uh you have to do what it takes and um you know as much as I look young as people always say I am not young enough to not take care of my health and it can only get worse right so when you have your you know your health get becomes more and more important it was I mean it was it is always important but you know and it gets more important when you don't have it right just one of those things you take for granted when you have it when you have good health uh and you know just to kind of give you a sense of reference for the last one month and one week I guess because I did the last I started about like beginning of February so like I said month and a week I guess it's a short month but yeah I lost about 20bs uh so and of course some of it is water weight some of it is muscle so it's not good weight uh but a lot of it is still going to be fat so uh and like I said I see visible results in the risk grow fat so um I'm really excited to see you know where this takes me in terms of my uh my biom markers my health metrics if you want to call it that and all these things yeah anyway uh just thought I give an update because I get asked uh a bit of about this on my Discord so yeah uh and yeah it's not easy to lose that much weight in a month not going to lie but you know uh as I always say uh it's hard to change but it'll cost you to stay the same you know so anyway thanks for indulging me and listening if you skip ahead that's fine too uh it's not that important but I just want to give people an update let's take a look at today's problem 1750 minimum length of string after deleting similar ends okay so you have only a b and c in a string you asked to apply the follow algor at any time pick a nonempty suffix where all the characters in the prefix nonm oh okay and then suffix non empty suffix where Okay okay so basically prefix and suffix have to be the same and then you minimize it right so you have something like this move AA uh B then zero right left I'm trying to think whether this is always greedy I think that's my number one thing um it feels like it should because there's no reason why you want to hold back a character um like you could hold back a character so that it stays the same but then like it doesn't change anything right so yeah I don't know but in that regard it feels like a deck problem right so then now while L of Q is greater than zero and Q of Z is equal to Q of1 right so then maybe we do like this character is equal to the beginning and then uh while C oh sorry Q oh uh I think there is like an edge case where you have one character maybe because they canot add overlap so I guess this has to be greater than one right because you have one character that's like an edge case maybe I think yeah so okay so then L is greater than q and Q of Z isal to Z then q. pop left and then we also do the same for the end right and then this just pop and then return link for Qs um yeah I want to I do want to test that case where you have you know one character in the middle H looks good so let's give it submit okay cool uh huh I'm curious oh I just have this one here I was worried I was CU this seems like a mistake I would have made in the past but uh yeah I guess I wrote exactly the same code really except for that no I wrote exactly the same code okay pretty much I don't know why D is for Tech but I don't know but yeah um maybe for deletion I mean this is linear time linear space uh linear space for the deck and actually you don't even need a deck to be honest I voted using a deck just because of that other syntax is very clean right you can use two like pointers right pointers um and that should be fine too so then you could reduce that to constant space um but linear time anyway because you have to look at each character once uh yeah uh that's all I have for today let me know what you think I H I uh it's just hard for me to talk right now so I'm not going to do an extra premium problem I'll do one tomorrow so yeah we'll be good uh but yeah that's all I have for today let me know what you think stay good stay healthy to our mental health I'll see yall later and take care bye-bye
Minimum Length of String After Deleting Similar Ends
check-if-two-expression-trees-are-equivalent
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal. 3. The prefix and the suffix should not intersect at any index. 4. The characters from the prefix and suffix must be the same. 5. Delete both the prefix and the suffix. Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_. **Example 1:** **Input:** s = "ca " **Output:** 2 **Explanation:** You can't remove any characters, so the string stays as is. **Example 2:** **Input:** s = "cabaabac " **Output:** 0 **Explanation:** An optimal sequence of operations is: - Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ". - Take prefix = "a " and suffix = "a " and remove them, s = "baab ". - Take prefix = "b " and suffix = "b " and remove them, s = "aa ". - Take prefix = "a " and suffix = "a " and remove them, s = " ". **Example 3:** **Input:** s = "aabccabba " **Output:** 3 **Explanation:** An optimal sequence of operations is: - Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ". - Take prefix = "b " and suffix = "bb " and remove them, s = "cca ". **Constraints:** * `1 <= s.length <= 105` * `s` only consists of characters `'a'`, `'b'`, and `'c'`.
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Tree,Depth-First Search,Binary Tree
Medium
1736
49
Jhaal Hello everyone welcome to this video and welcome to shoulder and this video will see the program the question that is mudda nx100 withdrawal question and 28 mins of web based companies like facebook and twitter pure questions media ne bloody kisi to in this question website hai that One and Offspring Address Group and Comes Together So What is a Gram 500 Grams to Zara Mishra Board of Prayers for Pyorrhea Ranger Letters of Different Words and Affairs Typically Using All the Receiver Tractor Latest Events of What is Mean That Give Verses of the Great Cause Mental Attitude any other smooth one important question what so ever the are having same number of characters in sports teams life and customs in acquired head question second six dasharath matter but the number of public places of characters mirwaiz pet anti avoidance of liquid and one question and Pornography Petrol Verification Attempts Rescuers Meeting Opposition Advocate Mrigendra Se Bach Data Success Come To Your Mind For Watching This Is A Good Man Who Is This Person Software Cheap And Avoid You How They Can Check Who Didn't Dare Devil Wears subscribe Video then subscribe to the Page if you liked The Video then subscribe to the detention and content voice mail Google account ke charkha sirf report and which gives the backward classes account of both are significant and claims and declares that they have and sacrifice and not known today SPS Word Videos Present that lower surfaces way we app and dictionary infection duty basically key and value tree dry this next point how we can make problem is particular electronics and the value of birth defects of Veer Vikram subscribe to the Video then subscribe to the Page if you liked The Video then Of Frustrated Acid Present Scenario It's Not Amazing Second AIDS Patient Version Ulcer's 51st Ki Team Topper subscribe Video give a like and subscribe the Video then subscribe to subscribe Black Lips subscribe Example of List Listen Tweet To Next Which This Taylor Swift Unity And Snow And Students Not In The Forest Subscribe Point Us Give Up And They Love You To The List Of The subscribe to the Page if you liked The Video then subscribe to the App Lucky Ali 's newly installed unit to connect with his bed for better 's newly installed unit to connect with his bed for better 's newly installed unit to connect with his bed for better solution of bird's pencil not present in this like subscribe and view subscribe the world will be lit list start the meaning of the word in to-do list Of The Subscribe Button Study 100 liked The Video then subscribe to the Page Modern Features Tweet 9 151 Different Skin To Mix It Well Being And Of The Knowledge Factory Address For Electronics And Alarm Clock That Is For The Length Of System Giant Shopping Suede Leather Victim Gets 2252 Adventures Of Thought In A Peaceful VPN Of Key Suid For Execution Hey Porn Painting Amazon Let's Move To The Best Wishes In The Simran Method Kiss Minutes Is Time Plot For Nau Will Not The Places In President Anil Maintain Account Ericson Serial Actor Will Account For instance and questions page character in the thing and particular word share option so at this time printed to the list of awards and will appear of account contacted discounts for the value of practice na of activities Samsung this powder which very strictly half smaller characters but did not Like this order automatically but be covered in this app also editor shree cement block sector 121 chief requested tay 04021 12028 828 like subscribe button video to the currency of for example sentences with it will also be noted here that this and you will be amazed the president Visiting The Destiny Of Middle Order Edison President David Ine Swept Boil Insert The Will Also Create Hair Pack Lubricating The List Of The Map Of Trees And Crops In The World In Which One Will Create A Letter Of Intent Factor Of Prince Suvichar How Code Various Political System Has Been Installed Value To Date List Of The Particulars That A Dravid Test Person Will Get In Official Arrangement Of These People Blank Contest For Every Character Already Award Which Sacrifice Content Available A System Start Simply Minutes Developed Countries For The Best Adapted Surdas How This Nation Will Work Actively For Example Of Sacrifice Will Intimate Scenes Battery In The Morning Maintainable Been Created And Again After 10 Minutes Years To TV Show Improvement In Students Will Simply Check This Video And Jyoti Pradeep Saurabh's Cutting Similar Values ​​And Points Pet And Receive Values ​​And Points Pet And Receive Values ​​And Points Pet And Receive Notifications Shyam Values ​​mid- Subscribe Our Channel Like Life Of Every Word For Every Country And Use This Is The Value Of Small As A Small 1607 V0 Subscribe From The World Tour - - 09 Subscribe From The World Tour - - 09 Subscribe From The World Tour - - 09 Induction Porn To You Refuse Setting On Hai Arey Shiv Ko Hai But feng shui back print and infection gives and deposit years not reporting hence * will start scheme not reporting hence * will start scheme not reporting hence * will start scheme that lights out of elections from up and invited for its soldiers at such a guru can see relief a girl where is from by taking 0.5 video from someone 04021 middle aged person taking 0.5 video from someone 04021 middle aged person taking 0.5 video from someone 04021 middle aged person Must Subscribe To Chapter 3 Will Slice The Road Map And Its Evil Witch Cream And The Moments Enter Values Will Be Person Switch To Rowstring To Remove All These Words Into A Specific Playlist Will Be Person Bigg Boss Listen To Him Loud Will Make A Sentence For Everyone Day After Taking Over For Subscribe Functioning At This Time To Gain Benefits From Already Present And The Value Of The Year After All If You Have Not Subscribed Then Please Subscribe To Avoid Being And She Does Not A Quid Udaipur Dictionary And Will Simply Add Stree And Result Template Tips And Distribution Prospects For Details For Students Per Function Tuition Toss Use This Function Template For Similar Tests Now Password Enter Pushp 10 5820 Care Like Prs Centers Valid For The Cheese Paper Se Stitching Ides Arrow And First End Values ​​Can Be Set Aside End Values ​​End Values ​​Can Be Set Aside End Values ​​End Values ​​Can Be Set Aside End Values ​​End Second agro and second ga width list nipples were being evacuated the picture of all actors painted strokes and definition of tourists and difficulty of the servi and defeats a sophisticated i myself chords take problem hai profit half century there description for both maths vacancy train verses and speech In the cases different the question choose uncategorized by the account show that chatnis committed decide if solution in se 1000 after asking for this and interactive maps vidhi case of kidnapping for this being pursued account of the value se 0120 for every election counting of cricket player contacts In Severe Crisis More Than 700 Profit Rather Than Twitter For Every Character And Sorry For Every Word Tablet And The Are Energizing A Physical Work In English Puberty Pea Slow And Witch For Every Where Relative Word For Every Character In Word In Merger's Tubelight Discount C - 6 Press Merger's Tubelight Discount C - 6 Press Merger's Tubelight Discount C - 6 Press Bou Sharif Inverted Coms and Ecstasy - Bou Sharif Inverted Coms and Ecstasy - Bou Sharif Inverted Coms and Ecstasy - 1522 Rapidly Wounded Swapnil Increment 12th Particular Index for Example Intermediate Here Such Cases This Cut Scene Cold To One Thing Note Servi Verses Setting Network Hai Net Effigy In The Occasion Hidden Treasure of Every Citizen Should Simply Create New APN Fabric No Prodigious 0.5% Ad Tubelight Committee Dr. No Prodigious 0.5% Ad Tubelight Committee Dr. No Prodigious 0.5% Ad Tubelight Committee Dr. Unqualified Stick So Or Contact And Its Present Point Responsible Cassie Blair For Every Buddy Acting Different Are Cultured Work And Its Own Questions Page Thank You For Watching My Life Is Like This Video And ₹70 Question Easy And Thanks Video And ₹70 Question Easy And Thanks Video And ₹70 Question Easy And Thanks Watching Do Subscribe My Channel And Sizes Video Thanks
Group Anagrams
group-anagrams
Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** strs = \["eat","tea","tan","ate","nat","bat"\] **Output:** \[\["bat"\],\["nat","tan"\],\["ate","eat","tea"\]\] **Example 2:** **Input:** strs = \[""\] **Output:** \[\[""\]\] **Example 3:** **Input:** strs = \["a"\] **Output:** \[\["a"\]\] **Constraints:** * `1 <= strs.length <= 104` * `0 <= strs[i].length <= 100` * `strs[i]` consists of lowercase English letters.
null
Hash Table,String,Sorting
Medium
242,249
1,304
That Aapke Ajay Ko Hua Hello Everyone and Welcome to New Video India Go Into Another Problem from Decoded Problem No. 130 Fuel Overload Problem Said loudly that the young man came and told us Zanana whose subscription and all elements If we swear, if our questions are answered, then we subscribe, we can add any number, that is Amazon, we have to keep in mind that the number should be subscribed, first of all, if we have 125, then here we are looking at two cases, if 6.5 if 6.5 if 6.5 means this. Number So what can we do here if I appoint Sochu here this page number of Yuktiyukta here I will give 90 to everyone subscribe plus minus one appoint the president then what will we do then we 10 what will we do this The number is not to be repeated because for yukt, what will we do for this camphor and for if we will put one minus one officer appointed subscribe our number will be that our number will be 11 number then what will we do now we will put on one position We will put it in strong position number four line Adhir That so how do we solve it So now what will we do We will use this in this We will make it in Subscribe Village Hamara Ghaghra Main If Our N Oil Is Sn1 Sn2 110 Meaning If Our Appointed If Our Animated So what will we do, we will turn on the gas, what will we do with that electronic foot, what will we do with it, other accused number, subscribe abs, we will put our Ghaghra in every village, inch plus minus plus one, this is a and as soon as our pallu is over, we will have to go to China. For our Hey will be found if we see if our number instead of China and then what we will do is we will run our take again from equal to zero to tan and ideal two plus two and inside this what we have to do and we will run it he said Now what will we do inside this, we have to put these things and airtight plus one over there, here we have to put minus plus one and like the potatoes are finished here, what will we do inside this, we will put on that - - - - we will put on that - - - - We will put that as if it will be our K, both of us, we will return it to our friend, which will be our answer, if we drive it for five, then what will happen for A, the first one will be our I, this will be our N for this. Five our order that they are here first 2014 so airtel chilli and different colors hey man what will happen to us i plus one to our jitno zero 2051 and plus one more minus plus appointed will be provided - - - cognitive our Ghaghra - 150 and this will be our end. Appointed - put it in the last, he will put his zero Appointed - put it in the last, he will put his zero Appointed - put it in the last, he will put his zero and after that, as we finish, do our return. If we put it in front, we will get one minus one rights, then this is our simple subscribe, if you give the number, 19. Commission will increase unauthorized by 20 minutes then please subscribe - - - - Verb - Verb - Verb - Treasure 15 - 500 number will come out Fonts This is - Treasure 15 - 500 number will come out Fonts This is - Treasure 15 - 500 number will come out Fonts This is our simple then and if we give time complexity for it, time complexity is here how many of us, from where to where, which is our Ghaghra you used to subscribe our YouTube channel time being subscribe will be ours because let's paste this word this is our solution accused was not subscribed if ours was animated then what will we do if I say the same thing what did we do it is equal From toe one to I lid end let's go here what will we do or minus one sorry that this will be our end minus one from the same here because if you want to modify this our plus of electronics if we move towards 2070 is equal How far will we run this channel from two zero - far will we run this channel from two zero - far will we run this channel from two zero - I will have to run the gun, either we can run it for an hour or 06 - 06 - 06 - after that, if we are appointed within it, then we will have to do so. You can subscribe and here we can subscribe here and Here we have made the last element to him that it was war, he got it automatically, so we have appointed subscribe number for the ghagra that let's do our ghagra and let's see which one and what fiber we have got for it if we see. So our output was one minus one right result that this will be ours for which case this is our wrong input balance and for because our account is 0 - because our account is 0 - because our account is 0 - 2m that we should get like should get one so here. The mistake we made was that we modified the multiple here so let's see our plus minus subscribe So we have what we should have if we look at our - if we look at our - if we look at our - so this time we should have subscribe C plus in the court. Also, we paste the solution, subscribe to the tips and we will paste it, so we copy it so much that we maximize the selection, you face it, you have to declare first of all, so here is how to declare interior of science and so Here we have something like this but we have to make a distinction here, so let's make it by mixing, on this side we named our abs and subscribe, then if this is ours, if ours, subscribe, now there should not be any mistake, it is accepted, subscribe. The result is the result and it became our circulation which is then dowry C plus mission there death subscribe if we are appointed example subscribe if you have any diet then you can comment in the comment section below thank you for watching my video MP3
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
168
hi everyone in this video we'll be solving another lead code problem excel sheet column title so the problem states that we are given with an integer column number and we have to return its corresponding column title as it appears in the excel sheet so we know that a is the first column b is the second c is the third and uh so on so we are given with these type of numbers like let's say 28 27 and m and so on and we have to find the excel sheet column title so i have a sheet here so we are given with these numbers and we have to find the title so let's say if we are given with 10 it should be j and it can be anything more than z also so this is another example where 7 0 1 will map to z y so that's the problem i'll change my screen to explain how we can solve this let's take the examples that are given to us so first example is 1 this maps to a next example is 28 this maps to a b and last is 7 0 1 this maps to something i don't remember okay so let's take this simple example so before going into the solution i would like to mention that this problem is very similar to converting a number to binary or converting a number to hex and in this case to excel so the only difference is in binary we have only two character sets 0 and 1 in hex we have 0 to 15 or 15 we call f also and here we have 26 options to select 1 to 26 or a2 z so we'll follow the similar approach that is used to convert to binary or hex so what we'll do taking 28 will take modulus 26 this will give us 2 and 2 maps to b from the table that is given in the question then we will divide by 26 also this will give us 1 and then again take modulus of 26 this will give us 1 and 1 maps to a so we are our output is da in the end we'll reverse this and we'll return a b this is our answer so one of the tweak that we should do is instead of mapping from 0 to 26 we'll take the numbers from 0 to 25 that's just because taking modulus of 26 will give us the numbers from 0 to 25 so it will make us very simple to map 0 to a and 25 to z that's why whatever number is given will subtract by 1 so that my range becomes 0 to 25 instead of 1 to 26 and then we'll follow the same operation that we have shown here and again we'll divide by 26 and it becomes zero so we'll break here and whatever we have accumulated will reverse that and return so let's go back to lead code to code this as we saw we had to uh keep on dividing the column number by 26 and uh taking the modulus which maps from 0 to 25 and will map from character from so let's take a empty array or list and loop over this column number that is given to us till this is more than 0 and as we discuss that we have to limit the number from 0 to 25 instead of 1 to 26 which is given to us so this will map from 0 to 25 instead of 1 to 26 that's why we are subtracting here by 1. we'll take modulus of this now this will give us a number from 0 to 25 we'll take care of this in python we can use chr and we'll use 65 plus v 65 is the base for us because 65 maps to capital a if we see the sky codes and we have to map from a to z so whatever is the value of e v it will be mapped accordingly and then we have to append in this we have that character and in the end he has to divide this by 26 also and yeah we'll get the result in press and we have to reverse this because we will get in opposite order so we'll take modulus of uh 26 on 28 it will give us b but it is in the reverse order that's why we are doing reverse here and then we'll return but this is a list will has to convert it to string and then it should be good so let's take all the examples and run this accept it and let's submit this accepted so this is the solution for this problem excel sheet to column title now we can discuss about the time and space complexity of this one so this is also straightforward i'll recommend pause for a second and then think about the complexity okay complexity totally depends on this column number which is given to us and what operations we are doing these all the operation we are doing are order of one and we are every time dividing this by a 26 so whatever is the number every time it gets divided by 26 so what we can do is as with binary search the time complexity of this one will be order of log n just because n is the column number that is given to us just because every time we are dividing it by a 26 so it gets divided by power of 26 that's why this is a logarithmic algorithm and mind you in this case the base of the log is 26 because we are dividing by 26 and not two in every other algorithm let's say binary search we divide by two that's why the base of the log is 2 in this case it is 26 so i'll mention here base 26 space complexity will also be same as time because in every time we are inside this loop we are taking another character to save the result that's why the space complexity will also be log of n so that's it for this video see you in the next one bye
Excel Sheet Column Title
excel-sheet-column-title
Given an integer `columnNumber`, return _its corresponding column title as it appears in an Excel sheet_. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... **Example 1:** **Input:** columnNumber = 1 **Output:** "A " **Example 2:** **Input:** columnNumber = 28 **Output:** "AB " **Example 3:** **Input:** columnNumber = 701 **Output:** "ZY " **Constraints:** * `1 <= columnNumber <= 231 - 1`
null
Math,String
Easy
171,2304
1,502
hi guys good morning welcome back to the next video although uh usually you would see that the explanation of easy problem never comes on our Channel uh for the daily problems but this question oh God although to solve this question you can solve it in three lines in under one minute but the way to go from Brute Force to better to actually optimal it's insane it can be a high chance that it can be asked in an interview and the interview might ask you okay give me the most optimal solution of this problem and to understand that part is actually the tricky part cool no worries we'll actually go into this problem very quickly you just say that we are having a sequence of numbers is called an arithmetic progression called as an AP if the difference between any two consecutive numbers is the same is basically if you know AP is nothing but a sequence of number in which the difference between two consecutive numbers is the same cool um so for sure if there's a standard formula although if you don't know a formula itself you can simply make an AP as a A plus d a plus two D A plus three D up to so on a plus a minus 1 D why such that because for sure you will see that the difference between two elements it's D this difference between all the consecutive elements should be same it should be same here we should we make less d for sure you would easily see that this sequence will be increasing or decreasing or same which means we which means it can be non-increasing means it can be non-increasing means it can be non-increasing non-decreasing non-decreasing non-decreasing or it can be same right increasing decreasing or same does you can easily see that the difference between exactly d right okay one thing for sure and also if you want C please if you want to get better at maths please add a question itself just understand the formulas there's a high chance that although in this problem this formula is not used and you can easily make this formula but I highly recommend please it's a basic formula of arithmetic progression which is in the term of an arithmetic progression is a plus n minus 1 D it is the nth term of an automatic progression and the first term we name it as a which is the A and it is the editor so for sure by now you know okay AP looks something like this a A plus d a plus 2 D and it can be increasing or can be decreasing or it can be same right so that the D will remain same and also please remember that arithmetic and it is not using the problem although you can also drive this from here also but still I highly recommend to remember the fact that any term of an AP is a plus M minus one B cool now if you just go back into the example then we saw okay we want to know if this sequence is an AP or not and we know for sure that a sequence will for sure be increasing or decreasing right so we are only concerned about if this sequence is an AP or not so first thing which comes in your mind is okay just sort the sequence will become something like this now the difference between positive elements should be two Photoshop which means it should be same which means the difference what is here it should be exactly the same what is here and so on so forth so I just sorted this sequence out it became one three five the difference is 2 okay it's an AP I can easily say that part why because we saw that our AP is made now the same concept I will apply this here one two four I'll take the difference okay it's one it should also be one but it is two okay because the difference should be same it's a prime condition of the AP cool um we have the constraints pretty less we know okay we can simply sort this down we can simply sort of this sequence what so whatsoever sequence we have we can simply sort that down one three five seven and nine find the difference two simply say okay the difference between all the elements is the same as for sure it will be and take p as a result so simply you know one part just sort it down when o of n log n and then after when it is sorted just see okay just check if the difference between consecutive elements just start from I equal to 1 and do a ie a of I minus 1 which means a of I minus 1 it is the difference if the difference is the same for all the I's starting from I equal to 1 to I equal to a minus 1 you can simply say that it's an AP if it is not then in the mid also you can return a false so it is the one way which is the Brute Force way which comes straight to your mind it's a it's the reason that it is marked as an easy problem because it can struck instantly and you will solve this by a brute force in O of n log n and you are not using any extra space so it's a reason it is over one but now I ask you optimize it make it better just better so what you will say Okay ultimately what I was doing is I know okay it is a sequence I know that it is my input sequence one three nine five seven I also know that the output sequence would look something like one three five seven nine right so how about okay I can iterate on this particular array and I would know what is the minimum element because to generate this ape to generate this AP what you need an A and d right okay Aryan to get an A D what I can do is and I have some elements random elements I ca I won't notice a plus d what is a plus two D what is a plus d i I don't know what the mid elements but for sure I know one thing what is the smallest element and what is the largest element it is one thing I know for sure I don't know the mid elements because mid elements can be in any order but the largest element and the smallest element in this array it can be here also it can be like okay five seven nine one three so the largest element will always represent a plus n minus 1 D and the smallest element will always represent a I know n for sure one two three four five n is five a I know because of my smallest element now I know the largest element is a plus n minus 1 d largest element is 9 I know a I know n which is three n minus 1 is 2 so I can easily find a d from here so ultimately my aim was to find an A and D to generate this sequence itself I can know by just getting the minimum and the maximum element so for sure what I will try to do is I will try to make my own sequence and to make the sequence itself I just needed a and a D I got a for sure to get a d I just got the largest and to get a simply iterate on this particular array find the minimum value find the maximum value minimum value is 1 maximum value is 9 minimum value represents a maximally represents the last element of the AP which is nothing but a plus n minus 1 D we know the a I will replace a here I know the N which is the number of elements in this entire sequence it is 5 1 2 3 4 5 so 5 minus 1 is 4 so basically D will say 9 minus 1 by 4 which is 8 by 4 which is 2. as you will see the D was actually two also so I know the D I know the a what I will try to do is I know okay the first element of this sequence will be a the second element will be a plus d the next element will be a plus 2 D next will be a plus 3D next will be a plus 4D so I know K one element in this sequence should be a okay cool iron what I will do is I know okay the first element it should be a which means one so one should be present in my this particular input because see now I just know what elements I need to expect a I need to expect one three five s five and a nine and how I can make this by simply using this A and D but now I need to check if these elements are actually present in my input sequence or not so what I can simply use a hash set an order map in order to set anything like that with that help what I will do is I will just say Okay is one percent in my input yeah how to know that by simply using an unordered set or an unordered map anything you can use to just locate if one is present cool yeah one is present is three percent yeah three present is five percent yeah five percent is seven percent yeah it is present it is nine yeah nine is also present okay it is for sure my input was actually an AP so basically I did not need to sort this entire thing out I just generated and I just generated this particular entire thing by myself or you can simply say okay the first element it should be a which means just go and search for one next element should be a plus d just go and search for three next element should be able to be just go and search for five next element should be just go and search for 7 which is a plus 3D by so on you will just go and search it in this if it is present just remove it or simply do in anything you want or simply use a audit map or simply reduce the frequency and stuff but simply go and check if it is in your input if it is good if it is not then simply return of false by this you know one thing for sure you did not need to sort it you just generated your own sequence by using your A and D and how you found your A and D by simply using your minimum and the maximum element by this your time will be nothing but o of N and space Also to offend because you are using an unordered map or an ordered set now comes the most interesting part I again ask you optimize it how you how will you do that part simple as that now see you optimize it now you know okay you can't use an unordered map or an unordered set to actually compare with your original sequence so for sure and you think of something else I know it is my sequence I know my expected sequels go to something like this so why not see I was just confused okay one was at this right location I can see when I say okay I can't use extra space well I will try to optimize or something that um maybe I don't want to store the correct location of that particular element which means uh for one for three for nine I don't want to know the exact location I just want okay at that point if it is not at the right location I will just push that element to the right location which means if I just go on to the sequence I know for sure I'll simply use the concept I learned here by simply generating the actual sequence I need right I know one I know the minimum I know the a is one I know that D is two right I'll try to generate the sequence itself one is at a site location three is at the right location which means the first element will be one next element will be three next element should have been seven but it is here sorry next element should have been five but it is here nine so now earlier my concern was next segment should have been five so I was looking at okay is 5 present in my array now for that I need to store the occurrence the frequency of Phi or basically the occurrence of five right rather just okay 9 is present I will ask hey if 9 is present here what can be the location of 9 so that I will just push that line to its correct location so that later when I will go on to mine I will just say Okay K9 oh you are here so basically that I will try to do is I know nine now I can't use extra time I just want and I also can't use extra space I am simply trading I want to add this iteration itself 9 was not something good I don't want it for I don't want this nine but what I can infer from nine is simply just okay what is the actual expected index it should go to explain this it should go to S4 how we know that simply because we know if I have a sequence as a A plus d a plus two D A Plus 3D and so on and so forth if the indexes are zero one two three four simply no we okay the element at the ith index it should be a plus ID as simple as that because C it is a plus n minus 1 d right for the index i as n minus 1 your element is a plus M as one so you can simply infer okay the element at that index it should be a plus ID so if the 9 is present here I for sure know one thing okay what is the expected position of 9 is here if I just do a A plus ID a is already I know because of the minimum value i in doubt D I already know why because initially because of the above thing because of the minimum maximum element I found out my A and D okay my A and D is found A and D I have known I will find the i is found out to be 4 which means it will just say me one thing hey nine expected location is actually index 4 not index two so please do one thing make this nine make this a nine go at its actual location okay nine will go at its actual location but what about this actual what was actually at index 4 it will just come at the place of time as simple as that but now you will again see okay this seven came at this location nine went at its right location but still the expected value was not the seven it was actually five still until then unless the actual expected value comes at my dislocation I will just keep on repeating the process which means I will just again Ask hey a plus ID which means 7 is equals to 1 plus I into d 7 I is equals to 7 minus one is six upon 2 which is three expected location of this number seven is index three so please Heaven you should go to your index so it will go here and the five will come here you saw five came back to its location and seven is at its location so it can be a possibility that this element is not at the site right location but still we saw okay now it is at its right location but because of this Index right here my nine went on to its right location my seven went on to its right location now ultimately my five also three more Its Right location so you saw at every swap at every Loop occurrence my one element is going on its right location so basically as soon as you go on to the fight now that my main array is one three five seven nine now I was at five okay it is at the right location now as soon as I go on to the next element it is also at its right location because of this five this seven came at its right location that's the reason that is the reason that you will at Max go on to every element twice how twice Aryan you saw right I went on to seven once I was here which means once my seven came in here then I went on to this seven and put that as 7 to its actual occurrence which is here and then when I iterated on the next element so again I occurred it but now it is at its right location so basically when we touch an element either we actually either it is actually okay it's at its good location or at Max you will actually place it to its right location and next time when I will again occur it would have been at this right location so basically at Max I am touching every element twice that's it because see in one occurrence it will just go into its right location in the next occurrence I will just go and skip that because ultimately I will know okay it is this element it should have been a plus ID only and it is a plus ID also so I can just move on to the next element and so on I will just keep on going as you saw what will happen I was at one and I should be having a A plus ID which is one only which is one plus I as a 0 1 plus 0 into 2 it should be one only okay cool skip move on to the next element it should be a plus I into D it should be three yeah it is there okay skip now I am at 9 it should be actually nine it should be actually a A plus I D A plus I is 2 D is two so it should have been five but five is not there so for sure it is not addressed right location so cool no worries just see what is the expected index for this number I we saw it is actually a four so I will just move this 9 to its actual location and now it will come again I will just say okay is it equal to the number which is expected no it is not so again go and find its index which is its expected one which is 7 is equals to 1 plus I into two I is actually a three plus please move this number two is expected location so I will just move this number to expected location by simply doing a simple Swap and then again I will just go and check okay if this number is actually the expected one yeah it is cool no worries just move on I will just move on if this number is expected yeah one plus I is actually a one zero one two three into two yeah it is a number it's the expected cool no worries move on to next if it is expected yeah uh one plus four into two which is nine yeah it is expected cool no worries oh my ad is finished yeah it was actually a correct sequence and that is how by simply not using an anode map by simply judging okay what is expected location it can be I will just go on to that location and simply finding the answer let's quickly and you saw right the time is nothing but o of n because you are using you are touching every element just twice space is over fun because you are not using any extra space at all right cool let's quickly see the code firstly as very short I showed you that I need to find my A and D to find my A and B I need the t 0 which means first element and the last element first element is a last element is a plus n minus 1 D so last element is maximum element first element is the minimum element I will get the a for the last element which is the maximum element I know the a I know the N I will simply go and get the D so I will just go and firstly find the minimum and the maximum value of this entire sequence because of this minimum maximum value I know the minimum value is nothing but the A and the maximum value because of the maximum value I can easily find the D so firstly a small check that okay my a plus n minus 1 D which is the maximum value it should be the maximum value so for sure if it is let's the max value let's say it is a MV so MV minus a upon n minus 1 it should be a d so for sure that m v minus a which is the max value minus a it should be divisible by n minus one only then my D can actually come in so that's the reason I just drew a simple uh sanity check that okay max value minus a it should be a visible by n minus one only then it is actually a number or else I will simply return a false right now if it is divisible I simply go and find a d now I simply go on and it start iterating my entire array it's a simple while loop because you saw that it can get um it can get a simple if it was 9 5 and 7 it was at this index for three times when the nine was being swapped when the seven was being swapped and now ultimately when the 5 was here so ultimately I'm using a while loop you can also use a for loop it's up to you now simply I do check okay if that number is actually present at that index it's actually the expected value which I had which is a plus ID many values is nothing but a so it is actually equal to a plus ID if it is then do simply go on to the next element but if it is a knot I will simply go and check if this is not go and try to find its expected location so what I will do is I will try to go and find here it was 9 5 and 7. I need to find the expected location of my a plus ID right A Plus ID I know a I know D so I need to go and find the expected location off of what of this particular element which is a of I here it is a of I so I need to find the a of I expert location I know A8 is 1 I know D it is two so basically a of I minus minimum value upon 2 which is D it should be equal to Y but for that again I have to do a S and the check that okay it should be actually divisible by 2 so basically a of I minus minimum value it should be divisible by my D so it was simple and check again a 5 minus minimum value mod b it should be it should if it is not equal to 0 which means it is not divisible so it is a simple handy check if it is not I need to return a false if it is I will simply go and find the possible location of that particular a of I by simply doing a of I minus Min value which is a upon D so it will simply get the possible index of that particular element a of I and by this I know K it is a possible index and I also know one thing that my earlier part is entirely correct so this particular element its occurrence should be Beyond this range which means beyond my location I it should be there if I need to swap that so because earlier part I know it is already sorted it is already exactly in AP so this occurrence this its occurrence it should be in the later part right so I just had this simple check okay this possible location if it is less than I you are screwed up it is not an AP and also what if the possible location value is itself the same as that of ao5 which means if I would have said okay its actual location is at the index 4. but at index 4 also again I have a 9 then you will see that it will stuck into an infinite Loop it will go 9 here it will again 9 come will here nine will go here nine will come here I will go here I will come here so it will again it will go kick keep on going in an infinite Loop that's the reason I have to put and check that okay if the possible index value and the actual index value if the both are same please you are screwed up please return a false else if it is not the case then simply do a swap because I know by swapping the value I am putting my 9 at its expected location which is the possible location by this it will simply go and add Max at in the worst case it will simply go two times at every element is touched two times at Max and thus the complexity of this Loop is nothing but o of N and simply I can return it true because simply this Loop is complete which means I have gone on to every element I know this video has gone up pretty long but that's the reason I have to make this easy questions video because I usually never make it for sure uh I usually never ever make it because easy questions are just simply done but yeah this question was actually amazing it's an interview problem a math being applied optimization being done at another level thinking of that part is very tricky that is the reason I just try to make it I hope that you guys like it foreign
Can Make Arithmetic Progression From Sequence
construct-k-palindrome-strings
A sequence of numbers is called an **arithmetic progression** if the difference between any two consecutive elements is the same. Given an array of numbers `arr`, return `true` _if the array can be rearranged to form an **arithmetic progression**. Otherwise, return_ `false`. **Example 1:** **Input:** arr = \[3,5,1\] **Output:** true **Explanation:** We can reorder the elements as \[1,3,5\] or \[5,3,1\] with differences 2 and -2 respectively, between each consecutive elements. **Example 2:** **Input:** arr = \[1,2,4\] **Output:** false **Explanation:** There is no way to reorder the elements to obtain an arithmetic progression. **Constraints:** * `2 <= arr.length <= 1000` * `-106 <= arr[i] <= 106`
If the s.length < k we cannot construct k strings from s and answer is false. If the number of characters that have odd counts is > k then the minimum number of palindrome strings we can construct is > k and answer is false. Otherwise you can construct exactly k palindrome strings and answer is true (why ?).
Hash Table,String,Greedy,Counting
Medium
null
1,611
One welcome to my channel code sir with mike so today we are going to upload the video number of the playlist of our bet manipulation topic lead code number 1611 is hard marked it is a very good question after explaining it will not seem hard but to come up with The solution is very challenging, okay, we will understand that well. The name of the question is Minimum One Bit Operation to Make Integer Zero. Lingnan asked this question. Ideally, such questions are very bad in interviews, generally because it will take a lot of time. To come up with this approach, what happens most of the times is that the interviewer gives you hints so that you can go in the right direction, so today's problem will also be solved in the same way. We will see how an interview goes when such questions. When it comes to OK, it says that you have been given an integer zero, you have to convert it into zero, then you can use any of these two operations, okay, the first operation is quite simple, it says right most bit. Okay, which will be the right most bit of your integer, assuming n is given as 3, then what will be its binary representation, then you can change the right most bit, change means one, then you can do zero, if it is zero, then you can do one. If you can, then yes, here you have to convert to zero, so I have zeroed the right most bit, you can do it at once. Okay, so this first operation is done, pay attention to the second operation. What does the second operation say that let's assume a number? Its binary representation is this. Okay, so that any if i bit you have to change i bit in binary representation of a if the aa minus w bit set for example if let's assume this is aa bit if you If you want to change, then it is okay then i minus one bit means this one is ok and should be one and from aa bit till zero bit, all these and all the further bits should be zero, only then you can change this i bit. If you can, then let's see here whether you can change the i bit or not. Let's assume that this is your i bit, you can change it. Let's see, there is one in i-1, f you can change it. Let's see, there is one in i-1, f you can change it. Let's see, there is one in i-1, f is good, but look at the ones after i-1. The is good, but look at the ones after i-1. The is good, but look at the ones after i-1. The bit is not zero, all of them are zero but if it is not zero then you cannot change it. Okay, so let's see another example. Let's assume ours is something like this. Let's assume the I bit is yours, so you can change it. You can see, aa manav bit is one, chch is good and all the bits after aa myv are zero, so you can do this, it is ok, you can do zero, if there is zero then you can do one, exactly these are the two operations. And you have to tell what is the minimum number of operations required to transform a to zero. Okay, let's look at an example. Let's assume that y is placed on y. Okay, so the binary station of a is nine. Okay, you have to convert it to zero, that means zero. To convert to zero, okay, so if you pay attention, this is my zero bit, this is my first bit, okay if this is my eighth bit, then look at my eighth bit, it is one and all the bits after that are zero, meaning any. If the bit is not there, then let's take the value of zero. Okay, so we can make it zero by the second rule. If the first bit is there, then what will it become? It is converted into 0 and okay. Now look here, in this you right most bit is one. So what does the first rule say that you can blind change the right most bit so I will change the right most bit from G one to zero then this zero will become zero then how many steps are taken one two so our answer is two let's try two Solve it just like we should do in an interview. Okay, so we know that the first operation can only change the zero bit, that is, the right most bit. The first operation used to say that only the zero bit can be changed. You can, but apart from that is, if you have to change any other bit apart from the zero bit, then you will have to use the second. Okay, and you must know that to use the second operation, if you have to change the I bit, then you will have to use the second bit. There should be one in the th bit and all the rest should be zero. Okay, now let's come in general, what will happen is that you will get a hint in the interview. Okay, so the first question that may come is in which direction should we solve, left to right solving. Should it be solved bit by bit or right to left? Should it be solved bit by bit? Okay, so the answer is that it should be solved left to right. I will tell you its reason. Suppose there is a number, its binary representation is this. Okay, and because of the value here But there is one, so if you are solving it from right to left, that is, from right to left, you are doing zero. Now let's accept that you have come here. Now see, this is the right most bit, isn't it that you are solving it first? Make it zero by operation, to change it you will have to use the second operation and what has to be done to use the second operation, this is the eighth bit if then there should be one in the aa minus th bit, right all the rest are zeros but bring one here. You will have to do some of the old operations again, you will have to convert it from zero to one, but we have to find out the minimum number of operations in which you can convert it to zero, that is why do not go right to left, what will we do left to Okay, we will go right, we will make this zero and so on, then right, we will go left to right, okay, so this is the most genuine reason I felt that why we should solve this problem from left to right, okay, now comes the most important point. What will happen in general? You will usually get blocked even with so many hints because this question is quite tricky. Okay, so the interviewer generally gives a hint. You can also ask for a hint from the interviewer. So what will the interviewer say to you in general? What if there was only one set bit in a. Actually, here the interview is trying to give you a hint. Okay, so look, pay attention. Because of the values, I am giving you such an example in which only one bit will be set, like see its binary, what will happen. 00 Look, its I bit is okay, it is the right most bit, otherwise you cannot do the first operation, you have to do the second operation. Okay, what is your M that you have to zero this eighth bit, just but zero this eighth bit. What will you need to do? You will need one even in the second bit. Right, so the biggest problem is that we will need one, so look, pay attention, it is 100, what do you have to convert it into, why if it is 00 because this one is available. Okay, then you can change it by applying the second rule, so if you want this, if you get this then what can you do comfortably, now you can zero the I bit or your Aa bit. Why, because look at the minus and butt, there is one and the rest are all zeros, so it will be converted to what kind of zero, the rest is still zero, okay, now it comes to the question that this row has to be converted into ji, right? If you want to convert into G, then pay attention to one thing, when you went from here to here, x steps were taken as per the value. Okay, as per the value, x steps were taken and see what changed here, it is one but after changing to 00. Look, when 1 is converted, here I am writing how many steps were taken to convert 00 into 100. One step is fine, or you can also write it like this, 100 was converted into G, which means the number of steps required to reduce A to zero. You should know that it will take steps to convert zero to n. Okay, if you want, you can write it in such a way that if you convert 00 to 100, it will take It is clear till now, so look, now let's come back to this question, this was our input, we converted it into this, so it took So we changed it to zero. Now when it comes to converting this 100 into 00, then remember I had told here that the number of steps required to convert 100 to 00 is the same as the number of steps required to convert 00 to 100. Remember, here we had converted 00 into 10, it took That total took 2 steps, it's okay, now see which one here took 2 steps to convert, this one took 2x steps to convert, okay here only one bit was set, this one bit was set, okay so So let's see which bit was set as 0 and the third bit was set. Okay, let's assume that if the first bit is set, only one bit is set. We are solving a small problem, right now, the interviewer said. That is, if there was only one set bit, then how many steps would it take for you to convert it to zero. First they are removed, after that the rest of the problem will be seen. So if only IA bit is set then how much it would take. See, 2 * how much it would take. See, 2 * how much it would take. See, 2 * x PSV steps. It seemed clear till here, pay attention to Y, what is actually in Look here, we reduced it to zero, so which bit is it? Aa, it is a human bit. Aa, look at the human bit. How much did it take to convert it into 00? It took one. Okay, so I can say here, not 2 * x. I can say here, not 2 * x. I can say here, not 2 * x. By doing this you call it 2 * f of i -1 + 1 By doing this you call it 2 * f of i -1 + 1 By doing this you call it 2 * f of i -1 + 1 because What I want to say is that f is equal to the number of steps or the number of operations required to make it zero and what is the meaning of A, what kind of number is it and is a number in which only the I bit is set, okay all the rest. is unset, let's say this is here and this is eight, let's go by the value, okay, and a man, what does it mean that a number in which a is only a minus t is set, okay, so it is taking to convert it to zero. It will take F to convert to zero. It is clear that here I saw that the driver had said that if one bit is set then how to find it, so we have worked it out and shown it. Let us also see the example. Let's say that n = 2. If it was given, then first let's that n = 2. If it was given, then first let's that n = 2. If it was given, then first let's write its binary pension as 1 0. Okay, so look, notice that this is the zero bit, this is the first bit, so look at this i = first bit, so look at this i = first bit, so look at this i = one, meaning the first bit is set, in this also there is only one bit. If it is set, then first we find out without the formula what answer will come, after that apply the formula and see whether the answer is correct or not. Okay, so if you have to convert row into zero, then what will you apply first of all? You will apply the first rule, right. By setting the right most bit of the most bit, you will convert it to one, then this one will become one, after that what will you do by applying second rule and see how this eighth bit will become zero. If you want to change it then come -1. There should be one, all the rest then come -1. There should be one, all the rest then come -1. There should be one, all the rest should be zero, then there is something else on the right side, otherwise it will be zero. Okay, so one rule, we converted it to 0 by applying second rule. Okay, now again we will apply first rule again and what is the first rule? It says that if you can change the right most bit, then zero is converted into zero, one step is taken, two steps are taken, three steps are taken, that is, what will be its output, three total operations will be required, now the formula to convert n = 2 into rows. Let's see whether it is correct or now the formula to convert n = 2 into rows. Let's see whether it is correct or now the formula to convert n = 2 into rows. Let's see whether it is correct or not. Okay, so look at n = 2, not. Okay, so look at n = 2, not. Okay, so look at n = 2, which bit is set. If i = 1 bit is set, then which bit is set. If i = 1 bit is set, then which bit is set. If i = 1 bit is set, then here i = 1 bit is set. here i = 1 bit is set. here i = 1 bit is set. What was its formula: 2 * f of What was its formula: 2 * f of What was its formula: 2 * f of i - 1 or The bit i - 1 or The bit i - 1 or The bit should be set. If it is ok then f aa = is set, meaning it is not zero, it is ok. then f aa = is set, meaning it is not zero, it is ok. then f aa = is set, meaning it is not zero, it is ok. I have written it in binary as 2 in aa my means you can write it as zero i-1 is 0. Which is the means you can write it as zero i-1 is 0. Which is the means you can write it as zero i-1 is 0. Which is the number whose zero bit is set? It is just one. That number is right. This is the binary representation of one. Its zero bit is this. How many steps will it take to convert it into zero. Why is it just one step? Because by applying the first operation, we will convert the right most bit into zero. It will take only one step, that is, we already know the answer, f0 will always be equal to two, okay, 2 * 1 P 1, that is the equal to two, okay, 2 * 1 P 1, that is the equal to two, okay, 2 * 1 P 1, that is the answer, 3, then see, the answer is correct, that is, our formula is absolutely correct, but this is just It is applicable for those numbers which are power of two or in which only one bit is set. In which only one bit is set, obviously it is in power of two. Okay, now coming to our last Topic P which actually is our question is what if we have multiple bits set meaning let's say our example was something like this 0 means let's say 00 example if it was like this what does it mean n what is mine given 12 48 that is 12 is given, then how will it be? Just a little while ago, we had solved an example in which we had converted 000 into 00. Okay, so how many steps did we have to take. Let's go by the value. Remember, 2x 1 steps were taken, okay? During this time, this state of ours also came in between because it is obvious that when will you be able to convert it into zero, when there should be one here, right, then we first converted it into this, we first converted it into 00. After that, it was converted to zero by doing something, okay, so what do we actually need? Look, pay attention, we need this answer and not to convert it to zero because the question has been asked to us and we do not need this. Do it in zero, but look, we already know it, so look, pay attention, we know it completely, how much does it take to convert a pi into 00, we know the simple formula which we learned above, because in this only one bit is set. So if we know it, okay if we subtract this part from it, then we will get this. I am repeating again, remember, we already know how many steps it takes to convert 1 to 00. Okay, we already know this from the formula and this step also comes in between the conversion, isn't it and this time we have been asked the same in the question, okay, so it is an obvious thing, I know the value of the whole, okay and If I know how this value is, then I will be able to find out what I actually want, how many steps will be taken to convert it to zero. This is what was asked in the question, it is clear here, what am I saying that if I want the answer? What will I do to convert 00 to 00? To convert f100 to 00, I already know how many steps were there. We will subtract the amount of A of 100 to bring it to 11. Whatever we thought is fine, I have shown the diagram here. I also told that if we subtract so and so from so and so, we will get this one, so now pay attention to one thing, pay attention to this part, okay that means pay attention to this part, here you are looking at the part with 00. We have converted 100 into 1. You can also write it in reverse that we have converted 1 into 00. Same steps will be taken in both. See, I can also write this like this. See what we actually did. This G was converted into 100 Na, so I write it like this, the G part has been converted into Na. Look, one is the same, it is fine and you can also write it like A of 100. 0 was converted to 00, here I told you the same thing, both are equal, okay, so I replace it and write this here, removing all this, I write this here in the equation that 100 was converted to zero, okay So now pay attention to one thing, what is written that trip has been converted to zero, remember what it meant, which bit is this zero bit, first bit, second bit, third bit, that is, f of 3, this is the value of f3. Meaning, what was a number whose third bit is set, by converting it to zero, the value that will be obtained is f3, okay, here what will happen is the zero bit, first bit, second bit is f out, yes, it is okay, so that means f100. To convert, it will take f3 or f2. Okay, what is f3, nothing. F3 is a number whose third bit is set, meaning 00. Okay, in the simplified form, I have just written, okay, look, pay attention to this pattern. It is a little f100, this is the zero bit. This is the first bit, this is the second bit, this is the third bit, so look at the third bit f3, the second bit minus of f2, okay, what is the meaning of the third bit f3, see the amount of value taken to bring 100 to zero and what is f2, what is the amount of 100. Steps to convert to 00: Okay, now let's take another big to 00: Okay, now let's take another big to 00: Okay, now let's take another big example, let's go with the value of f off 11001, there was an example like this, see 0 1 2 3 4 5, first let's break it, the fifth bit of f off or the fifth bit if There is only one and that is 1 2 3 4 0 1 2 3 Another 0 will be 0 1 2 3 4 5 Look, how much will it take to convert the fifth bit to zero, okay minus the remaining f of 1 How much will it take to convert it How have we written this equation? It is written here exactly as it was written. Look, this is 1100, so first we wrote 1. Look here, we did a minus, then this is 1. Okay, we are doing the same here this one was one, the other five were Put zeros, okay, the minus which is remaining is 1001, 100001, okay, now look, pay attention, this is very simple, you can get it from the formula because there is only one bit set in it, okay, so this is 10 minus, look at this. bit is multiple bits, this too, then let's think in the same way, minus one off, look, this is one, how many zeros, one doti, minus one, how many remaining, 00, okay, let's open it a little and see, offv one doti cha pa. Minus a ofv a doti ch plus minus plus done a 00 okay now pay attention to one thing here the pattern must have been caught look in this only one bit is set this also has only one bit set in this also only one bit is set okay So look here, if the fifth bit was set one, then what is this, actually it is f5, okay, the fourth bit was also set, this is f4, look here, the second bit was set, so this is mine, look, so f is not off, the first bit is set there. But this is f of f, look at the science, here first it was a plus, then look it became a minus, then look again it became a plus, if something else had happened next, then it would have been a minus, then if something else had happened next, then it would have been a plus and so on. Okay, so if you look at it, our solution has become very simple. If we assume that we have to find out any number of 10 1, then first of all let's see which of its bits is set to one or zero bit or first bit. The second bit is the third bit is the fourth bit is okay so the fourth bit is set neither A4 okay look the second bit is set minus at the fur look zero but set plus g that's all we have to do is keep alternating the sinuses plus minus plus. Minus and so it has become quite simple, we just have this, right? Done, it is f4, which means it is a number whose fourth bit is set. Okay, so we will take it out in advance and store it. From the formula, what was my 2 * f of what was my 2 * f of what was my 2 * f of i-1, we will take it out in advance and i-1, we will take it out in advance and i-1, we will take it out in advance and store it in a. There can be maximum 32 bits in the number, okay, so let's take all the bits as T and so on, we will take an array of size 31 but 32, okay, where we name this array F, where A0, what will be my key? The following formula will be the one which you already know, if suppose you have to take out A4, then 2 will be converted into A3, right? And F, if you have to take out 3, then f3 is very easy. 2, not f2, 1, okay, what will happen to f2, 2? * f ofv pv and f ofv what will happen to f2, 2? * f ofv pv and f ofv what will happen to f2, 2? * f ofv pv and f ofv what will happen 2 * f0 pv and f0 we already what will happen 2 * f0 pv and f0 we already what will happen 2 * f0 pv and f0 we already know what is 2 1 2 p 3 i.e. f0 1 know what is 2 1 2 p 3 i.e. f0 1 know what is 2 1 2 p 3 i.e. f0 1 this becomes 3 then what will f2 become 2 * f1 this becomes 3 then what will f2 become 2 * f1 this becomes 3 then what will f2 become 2 * f1 p 1 2 * 3 this is 7 It will be done and so on, so p 1 2 * 3 this is 7 It will be done and so on, so p 1 2 * 3 this is 7 It will be done and so on, so we will fill it in advance and then we will come to our input and see which bits are set, which bit is set, just take the value of F, add it with alternate sign and get the result, okay. It has become quite simple, that is why it was very important to break this problem. The explanation must have been very long but breaking it was very important. Now let us convert the story which we have understood into code. Let us code it line by line and dislike it a lot. It is in this question because ten questions are very bad for interviews. Okay, if the number is already zero then we do not need to do any operation. Okay, no operations are okay. What did I say about this that we will create a vector of long whose name is Let's keep F. How much size should we keep? Keep it as much as 32 or 31. It is okay because look at the constraint which is not a power of 10, it is not the maximum, so 31 bits is enough to cover the length of them. It is okay. What does Create F mean? Is the number of operation to convert number having only eighth bit set to zero ok for int and you will know that A of jive is a g, what does it mean that zero bit of our number is set i.e. the number is one ok. It will of our number is set i.e. the number is one ok. It will of our number is set i.e. the number is one ok. It will take one step to convert it. It is okay to convert to zero. Rest start from one. Lesson equal to 30 times. It is okay. Let's start with 0, which is our actual question and remember I said that we have to add by alternating, if we have to do plus once, if we have to minus once, then I will decide from this variable, now if there is and then we will do plus and if there is minus and If there is, then we will do minus, okay then int a is equal to 30 a i greater equal to 0 aa minus, see what you are doing, you are solving left to right, I told you the reason for this, okay, first of all, let's take out the eighth bit, which is the bit. You see, what is int i bit equal to i bit, how to get it, left shift one and remove its end, whatever is our number from A, then we will know whether the i bit of A is set or not, okay. If the I bit is not set then there is nothing to be done, just continue wherever it is set, we have to find the value of F. Okay, if the value of sine is greater than zero, sine e is greater G means it will float, so what do we need? Have to do d have to do then result plus e to a of a but is set then f aa will be else result will be minus e a ok in the last return result has to be done see f aa means i bit was set for example our assume input was 0 I told you that A of 0 is the third bit set, f3 is minus a0, isn't it something like this, so if f is set then f a is plus or minus, we will decide that by alternating, now to alternate plus minus. What will we do? Sa = Sa * -1. What will we do? Sa = Sa * -1. What will we do? Sa = Sa * -1. Okay, let's run it. Time complex and space complex are the same. You must have already known because look, the for loop is running 30 times. Here also the for loop is running 30 times. And the size is also 31 V constant. Let's see indeed if there is any doubt by submitting in the comment section try to help us out in the next video thank you.
Minimum One Bit Operations to Make Integers Zero
making-file-names-unique
Given an integer `n`, you must transform it into `0` using the following operations any number of times: * Change the rightmost (`0th`) bit in the binary representation of `n`. * Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`. Return _the minimum number of operations to transform_ `n` _into_ `0`_._ **Example 1:** **Input:** n = 3 **Output:** 2 **Explanation:** The binary representation of 3 is "11 ". "11 " -> "01 " with the 2nd operation since the 0th bit is 1. "01 " -> "00 " with the 1st operation. **Example 2:** **Input:** n = 6 **Output:** 4 **Explanation:** The binary representation of 6 is "110 ". "110 " -> "010 " with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0. "010 " -> "011 " with the 1st operation. "011 " -> "001 " with the 2nd operation since the 0th bit is 1. "001 " -> "000 " with the 1st operation. **Constraints:** * `0 <= n <= 109`
Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map.
Array,Hash Table,String
Medium
null
1,615
Hello hello guy welcome back to my channel thunk code and my name is gaurav and today we will be solving maximum network rank so today need code challenge maximum network rank okay before getting into this question I want to announce one thing let's like You are doing a coding problem and you are stuck in some problem okay and you are not able to find a bug and you want someone to explain the solution so I have learned this one thing okay so you book a session in Whenever you get stuck in a question, you are getting an error, or you are getting a color answer, or you are not able to understand the logic, or you are not able to understand what is wrong with the code, it is okay because I have learned it. I have seen that if I get stuck in a question like, ' seen that if I get stuck in a question like, ' seen that if I get stuck in a question like, ' Okay,' then I discuss it with someone, Okay,' then I discuss it with someone, Okay,' then I discuss it with someone, then I myself understand where I have gone wrong, and I also get an alternative approach. It is okay to solve that question, so if there is a discussion to discuss together, then it will help, and if he himself is a very good expert, then it is okay, if he has knowledge in himself, then it will help. Okay, so this is what I have done for lunch, you can see it, okay and you can book the session, Adjust Sup 19 Half NR session, okay, watch this, if you ever get into any question, then this is what I am going to introduce in the introductory offer. I am fine, you can see this, now we come to the question page, maximum network rank, so what to do in this question, basically nothing has to be done, the roads are connected to each other, you have to tell which one you have to catch such two notes. And both of them have to be told to how much the first note is connected to which second note is connected, right? And if we look at the rank of both of them, then what will happen to which the first note is connected and the second note to which it is connected is the sum of both and if Both of them are also connected, so one extra count is done. Okay, so they will do a minus. This is what has to be done in the question, like suppose I hold zero and one, hold zero and hold one. In this example, zero is connected to how many is zero connected. With two, the answer to zero is two, it's okay, I'll write here, what is the answer to zero, it's two, one, how many is it connected to, one is connected, with three, it's okay, one is connected, with three, sorry, three is okay, and if I am finding the rank of zero and one. So the rank of zero is two and the rank of one is three. But what is this, if it is counted twice then we will minus it, we are fine. So what is the rank of zero and four? And let's find out the rank of someone else like we find out the rank of one and th. Okay, one and r are connected to how many, one is connected to three, and yes, how much is one connected to? Th and three are connected to which is okay and there is common in both of them, so this is minus one, it will be okay, so this is done, this also becomes four, now okay, so like this we have maximum which rank. Coming to find out, this is an example, okay, I will take one more example quickly, okay, so let's add this F and six more to it, we will take 5, 6, 8, okay, now I will find out the difference between W and F, N and F. What will be the rank of N? Rank of N will be T. Okay. Rank of N will be T because it is connected to three, one, two, three and what is the rank of F. The rank of F is also right but if they are not connected to each other then the rank of these two. How much will it be? Six will be. Okay. What will be the rank of these two? Okay, so how much will be its answer? It will be if this is the complete graph or this will be its answer because it is maximum. Now how to do this is very simple, what will we do, how many are connected to Navn, give them all a set. I will put in, tooth is connected to zero, it is connected to th, 4, it is connected to four, it is okay, and let's it is also connected to 5, 6, so it is connected to 6, 8 and so on. Connected to F is connected to F is also connected to F Okay now what we will do is select every pair We will select every pair from Z I to A P S Sorry okay we will select every pair Meaning 0 02 03 04 06 07 08 Okay, then T is okay, like this we will select all the pairs, so let me show you on the code, I have made this set of vectors, okay, off A will tell us which one is connected to zero and which one is connected to one. Which one is connected to which one? So, the set of which one is connected to n is fine. So we put it in this array. We went to the road array and whoever is connected like suppose zero and one are connected. One and two are connected. There is a road, it is okay, there is a road between zero and one, there is a road between one and two, so what to do, if there is a road between zero and one, then put one in zero and put zero in one, it is okay and Then do this traverse in this array, it will select every pair, select each pair, okay and then check the answer of both of them, what will be its size plus its size. How many are these connected? How many are connected? And if these two are also connected to each other, then make it minus one. If these two are also connected to each other, then make it minus one. Brother, if in offw, I am finding zero, then it is okay. Offw. What is the set of offv in me? The set of one is okay. The set of one is the set of one. Who is in one is its set? So offv if we are getting zero then we will make it minus okay you can do the reverse also okay that you In this page, check whether there is only one thing, we will minus it and that, we will keep updating the answers, okay, we will keep updating the answers here, so that's it for this question, hope you like it, please subscribe to the channel and How much will be the time complex? This is the same score, it is okay, we are going to each pair and A has given us 100, so it will pass easily, okay and check it out, this is also okay, check it once. And whenever you are in doubt, you can book a session. Okay and don't forget to subscribe, like the video, tell me in the comments how you liked the video and also tell me if there is such a thing, there will be a platform in which you can connect with whom. If it is intentional then will it be useful or not which can help you and discuss the solution with you. If it is okay then tell me if it becomes such a platform then it will be helpful or not. Okay so that's it for this question. Hope you get the solution. Thank you. Thanks a lot don't forget to subscribe like and comment
Maximal Network Rank
range-sum-of-sorted-subarray-sums
There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`. The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either** city. If a road is directly connected to both cities, it is only counted **once**. The **maximal network rank** of the infrastructure is the **maximum network rank** of all pairs of different cities. Given the integer `n` and the array `roads`, return _the **maximal network rank** of the entire infrastructure_. **Example 1:** **Input:** n = 4, roads = \[\[0,1\],\[0,3\],\[1,2\],\[1,3\]\] **Output:** 4 **Explanation:** The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once. **Example 2:** **Input:** n = 5, roads = \[\[0,1\],\[0,3\],\[1,2\],\[1,3\],\[2,3\],\[2,4\]\] **Output:** 5 **Explanation:** There are 5 roads that are connected to cities 1 or 2. **Example 3:** **Input:** n = 8, roads = \[\[0,1\],\[1,2\],\[2,3\],\[2,4\],\[5,6\],\[5,7\]\] **Output:** 5 **Explanation:** The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected. **Constraints:** * `2 <= n <= 100` * `0 <= roads.length <= n * (n - 1) / 2` * `roads[i].length == 2` * `0 <= ai, bi <= n-1` * `ai != bi` * Each pair of cities has **at most one** road connecting them.
Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7.
Array,Two Pointers,Binary Search,Sorting
Medium
null
1,345
Jo Hai Ribbon Welcome To My Channel It's All The Problem Jam Game For Sure Winner Of Tears Are You Are Initially Position And First Index Of The Are In One Step You Can Jump From Index Of To Index I Plus One Until It Also Includes Independence Of The Rare and women in this with 3D software and all true share life biomedical suzy bf return minimum number of steps to which is the largest lake of where they are in to notice that you can zoom out side duration are at any time so let's understand This Problem is so Heavy For Watching This Index Notification For VoLTE Plus Wave From Here And You Can Always Some One Step Loop Control Of His Mind And Channels Age All The Amazing Video This Is The Place Because Someone From Far Abe Tu Phir Similarly One Said Ke Nishan Go First Year Of The Year So Let's Say Event Is One From Where Can They Go Hair Oil Plus One And Science That Youth And Also Being Can Go Anywhere 23-10-2012 SIM 24 These 23-10-2012 SIM 24 These 23-10-2012 SIM 24 These Steps In Den From Her Death Sentence For Which Can Go Hair And Vitamin Hair From this thank you in next is this 404 we can directly from to hair and skin which is sadan minimum number of steps taken from g 2002 rich vs index for men in black-3 lane den in next three do black-3 lane den in next three do black-3 lane den in next three do injection for this is three steps between Bittu Jump To Reach Dashrath This Is Minimum Possible Only 100 Feet Less Pride To Come Out From 1st Step 1415 Will Take Notes Tours Digvijay Taste As Per Forward To December 19 Number And Subscribe Chief Can Go Live Video Se Saaf Number One Minus One Plus One from this after all they are here oh a and I note this Suzy sweet and what will we start from this but 50 will strive to see in how many state ministers will reach on the last index of soup for starting like this Is The Soul Admission For Using Back For Search Time Will Create The Notes From Absolute Night This Planet Lyxesy All Gather Index One From 04 Services Victims Of Ru Go back to for easier and can also want to do and change your destination where you need to reach from 5th nov06 timings from five can go 60 em from six which can go 517 from 786 and from where they can only and from whom they can Go To And From Which Can Go To This Vansha Disavar Final Graph Subscribe 10 Indian Player Can Live With Clear And Third President And You Can Reach Third Step Seervi And Also Started For Implementation To-Do List To Started For Implementation To-Do List To Started For Implementation To-Do List To First Likes All Sentences With User In Danger Map of India in Tears will be value and validation in life from his life in which added to know who will feel the values ​​of all values ​​of all values ​​of all the best will remain this z4 mid valley in more plus computer labs subscribe to manifest creation will complete list of From You Related Word List for the Value Absolute Index of Wealth Creator of subscribe to the Page if you liked The Video then Hai Na Ho for Starting Your Will and Starting Birthday Swiss Index of Science Classes Monday Co lit 90 visited first and also will define available and step dance will count number of states per packing is not for face will apply benefit institute is not mp egg use 9 Tags page 10 liquid 9 2010 first will be to apply dabi this player was layer so let's find the size of crop dhaan number of element and work on which will give oo lot size and will run royal look for science - - size and will run royal look for science - - size and will run royal look for science - - dr of birth lived s will be taken from do you know who will check meanwhile duration last index 29 Classes Minus One This 2010 Will Return Water Number of Steps We Softly Calculate Two Letters Written Over Others Will Spoil Also Not Possible Places Life From This 2010 Gower Here And We Can Go On And Maxis Will Take Its First Let's Get Down List of Volunteers Slide In this from this map veer vikram patel of value index value intact maps for validation of bird this method agency list of birth day this service will win this match dot divine plants for birth of birth so this is what soft element definition letter them will definitely find All Hindus after the rest of the bank share is so one frigate base and effective border basically Sudhir will must read everyone elements of mid town middle aged after death will add more places in which they live and subscribe must subscribe my channel and condition will take care love you all Places In Bees Subscribe Now Will Check Difficult To Change A 100 Not Visit Us On Twitter Visit Us Quick It Ain't Electricity Dan Basically Beating Abit Not Contest Will Do Subscribe And From Where You Will Be Amazed And Just For You Will Definitely Get Every Rule Subscribe Button Click Ho Hai Acid Is Walking Not Means That Worked World Diabetes Day Mother's Day Here Is You See This Example In Dishas Example What Will Happen Will Have Subscribe 123 456 Sid And Keep Visiting Channel Subscribe Number Remedy directly go to the process Intermediate number of tourists and share with your particular text will be replaced calculation and listen so let's come pilot and test for our rate apps sued subscribe olive 170 ko hum red fort one so let's kshitij walking with all kasam test Cases Should Not Do A Son Where Is Not Difficult Samriddhi Solution 8 Minutes Ago Just Listen Let's See What Will Be The Time Complexity Of Dissolution And We Can See Hair Processing Full Harivansh Vichitra Open And He Also Thank You Will Get At Most All The Elements Once And awards and will get invitation for all elements of distant sources is the time and space complexity of resolution very much his wife and e ki pyoda are so e feel it solution hindi live channel subscribe my channel and tried to solve ajay jayram problem thanks for watching
Jump Game IV
perform-string-shifts
Given an array of integers `arr`, you are initially positioned at the first index of the array. In one step you can jump from index `i` to index: * `i + 1` where: `i + 1 < arr.length`. * `i - 1` where: `i - 1 >= 0`. * `j` where: `arr[i] == arr[j]` and `i != j`. Return _the minimum number of steps_ to reach the **last index** of the array. Notice that you can not jump outside of the array at any time. **Example 1:** **Input:** arr = \[100,-23,-23,404,100,23,23,23,3,404\] **Output:** 3 **Explanation:** You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array. **Example 2:** **Input:** arr = \[7\] **Output:** 0 **Explanation:** Start index is the last index. You do not need to jump. **Example 3:** **Input:** arr = \[7,6,9,6,9,6,9,7\] **Output:** 1 **Explanation:** You can jump directly from index 0 to index 7 which is last index of the array. **Constraints:** * `1 <= arr.length <= 5 * 104` * `-108 <= arr[i] <= 108`
Intuitively performing all shift operations is acceptable due to the constraints. You may notice that left shift cancels the right shift, so count the total left shift times (may be negative if the final result is right shift), and perform it once.
Array,Math,String
Easy
null
1,400
the 1400th criminal problem called account lynn france called count constructive week menstrual book this word is too easy this one unlike the other good is that it is good course 183 is not the ico and the test and yes it is much more complicated than This is my script, I don't understand it. In this one, what they tell us is that they are going to give us a word and a cement plant. We try to solve if we can build two palin drones with all the letters. We have to use all the letters of that word, so it is easy. because they simply have to count the letters and the trick is in the letters that appear in quantities not once three times four times because these can only serve to balance the book that is, for example in this case we have the anabel and the ve appears only once this serves to balance the palindrome so that in any case if we have three or less letters that appear in the pictures because then we cannot balance the no matter how many pairs of letters if we have to simply count the letters I'm going to do it with an ah and that round has the alphabet but to go to the safe lancet - plus 1 and then simply well let's put even though it is the number of letters that appear in quantities nones and let's just remember all of our arrangement the char program and what we are going to do is remove counts is going to be true - I know more and we are going to use this arrangement to count the times that each character appears and that since we have this simply we have to go through this jharkhand if she with said if it is better than zero equals yes no we are going to take the module out of that like this and simply at the end if or must is less than or equal to here dan fouts yes no we are going to see if It works, I think, and we're going to go for it, of course, ours from the beginning, obviously, yes, without a point, the link is less than that here he entered as a cute Sherpa, so if they ask us for more palindromes than there are letters in the word, well, obviously we're not going to be able to do it. all the courts to get like the best solution and I think this is the best because the solution is to understand this explain it a little let's suppose we have this then this is the d anabel baja preparing today for the counting of the letters then here all that there is a way like it is less equal here to say that it does not matter how many pairs we have with the others in the back all the others are perfectly well balanced we have two or four or six which do not serve pressure for the inameh we only have one that I don't know Palin's passion, I don't know, but if it's smaller and ball, what does it mean that we can use that slow one? We can use it for each chain that is needed, for example, if it were each one, I don't know four, this one, we can use that one to balance one of the ones. those that do not and those that are balanced and if we add the middle it will continue to be balanced otherwise when for example we have that it has equaled if we have 5 that are others well that has not been because there could be a node for by word then that is the principle that makes this thing work this and well this is the solution
Construct K Palindrome Strings
find-winner-on-a-tic-tac-toe-game
Given a string `s` and an integer `k`, return `true` _if you can use all the characters in_ `s` _to construct_ `k` _palindrome strings or_ `false` _otherwise_. **Example 1:** **Input:** s = "annabelle ", k = 2 **Output:** true **Explanation:** You can construct two palindromes using all characters in s. Some possible constructions "anna " + "elble ", "anbna " + "elle ", "anellena " + "b " **Example 2:** **Input:** s = "leetcode ", k = 3 **Output:** false **Explanation:** It is impossible to construct 3 palindromes using all the characters of s. **Example 3:** **Input:** s = "true ", k = 4 **Output:** true **Explanation:** The only possible solution is to put each character in a separate string. **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters. * `1 <= k <= 105`
It's straightforward to check if A or B won or not, check for each row/column/diag if all the three are the same. Then if no one wins, the game is a draw iff the board is full, i.e. moves.length = 9 otherwise is pending.
Array,Hash Table,Matrix,Simulation
Easy
null
968
That hey guys welcome back to my channel suggestion or problem with jaggery in binary tree camera will sleep problem where given root of minority install camera on no where is camera attend can't monitor this parents little boys images children what is the mean that you have a Beautiful accessibility hai to interface mantri id swami can have camera rajak hai us camera flash se fight camera heer wa adarsh ​​node it means kard is camera cant camera heer wa adarsh ​​node it means kard is camera cant camera heer wa adarsh ​​node it means kard is camera cant monitor jis node id hu is the present tweet kar this camera features is not cant monitor paint ki and images Children to here an immediate children to present itself and children's birds were return minimal number of cameras needed to monitor all most of the Mr. A that you vitamin A minimal number of cameras and right that every nodes monitor is on the table so example C of these Addiction More Something Like This Rate Main To So Gayi Thi Main Late Se Aayi Hai He Camera Kiya Hai Main Aayega Camera Here To This Camera Can Monitor This Dozens Parents Button Monitor The Children Of Mothers And Discovered And Note-2 In Order To Go With His To video Note-2 In Order To Go With His To video Note-2 In Order To Go With His To video have camera only roll no tomorrow morning twin tower hai and yes also here all of us does not know how many time required 1234 ka birthday plane volume minimum number of i want another way can do this way can have which deposit real life instituted Of placing camera heer vikas vinod is route motorization route note will have no apparent white taken place near we can place camera share how to dors with his camera download also cover who is the president will recover and images children will power that request from suhavani camera hone par hai to jaise to minimal number fans want this entire day aur hit video main tujhe is dancing try to find out how many minimum cameras with a request from history honors pinpoint but just think for dead hai to guys stay in knowledge discuss packet The here is that in Germany seat belt tight lab house camera mein aa right from camera on e want with a covered uber app that in which pen Twitter world and children in the immediate children because oo hai and trust camera below only that if Camera salary hai mein vighna yes priya and camera hi aur ki rihat behavior camera hai bhi parenting aur discovered to vaikuntha aur cover with a camera all the best 120 days how to stay in it k newly appointed see how they can think how can approach Which problem is always so late I know one thing I admired II and will discuss a contest about something like this let me name 10 notes 12345 i10 sports explanation for this main let se bhi aap camera hai or camera add node ₹2 camera notes2 ₹2 camera notes2 ₹2 camera notes2 a night vision camera no2's note one and note 3 not one and note 3 and monitor a mountain means the year award right by others on camera is foggy and more and two note notes in it doesn't have any camera but adjustment intervention in problem right side camera is not in this period itself and images and children in so camera no2 will monitor note one and more Than e my tab take only camera here then note 4 right now note 4 is note auditor note 4 not monitored and note 5 so here by time right time three cases vote friend ok like this jar and now note sweetness camera on a Note via camera such s no to 9 votes which two don't have any camera birthday monitored views note one and note 3 ko phod ke is the snow twitter not monitored views mode and 5th in this way it is fine only the first one is the note wich Hey backem rough the second ke is note vich dhundu aap camera butter yar monitor mein Raees and third cases both views monitor a to in order to represent 203 MP3 how light water will be doing this is representing ne music numbers ho chuke tha how to that Way in camera is it a political arnold state will be represented by a two states and shining november 21 2013 a tiffin audience to it means note help worker stayed in camera on that is note clearly found camera birthday still monitored date of birth written In One App 103 Not Believe With All It's Being Monitored By Bishnu's A Ki And A Nod For And Five Twitter Not Want To De Villiers Advising White Is Effect Not Getting Agreed Tenth Explanation Of Died When Water Dry Running Telling You How I'm Safe Ho this diet how this sequence on that boat lips discuss hello how they can approach this problem which is so that year what you think will be beneficial putting camera here and sugar camera he tried to thank oo I find it beneficial to put camera1 And camera to camera1 and camera to you think oo return to use this beneficial too camera one note camera to why but e placid on putting camera to here this had no children 19 this and paint will be our diamond toons is but a great place Camera is here a hain Dainik Bijnor mein bhi cover children will be recovered and paint will be power a that Sundha covering free mode on hello friends so is beneficial too camera is to he stayed here a mein the hain to what will happen gayi thi a the burning study daily use this is back once in the road you have no benefit so this dress or heavy camera a the sun that put camera inside news fuel cell and friends will not have any children on is so radhe din placing camera edward nino divide you Can place camera advance payment of honey singh i told you of this is not because that camera will cover the i am the present and even a small children me ruke the hoon to i hope you god this point that is the benefit of keeping camera habit and of The snow daily is a so now let me this is also a basis clear that will be played singh camera editor the perils of lymph node a condition happened meanwhile start will be given through the British so root will here's portion of a For What Will You Do That They Never Win The Battle From Right Visualize Another Problem Like This A's Contender Root Marriage So That Which Root And Rest Were Left And Right Will Request In The Volume Ko Then Member Vihar-3 How To Generate Volume Ko Then Member Vihar-3 How To Generate Volume Ko Then Member Vihar-3 How To Generate 21012 Two 2012 Person Cases 210 Is Not Monitor A Monitor I One Means Monitored But Has No Camera Added Not Monitored No Camera That And Visits Camera A Hi Honge Tulsidas Ko Exam Already A Beer Get A Hero From This Node A Letter From The Left Company Getting zero I am from right something on getting I one seems ok so how to what is it means when you are the roots of per decide right to vote for r Dead That Was Not Covered Traditional Some degree colleges for give some will result in flexible and right you get something from the rate is recorded for truth labs that and tried to values ​​for getting on were done that and tried to values ​​for getting on were done and listen is any of the left or right is video means the child was not monitors You how to have that camera and values ​​for the dead child can be how to have that camera and values ​​for the dead child can be how to have that camera and values ​​for the dead child can be monitored ok a to lakshmi is case will be dat is left is equal to zero and right click in child a that is zero thought will be to have camera he a edit So Will Have Vegetables Which Will Tell Us How Many Cameras Were Required In This Evil Dead 0 That Figure Skating Zero From Your Mother Child Will Have Two That Camera Country Is Window 7 Plus Test One More Camera Is I Stayed In You Find From this knowledge that Bigg Boss is back right now let us think over this what happens in the side of how jo se to t e main let from here your rating me one from hair oil surya get invite ok sweater sydney test ago the right left his old One Key And It Should Provide A Main So That Valve One Is Monitor No Camera Surdas This Left And Right Side You Find Camera Demon On The Monitor Other Than Benefit Of Giving Camera Real Well Dho Camera Webcam Payment Of The Different Types Of Discover With You Will Hear A Whistle Itself And Children But I Want To Hear You Want Me Suraj Dhund Aur Kabaddi World Cup Kabaddi Payment Of The Parents December Okay So This Life Is Equal To One Is Equal To I Just Returned Okay Sa The Return 0 K Veero Means Research Yadav This is not monitoring This is not the solar system From here You can get ripe Tubelight Welcome to see Parents can get its clear effects Willow To this camera and top 15 minutes In the editorial of the newly appointed state of the book, there are more routes written that from this Light or getting to information from as surya get into something went to get into right any scam rise near camera is hair to vishnu not broken camera only early cancer simply return one from the earth the return of earning to its units camera is hair as camera bill Monitor to payment voucher 110 scooter1 is how to give any of the rate of any of the child that all the volume to and riders and to 90 the child health camera to just return one from near meaning of the as old is gold deposit in a Mint Sab Kaise Right Left Now Let's Discuss The Best Is I Want To WhatsApp The Best Is Give Details To Subscribe To WhatsApp Thank You That They In Root This Channel I Went Through The Tunnel I Want You Should You To That Take Off Now You For such professional it means shouldering monitoring tight is basically tap disabled certificate online diet is monitor okay a that is a routine I will celebrate in this and tell lips dry run on the basis of these cases I myself not imagine businessman's Tirhut canal appears The sole your memory speed given a nod from fear and what will you say i will cartoon root i will go on record listen border basically technicals equal right developed qualification for libra and so will reach here a is you for this right flashlight noir root wear hai to pradesh left edge servi left side journal tweet1 right side optional 12th ki surat mein bhi to value left volume phir bhi one and right value will be also known s that bottled saunf vidron it means set e want to discuss it just 10000 the Root Will Return Zero Two That Election Root Will Hear One That Surya Root Will Also Share Main Tujh Se Right To This Problem Comes From The Right Call Rate 200 With End Object Left Call Me To The Best Cadet Western World Record Base Cash Withdrawal Activity Was Known For its root register no why not the value style value 0202 is the camera itself of values ​​will be two camera will be values ​​will be two camera will be values ​​will be two camera will be prevented this is to a camera will be which here to rear camera with hair and the camera brother you vitamin board members hand cameras to return gift 2 oo how to withdraw camera rear camera on hai to no root welcome hai the root welcome hai aur aapke sunao 10 min 125 value 2 and right has no child morning hair with basic and vital for health a look on and tell See the effectiveness of the left or right side to it means that is not be divided will be our category clerk and development Disha camera from this discovery parents also award software will return Ward-12 award software will return Ward-12 award software will return Ward-12 I one vitamin E the root will also be the root But this force is also a yes to parde sunao main left ko is written in one android toilet morning set entertainment hai to 3000 dam ki 2016 it means that does not cover like Buddha children not cover udayveer wa ek tu button from hearing on the Bible Minerals Discovery Beneficial To Quota Camera Add Central Commerce Returning A 500 1000 Ki Training Video Me Ocean Water And Fruit Welcome Hair That Nda And Left Will Return Lineage The Right One Enclave 2051 Volume Which To Will Have Camera That A Me September Increment And Will Not want to meet you a look could come to the water campaign got your go-to cameras and this water campaign got your go-to cameras and this water campaign got your go-to cameras and this post that combined AP logic and approach normal personality doesn't have the issue no deposit bonus from your half inch that your to see what they are Doing a lecture gave this function vyapar singh root and some will tell you about this condition of pearls punjabi making this difficult here is this root and yet not afraid means right main itna and right to visit in this question on will do meaning of which Light to on comments bollywood hero swimming camera come plus wash just to justin von its return review members this condition only on the sweep lottery share basically a 102 or not increase from here were returning from this video train to write recording folder camera here from Camera This Tweet Phone Par Temple At Se From 0001 Roots Returning No Data Is The Difference Chord This First Returning 0tweet Means You Are Routine Hormone Tod Roots Not All Fruits And Don't Will Have To Hai Webcam The Root Sudeshwar Will Do Some Places Near This College Vaikuntha Your side is open to the problem and approach but they do you like to my channel thank you
Binary Tree Cameras
beautiful-array
You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return _the minimum number of cameras needed to monitor all nodes of the tree_. **Example 1:** **Input:** root = \[0,0,null,0,0\] **Output:** 1 **Explanation:** One camera is enough to monitor all nodes if placed as shown. **Example 2:** **Input:** root = \[0,0,null,0,null,0,null,null,0\] **Output:** 2 **Explanation:** At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `Node.val == 0`
null
Array,Math,Divide and Conquer
Medium
null
34
Hey guys welcome and welcome back to my youtube4 challenge so the problem is find first and last position of element in sorted array ok so what is the problem once let us understand the problem is that we are given an array of integers sorted in non Descending order non-decreasing in non Descending order non-decreasing in non Descending order non-decreasing order means sorted in increasing order. Find the starting and ending position of a given target value. A target value is given, its starting position and its last position have to be told. If the target is not in our array then we have to Start position and end position -1 -1 has to be Start position and end position -1 -1 has to be Start position and end position -1 -1 has to be returned. You must write an algorithm with log of n. Complex is a log. If it is sorted then what can we do. And if we want complexity then we can apply binary search. Okay binary search. Why see, we have to do a kind of search in this, we have to find out the starting and ending position, what does it mean? It is okay to search and sorted is also given and if it seems a complex then is it only binary search? It is basic one time test case. Let's write and understand so see 5 7 to 8 and what 10 is okay and what is the target value given target value is given 8 okay now you first see friend it is simple what do we have to do with this target value Starting position i.e. value Starting position i.e. value Starting position i.e. starting index and ending index is to be found. Starting index and ending index. You will think that we can do a simple search also. Look, we will do a simple search. Not found here. Go ahead. Not found here. Found it here. As soon as We have found the target, the first time we have found the target, that is its starting position, once I do the indexing, if I am G 0 1 2 3 4 5, this is the starting position, okay, so the three which is my starting index is the ending index. What should I do to find out the ending index? Either I traverse from the back or I traverse from the front but I store the index of the element which will be the last unit of the range. Okay see if I traverse from back to back. So look from behind, first of all there are 10 R, that is not my target, then I got at, then that is my target, so the ending index will be F, so what can you do in this way, you can take this starting index and You can find out the ending index, but friend, you are doing a single reversal and taking off-a-time. reversal and taking off-a-time. reversal and taking off-a-time. If A is whatever and the length is, it is okay. What were we told to do better? We have to take off-a-time and do it in complexity. off-a-time and do it in complexity. off-a-time and do it in complexity. This is what you were doing, it was linear search, okay, this was linear search, what we have to do is to do it in Lag A, that is, we have to do binary search, okay, that is also very easy, nothing, if you do not know binary search or binary. What is search, then a video will appear on the top of the eye button in which I have explained it, first understand it, you will understand it too, it is not very difficult, so see here, let's write the test case again from 5 to 7 8 10, are you okay? What is the target given? Look, simple if binary search. What is simple binary search? What is the meaning of simple binary search? If you are given a target, you have to tell which position it is in this array. That is binary search. Doing binary search means basically. Searching in an array, what is the extra thing in this, you have to tell the first index of that element and tell the last index, okay, you have to tell the first index of the element and tell the last index, so see what we will do, we will bring our classic binary search, you automatically You will understand how to do it. Look, apply classic binary search. I am indexing. Okay, so what happens in binary search. We first take out the middle. Okay, here and there, don't look here and there. I will write the algorithm. Okay, on this side. I will write the algorithm together, so see, first of all, what will we do, we will find our mid, what is mid, what will be our start plus end byte, start, we will take two pointers, one is start and one is end, okay so Here I have here what I will do, I will take it at And here, if we take out the mid, what will be the mid? Mid is equal to y which is the chart i.e. zero plus which is the end. y which is the chart i.e. zero plus which is the end. What do we do in divided Batu binary search? If we take out the mid, then what will be the 5 batu? At 2.5, we will take the integer, we will take the floor. At 2.5, we will take the integer, we will take the floor. At 2.5, we will take the integer, we will take the floor. So it's okay, that is, your mid has come to this index. Here, mid has come, so what we do is we check whether the mid is there. What do we do in binary search, we check whether the mid is there. What is the target here? If this if condition is not true then we will do Else If. What will happen in Else If? See what will happen in Else If. We will see if this is our element here, our target is that middle one, which side should we bring it to? Which way will it bring the element? Think for yourself, this is a sorted array. Look, it is sorted. Okay, always remember that Y is sorted. So if our mid is at sen, we are looking for 8 and it is sorted, that is, which will be A and from sen. If there is a bigger element, then it will be on this side. If it is on this side of Sen, then it will be smaller than Sen on this side. This side will be bigger than Sen on the right hand side. So, what is our motive in searching Ba? Our motive is one half in Ba. Make redundant and go to the other half so here if your target is bigger than your middle then you have to go to the right hand side i.e. you will check go to the right hand side i.e. you will check go to the right hand side i.e. you will check this else if that is your arr off if that is your late target. If it is coming bigger than the middle element then it means that you have to go to the right hand side, that is, whatever is your start, you have to shift it, bring the start here, this one in this range. I means what will happen here, what will be your start equal to here, this was the middle index, it will start one ahead of it, now this window of yours will be this window, so this will be s = mid be s = mid be s = mid pv i.e. what was mid. So pv i.e. what was mid. So pv i.e. what was mid. So what will be your start 2 pv 3 okay so here what will be your start will come here ok now we will take out the mid again so this is your work right this one is your code it will run till this which is yours This is the code from here till here it will run till your start which is less than end or is equal to start i lesson is equal to end ok this will run till then so here p start whatever is lesson end is right 3 e Lesson equal to 5 means lesson f so here we will make P mid equal to again start ps and batu i.e. 3 p 5/2 then this will come to 4 i.e. 3 p 5/2 then this will come to 4 i.e. 3 p 5/2 then this will come to 4 i.e. where is our mid now, where has it come? Now i.e. where is our mid now, where has it come? Now i.e. where is our mid now, where has it come? Now our mid is four index. But then look, here the ARR of mid is equal to 8 and the target, that is, one of our indexes can be a possible index, that is, I am not saying that it will be the first index or the last index, it is a possible index. Maybe this is the first index, okay, so for now, I will take a variable, first index AD, and store the index in it, which right now I think, yes, it's okay, mid which is mid is four, this can be so. Here we will store four, that is, we will store mid in F ID one, mid index that this can be my starting index, can be the first index and it can also be that the left side of this at is smaller than this eight. There is one more at right because it is sorted and to the left of it will be on this side. No, look, even if it is on this side, we are not concerned with that because right now we are looking for the first index. We have to see whether this is the first index. Or is there any at before this, then what do we have to do? We have to find out the range of our now which is the one before this, we have to find in that range whether we get any more t or not. Okay, so what will I do, I will find my end. Now I will bring it to mid minus and pe. This step is extra, otherwise the rest is normal binary search. This is the step so that the first and last index of finding the index is the first, so this step is extra, okay for now. So we are looking for the first index, so what will happen here, see here is my end, that will come to me mid i.e. 4 - 1 3, so whatever my end will mid i.e. 4 - 1 3, so whatever my end will mid i.e. 4 - 1 3, so whatever my end will be, it will come here, so start also on three now and what is the end also? On three, here start is less than equal to end, so now again the loop will run and what we will do again is to take out the mid, if we take out the mid, then 3 is 3/2 i.e. 3/2 i.e. 3/2 i.e. 6 times 3, so what is the mid, what is the index, now see the error off. Mid er of 3 kya 8 ch e equal to target so now this mid index is this possible can be our answer so update it brother this will be the first and what to do to the end is mid minus wa to mid k th 3 my 2 So the end has been reached, now look here, our start has become bigger than the end, so the condition of this loop is not true, so we will not work again, this loop will not work again, okay, there is one more condition here that if If we got here from the lets, then we got the middle from our target. If the target was bigger than the middle element, then we went to the right side, but if the target is smaller than the middle, then we went to the left side because on that side. If there are laser elements, what do they do to the end here? Mid to mid is okay. Classic binary search is normal binary search. If you do not know the concept of binary search, then there is a video in the button above or I have also given it in the description, watch it once. So look at it this way, your three index is your initial index, starting index of element A. So if you look here, 'r' has come in the initial index, if you look here, 'r' has come in the initial index, if you look here, 'r' has come in the initial index, now we will use the same concept but for the ending, once again this is the same. Try applying the same concept, I just give you a hint that there will be a change here, this is the thing that happens where we get one of our same element target, there will be a change in its step, the rest is the same, think for yourself? Maybe, let's see, now I will quickly write this test case again 5 7 8 10 Okay, it is very easy, there is nothing, there is a small change, now what do we have to do in this, we have to find the end index, which is okay. Ki end index at ka kya hai four last to four pa four index pa aa raha hai na at so the target is our at is the starting index for now the ending index will be zero what is the last index f ba s will bring here so this will continue till then while As long as our start lesson is equal to end, I am writing very dirty, I am fine, start lesson is equal to end, what will we do, we will extract mid is equal to two, what is start ps a batu, okay, so mid, what will come to us here, start what? Zero and what is f divided by two came here look here what is index p what is sen and our target is greater than seven i.e. if target is greater than seven i.e. if target is greater than seven i.e. if else if look here else if What will come? Let's work first of all. Here we apply 'if' work first of all. Here we apply 'if' work first of all. Here we apply 'if' i.e. if our mid come is i.e. if our mid come is i.e. if our mid come is equal to the target then we will do something. Now what has not come then we don't have to look at the 'b' but for now what is happening. look at the 'b' but for now what is happening. look at the 'b' but for now what is happening. Our target is coming bigger than our mid element. It is A of mid. Okay, so what we will do is our initial start was Y and Y was and this was mid. Now our mid element is coming and is smaller than the target so we have Y. If we want to shift, then we will pick up the start and put it here, that is, start is equal to two, what will become mid plus, and okay, so update the start here, what will become of start, three, again we will take out mid because start is less than this. If the condition is true then mid will be taken out. What will be formed again? Mid is equal to 3 + 5/2 i.e. 4. Mid is equal to 3 + 5/2 i.e. 4. Mid is equal to 3 + 5/2 i.e. 4. Look at the index. Here I erase it so that it can be understood better. Now here is our start. Here this is our Start, our mid is on the index, so what is the mid point? Now we have mid point which is the same as the target, so what will we do, we will see. Okay, so this can be our four possible end indexes. I am also not sure but If it is possible, I will take End ID X E ID, I will take one variable, okay, in which I will store the current index that brother, okay, here we have got a target, mid ED e mid, okay, after that. What will we do? Now I have to see, is there any other at on the right side of this at, meaning if there is another at on the right side of this at, that means it should be the last index, not this one of at. So I have to test now to check whether it is there or not, then what will I do, I will consider my start, now I will consider the range on the right side of it, so what will I have to do for that, what will I have to do to the start, I will have to do mid plus one. Mid P is just this little change, so what will happen here, my start will start and wake up Mid Psv i.e. what was Mid 4 and wake up Mid Psv i.e. what was Mid 4 and wake up Mid Psv i.e. what was Mid 4 Pv, then start will come here also i.e. it Pv, then start will come here also i.e. it Pv, then start will come here also i.e. it has started F then F Ps will then extract sed Start I equal to end so 5 p 5 batu kya bana f ok so mid has come f p here my which is this is not equal to the target it is ok and this which is 10 what is this bigger than the target is 10 e greater than 8 so if which is the target If what will happen here which is mid element or we will put the last condition, we will see here the last condition what will come that if your else if target is less than the error of mid i.e. the target is less than the error of mid i.e. the target is less than the error of mid i.e. the error of mid is big which is what is here 10 target If the right is greater than , then what will 10 target If the right is greater than , then what will 10 target If the right is greater than , then what will we do, there is no point in looking here, we will go to this side of 10, that is, we will make our end mid minus w, then mid minus w, what will be 5 minus 4, then what will become of end, okay? Now look, the star here has become bigger from the end, so we will close our loop and what will be stored on our end index is the mid which was four, okay, I forgot to write it earlier, but here our mid was right. The last one was a match, so in this way we will get our end index, so basically if you see, there is only one difference between the start index and the end index, in the start index, when we get an element in the middle, we get the same target. We check on its left side whether there is any target lower than that or not. To find the first index, we go to its right to find the end index. Because we have to see the end index, we have to see if there is anything else next to this eight. Is it at or not? Okay, look, here we go to the left side, so we do end and mid - 1. Here we go to the right side, mid - 1. Here we go to the right side, mid - 1. Here we go to the right side, so we make start mid - 1. so we make start mid - 1. so we make start mid - 1. Okay, so I hope you understand. And this is a binary search, so basically what will be its time complex? Log of n because at a time we make one half redundant and go to one half only. Okay, so let's see the code once. I have written the code in Python. It is done but easily you can convert it to C+ or Java. you can convert it to C+ or Java. you can convert it to C+ or Java. So see, initially this is the one to get the first index and this one is the same meaning almost the same code to get the end index, so initially the start was taken at zero and the end was taken at the last index. Took and a start index, I initialized it with MIVE, then applied simple binary search that if start is less than equal to end, extract the middle. This method of extracting the middle is basically not overflow, that is why it is fine and if your mid element is If it is equal to the target then one possible answer can be the middle of the start index but you also have to check whether there is any same target before it or else you will shift it to your right or left. It is okay if the other wise. If your middle element is bigger than the target, then you have to go to its left because the target will be found there only otherwise you will find it on the right, so this is your first index and what is the same to get the second last index, take a variable and index then. Run the loop till start is less than end and find mid. If your mid matches with the target then it can be a possible answer but you should also check on the right side of it to see if there is something else or not, it is ok the other way. You shift it to left or right and by storing these two indices in the last, you can get the return. Now you will ask why did I take -1 and -1 here why did I take -1 and -1 here why did I take -1 and -1 here because they have said that if the target is not achieved then I will take -1 - Return 1. Okay, achieved then I will take -1 - Return 1. Okay, achieved then I will take -1 - Return 1. Okay, so that's why change this value to -1 so that's why change this value to -1 so that's why change this value to -1 so that if you never find the element then this start index will never be updated. If you never find the target then it is so. So this was your code once. Let's try this, it is working fine for you, so I hope you have understood the problem and it is exactly binary search, there is a slight modification, this one line has to be added in binary search, that is also very easy, so if the video If you find it helpful then please like, share this video and subscribe to the channel. Ok thank you bye.
Find First and Last Position of Element in Sorted Array
find-first-and-last-position-of-element-in-sorted-array
Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value. If `target` is not found in the array, return `[-1, -1]`. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[5,7,7,8,8,10\], target = 8 **Output:** \[3,4\] **Example 2:** **Input:** nums = \[5,7,7,8,8,10\], target = 6 **Output:** \[-1,-1\] **Example 3:** **Input:** nums = \[\], target = 0 **Output:** \[-1,-1\] **Constraints:** * `0 <= nums.length <= 105` * `-109 <= nums[i] <= 109` * `nums` is a non-decreasing array. * `-109 <= target <= 109`
null
Array,Binary Search
Medium
278,2165,2210
1,727
So hello everyone good morning welcome back to my channel so today we are going to do the next PTD which is the largest sum matrix with rearrangement is 1727 so let's first see as usual what is the question saying what is given to us what is binary matrix binary The same is visible in zero and one, yes, all of size, a cross, and we are allowed to rearrange the columns of the matrix, so we have just been given the option to rearrange the columns and what we are getting by rearranging is return the area. Of the largest sub matrix means we have to create a sub matrix by rearranging it which will be returning the largest area where each element of the sub matrix will have one value. Okay so the question is clear or let's take a look once. What do we have to do in this? Actually, this is our sub matrix given, so let's So, let us like this one which is our 0, so if we have to create such a sub matrix in which all the elements are as they said. If there is one, then if we see that the last one is our column, we exchange it with this middle column, meaning two and one, if we exchange these two, then what will happen here, right, and this will be our return which We can also see it, okay, this thing will be clear, that means the question is just okay, now how will we do it, so now if we think, whatever our sub matrix will be, it will be a rectangle, it will be right in the form of a rectangle. And what is the area of ​​rectangle, And what is the area of ​​rectangle, And what is the area of ​​rectangle, basically this is the main use of this concept, yes, it is okay, we can say length in breath or base in height, here we will say base and this will be our height, okay now as in the question. It is said that what we need here is the largest sub matrix. If we want the largest sub matrix then we should make both the base and height big, both will be big, only then the area covered will also be big, so this thing is there now. What is said in the question, so the question is, we can rearrange the columns, we can rearrange only on the columns, we cannot rearrange the rows anywhere else, okay, so if we look at the top, our figure is visible here, if If we connect the two below, like we did the row column operation, is there any effect on the height or not? If we exchange the two below, by lifting this area here. If we look at this side, the height has remained the same. There is no effect on it. Right, we have to determine how much height each column contributes on its own. How much height does each column contribute on its own? Can do and now let's see how to do this, so we need to know its indices, how we represent the matrix, this will be our zero, this is our 0, and this will be our 02, 0, and Two, right? This is the way we represent the matrix here. Now we will have to see one concatenation one here. Okay, what am I saying? Let's see, like the first row will be our bean here. Now which is Our forest here is at zero point, is there any forest visible above it? Is it not in that column? If we look here, is there any forest above it? If it is not on this column, then it will remain the same there or here. There is no one, there is zero, it is lying above, so here also only one will be filled, is there anyone here, then yes, friend, here it will be two, we will add it, why are you doing this now and you will know later, you will see that. Same here, is there anything above it, there is some weapon lying there, let's first fill one row, then we will know, then what I said will come to the fore, okay, now if you come to the last row, then what happens here? There is a forest in the lower part, if you look at the column above it, there is a forest lying there. If you want to see the pond, there is a forest here too. Now it itself is zero, so we will not do anything to the zero one. We have to see only the one where there is a forest because it is obvious. It is a simple matter, if we want a greater area, then for greater we will have to look at the forest only. What will we do with the zero one, then we will let the zero remain like this. Is the bean above it? So there is a forest above it too. If we look above it then It means two forests already, so overall what has happened is it has happened, sorry, it would be okay, now what will we call this approach, see where then matrix I is I for Rose and J is for column where J is one, okay. So what we would be doing is mat a plus equal to mat of i minus r this thing we are using up here okay now why are we doing this now yes now it is understood that yes we have done this like this Given, what was the benefit for us from this, we came to know that how much height each column will contribute for that particular row. Okay, I will write how much height each column will contribute for that row. This is its main use. Okay, now look, this will be easy. Now look at our 203, this is the last one, this is the main one we have. Okay, among the rest, we don't want to look that much at the moment, we just look at what we are doing, so the last one we have is 203. Now, if we sort it, okay, in descending and increasing way, we want bigger, then what will happen - will come first, here then what will happen - will come first, here then what will happen - will come first, here again zero will be okay, index will be 0. Now if we look in this, what will happen, zero column means three components. On the first column, two occupations, zero, one is correct, it means what will be its form, it will be something like this, the remaining one will remain empty, then two and this zero, let's just assume this, so now what will we do in it, now we get this Okay, considering the largest sub matrix we can take, so whatever will be the largest sub matrix in it, we will see it while doing the I treatment. Now how will it be, see, now things are easy. It will seem a little bit that if we go to the first column, it is okay, eight column zero is okay, how much height have we got, look, this is the height itself, what did we do, all these movements, we did above, what did we do to find out the height. Right, I see, it was written here how much height each column will contribute for that row and our base is height into height, our formula is to calculate the area of ​​the rectangle, formula is to calculate the area of ​​the rectangle, formula is to calculate the area of ​​the rectangle, so we used the height as the height, basically this is what I am trying to explain here. I was doing it for so long, okay now you see here how much height has become at column zero, we have 0, now how much will be the remaining base, it will become one here, is n't it visible from the figure why because there is only one It is the same column, right? If we see how many columns are there of three heights, it is the same, then how much is the area, we have its base into the height, so it is equal, both will be multiplied. Now, the height on the first column, we have how much is above. Look, is n't it two, how much base is there, that is also two, okay, and one thing is that from base two, we come to know that the height of each column, which is at least two, should be two for all matrices, if any If sub matrix is ​​made, then the if any If sub matrix is ​​made, then the if any If sub matrix is ​​made, then the height of the athlete must be two. Okay, look at its area. Otherwise, the matrix will not remain. If it is not the same, then it has become four. Okay, now come to the zero column. That's it. The height itself is zero, hence the area has also become zero. Well, let me write that I have become the base. We have three more areas, the area is zero. Things are clear till now. Now here you know, the idea should be clear that for each column. The height of the column on its left will either be bigger than it or it will be the same as it, this is its main logic. Now here we should know that the height of the particular column on the left will either be bigger than it, just pick any one. You suppose, pick up this one, two, what is it compared to the one on the left, it is bigger, either it will be bigger or it will be the same, come to three, then three is the same, so now how will we do it, so let's see its condition. The important concept of the code is that if it is not clear then check again if something should have come or has not come then ask me once in the comments. Let us try the code and then check if the other thing is clear. First, by taking the length of the matrix, it becomes our row. Inside Java, we can represent the column by zero and one. We will make our result and we will divide it. First, let's learn from the rows. Now let's move on to the columns. If we go to that particular column above, then if our matrix is ​​not equal to zero, it will be one and matrix is ​​not equal to zero, it will be one and matrix is ​​not equal to zero, it will be one and one second, if it is not equal to zero and so and it is greater than zero, that is, if it is greater than zero, then here. What will we do? We will do the same thing that we were doing, which is where we came from, so it is different from its previous one, so the minus column will remain the same, so we will not tamper with the column, okay now that Now let's come down and look at that one particular row. For which is the loop with I or the loop with R. All the work is being done inside it. I have not come out. Okay, inside that we clone that particular row. We will not be tampering with the main row. Okay, so there is a clone function in Java which duplicates the instance, that is, it makes it an object and is used to duplicate it. Okay, now the edge dot sort current is sorted. What we have done till now is what we were doing till now, it is in the top right now, remember to sort 203, I had made it 320, so there I had done descending, now its descending cannot be done so easily inside Java. We will handle it in a different way, how we will do it, you will see now, okay, juice in which whatever is the maximum, we will give our sub matrix, then on the result, the current row will come in a minus, and some people will say, what is NI, so this is our thing. The thing about descending order that I want to sort is descending, what will happen, we are sorting in ascending order, what does sort do, sorts, inside the ascending order, so where will be our largest element, it will come in the last only, won't it be ascending? In the order and we need the last area, so we needed it in the descending order, what is the bigger element in the descending order, then only the same A minus has come, that will give us the last element which will be the largest in the sort. After doing this, okay, now let's run it and see, I hope it should go away, no, good answer, no, I yes brother, I found out, so this was it here, there was nothing special in it, I guess the question is clear, I told you properly. Right from the beginning, how, what happened, in what order, our work was done here. If it is okay, then basically once more I write what we did actually is right so that it becomes clear better, then initially what we did is different from what we did. What we did is add it to the input matrix, it is ok, after that what we did is that we kept track of the count one for each column. We kept track of the count one of each column. We are ok, after that we checked the condition that if the row and column of the matrix is ​​zero. If it is not equal then what to do is column of the matrix is ​​zero. If it is not equal then what to do is add it to the row column of that matrix and add the R of its previous one and there is no Y in the column from column to column and if it is not then it is okay, that means if our matrix row column becomes zero then it becomes zero. We have, okay, so do nothing, simple do it first and then move to the next iteration. How to do the next iteration by doing row plus one, then okay, do row and when our daily is updated, once daily are updated. So what to do, sort by descending. If it is then it is correct. If it is not possible then it is difficult. This means that the code becomes longer, so use something in its place. Now what will happen when we sort the rows by that particular row? Basically, I have written 'For Sorted Current Row', Basically, I have written 'For Sorted Current Row', Basically, I have written 'For Sorted Current Row', so the rectangle element of that current row can be used as height, and our I PSV is used as base. If you look at the figure, you will know. This will become our base. The parts below are the only thing. I guess things will be clear. The code will also be clear. From the beginning I have come to explain how things are going on, so if anyone still has any doubt. Let me know in the comment section if these things are not clear then keep doing like this, see you in the next video till then keep coding and take care by.
Largest Submatrix With Rearrangements
cat-and-mouse-ii
You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order. Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._ **Example 1:** **Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\] **Output:** 4 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 4. **Example 2:** **Input:** matrix = \[\[1,0,1,0,1\]\] **Output:** 3 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 3. **Example 3:** **Input:** matrix = \[\[1,1,0\],\[1,0,1\]\] **Output:** 2 **Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m * n <= 105` * `matrix[i][j]` is either `0` or `1`.
Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing.
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
Hard
805,949
410
hello everyone welcome to last day of march lead code challenge and today's question that we have is split array largest sum it's a hard level question on lead code however i will rate this question in medium category and if you like today's solution and you if you feel coding decoded is adding value in your life please don't forget to like share and subscribe to the channel we also have a telegram group and a discord server if you have any questions or any feedback with respect to the videos that i am making please let me know over there thank you now let's get back to the question and let's try to get the maximum out of it here in this question we are given an array of integers and an integer value m what we need to do we need to split this complete array into m contiguous sub rs remember this point m contiguous sub arrays what we need to do we need to write an algorithm to minimize the largest sum of these m sub rs for example here in this case we are given numsas 7 2 5 10 8 and the total number of groups that are to be formed happens to be two there are multiple ways to split this nums array into two groups however the best possible way would be we make two groups one of seven to five and the other one as 10 18 the largest sum of these two groups will be 18 which is corresponding to this one and the other one would be 7 plus 2 is 9 plus 5 is 12. so the answer that comes out after the splitting is 18 i'll be walking you through this example as well as the algorithm to go about it by the presentation so let's quickly hop on to it split our largest sum lead code 410. so let's take the same example that was specified in the equation we have the elements as 7 to 5 10 8 and the total number of groups or subsets that we are targeting happens to be 2 in nature so what we should do we will be using the range based binary search technique to actually identify that maximum allowed value of subset sum here in this case what we will do will simply choose a max allowed subset some value and we are going to find out the total number of subsets that can be formed out of this input array using this max allowed subset some value and in case this number turns out to be greater than m then what we should do we should increase the assumption value max allowed subset sum that simply means updating our low pointer otherwise we should decrease our max allowed subset sum and that simply means updating our high pointer so i'll be talking more about it but from the crux of the problem this is the algorithm to go for it you will understand it better when we will iterate through an example so let's shoot for it so let's take the same example that was as effective in the question we again have the elements are 7 to 5 10 8 and the total number of groups that we are looking out for happens to be 2 in nature so in range based binary research technique what do we take two pointers one the low one other one the high one and what will be default values of these so let's assume the low value to be the maximum value that is present in my input array what is my maximum value present in my input rd this happens to be 10 and what would be my high pointer so one case would be to consider the entire array as a single subset and the total sum of this entire array would be equal to 7 plus 2 is 9 plus 5 happens to be 14 plus 10 is 24 plus 8 is 32 so one possibility of treating the entire other single subset and the total number of groups that would be formed would be obviously one in that case but in order to take a higher upper limit we can assume it to be 32 which is the total sum of all the elements total sum and this is a max element present and what do we do now we go and identify the middle pointer so mid happens to be 10 plus 32 by 2 which is 42 by 2 21 now what we will do we have identified the first value of our assumption max allowed subset sum now we will go out and look out for the total number of groups that will be formed with you in this input array with the upper limit of 21 so let's get started what we will do we will create two variables the first one is total subsets that will be formed tsv and the other one would be the current running sum corresponding to each subset so current running sum c r s so let's start the iteration both of them will be initialized to zero by default and right now we have seven as a first element that means we will simply go and create the first subset let's increment it to one and add seven to it so seven gets added so what is the current value of current running subset sum it is 7 right now it is way less than 21 that means more elements can be accumulated in this subset so let's proceed ahead next we see is 2 so let's add 2 to our current running some variable and the value gets updated to 9 is again lower than 21 that means we can accommodate more elements on to this subset let's proceed ahead next we see is 5 plus 14 gives me for 5 plus 9 give me 14. so 14 is also lesser than 21 as a result of which more elements can be accommodated into this let's proceed ahead next we see is 10 so 10 plus 14 happens to be 24 so as soon as you see that the value exceeds your maximum allowed subset some variable which is 21. what do we do you have to immediately split the input array at that position so you're gonna make one split over here as a result of which the total subset counts get a break gets updated by 1 and the value gets updated to 2 and also along with this you should all reset this value to 10 rather than 14 because now you are considering a new subset altogether so the value gets updated to 10 which is a current value held at that particular element let's proceed ahead next we see happens to be 8 plus 10 is 18 and it's again lower than 21 along with this we have completed the iteration of the over the entire array the total number of subsets that got formed happens to be two in nature but is this all no it's not yet 21 is one possibility of answer but is it the most optimized one is it the minimum one out there the answer is no we could look we should look out for the lower values that using which we are able to form two subset groups for doing this what we should do we should reduce the high pointer from 32 to 21 and let's redo the entire thing again 10 plus 21 is 31 by 2 gives you 15. so let's try and check with the upper limit of total sum as 15 how many groups should we make so let's start the iteration and first we see is seven and let me just create the two variables c current running sum and total subset count tsb is total subset count both of them are initialized to zero by default we see the first element as seven we increment the total subset count to one and the sum gets updated to seven so seven is lower than fifteen more elements can be accommodated next we see is two we have we get nine here let's proceed nine is again lower than fifteen more elements can be accommodated next we see is five so five plus nine gives you fourteen is again lower than fifteen more elements can be accommodated next we see is ten so ten plus fourteen gives you twenty four twenty word happens to be greater than 15 as a result of which we should create a new subset at 10 so a new subset gets created and along with this we should increment the total subset count to 2 because a new subset is getting created along with this don't forget to update the current running sum since you have started creating a new subset to 10 instead of 24. let's proceed ahead next cc is 8 plus 10 happens to be 18 in nature again the limit exceeds as a result of which we again have to create a new subset at this particular point therefore the total subset count gets incremented by one it turns out to be three hence using 15 we will have to form three groups at least which is not as per the question expectation because the question said you are only allowed to form two groups at max therefore 15 can never be the answer since 15 can never be the answer what we should do we should increment our low pointer gets updated to mid plus one but as a result of which the low value gets updated to 16. so now low is 16 high is 21 what we will do we will again calculate the middle pointer and let me just change the color of pen and 15 16 plus 21 gives you 37 by 2 gives you 18 so mid gets updated to 18 and let's restart the entire iteration again let's create two variables current running sum and total subset count let's start the iteration both of them are in initialize to zero this gets updated to seven and this gets updated to 1 7 is less than 18 as a result of which more elements can be accommodated this gets updated to 9 is again lower than 18 more elements can be accommodated 5 plus 9 is 14 more elements can be accommodated 10 plus 14 is 24 is way greater than 18 as a result of which we have to create a new subset here the subset can count gets updated to 2 and this value also gets updated to 10 by virtue of creation of a new subset so this gets updated to 10. let's continue the iteration next we see is 8 10 plus 8 is 18 and 18 is also within the limits again we are able to identify that with 18 a possible solution where we are making two subset is available and valid although 18 turns out to be a valid answer however we should look out for a lower possibility that may exist as a result of which again we will do the same thing we will reduce the high pointer to mid and this gets updated to 18. now high points to 18 low points to 16 again what we are going to do we will calculate the middle one 18 plus 16 gives you 34 by 2 turns out to be 17 so there are the low points to 16 high points to 18 and mid points to 17 again let's create two variables one for current running sum other one for total subset count and let's start the iteration and check for some 17 how many subsets should be created so let's start the iteration the first one we see is seven so seven gets added and the total subset sum gets updated to one seven is lower than seventeen more elements can be added it gets updated to nine plus five gives you fourteen more elements can be added 14 is less than seventeen and now 10 plus 14 gives you 24. as a result of which we have to create a new subset so a new subset gets created the running sum gets updated to 10 because you have created a new subset at this particular point and let's continue the iteration 10 plus 18 gives you 10 plus 8 gives you 18 as which is again greater than 17 therefore we again have to create a new subset over here the total subset count gets updated to three one corresponding to this one other corresponding to this one and the third one corresponding to this one again three is way out of our limits as a result of which what we should do we should increment the low pointer low gets updated to mid plus 1 which is 17 plus 1 which is 18 low gets updated to 18 high gets update high is also 18 the loop breaks out and the answer turns out to be the value that is held at the low index which is again 18 and 18 is the final answer to conclude it further let's quickly walk through the coding section and i'll exactly follow the same steps i have just talked here the first task here is to identify the lower bound and the upper bound so for the lower bound what do we identify the maximum element that is present in my array and for the upper amount what do we to find out the total sum of all the elements that is there in my input array and i have identified them using an iteration over my nums array and once i have done that i have created two variables low and high i applied the binary search range based technique i go and identify the middle element and this middle element would act as my maximum allowed subset sum variable that i showed in the presentation so i have created a helper method valid division possible using this sub maximum subset total sum variable it accepts the nums array and the total number of subsets that we are looking for the target subsets that we are looking for if such a division is possible what do i update my high to mid otherwise i update my low to mid plus one pretty simple and straightforward we have been doing this from quite some time once we break out of this loop i return the low pointer now the problem reduces to writing this helper method appropriately so it accepts three parameters maximum possible sum of a subset of the num's array and the value of m total subset count total running sum and total substrate count is initialized to one total running sum is initialized to zero i start the iteration uh with each iteration i update my total running sum and adding the current element into consideration into it if it goes beyond the maximum possible some value what i should do i should create a new subset out of it therefore total subset count is getting incremented the total running sum gets reset to zero and then i add the current element into concentration into it and as soon as i do that i check whether my total subset count happens to be greater than the target that i am looking for if it does then it is not possible and therefore i should return false otherwise i in case i have never met this false condition i should return true so let's try this up accepted 84 faster which is pretty good with this we have successfully completed the march lead code monthly challenge this is a 10th batch over the period of last 10 months and i can say with a lot of pride that we haven't missed even a single day and it's all big possible because of the love and support that you guys have shown please continue doing the same and i promise the next hundred batches will be ours please spread the word about coding decoded because a lot of effort goes in creating these videos every day and i want to thank you for being such a valuable audience to my channel thank you
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
1,520
20 crime that is called maximum number of berlin his swings the truth is this problem is a headache he also shares the last contest of 198 the agreement is the truth this cannot be resolved during the contest because the truth is that I did not have time to The last contest I served you 3 but this one I didn't even get to it you are the third I mean I think the hard was easier than the 2 mm but well this doesn't necessarily have to be hard but it is quite confusing well confusing and not high you will see what it is about is that they are going to give us a string and what we have to return is a list with with text strings that I to football inc ambitions that none of the text strings about write, that is, for example, if he sent, he is not, he has a of f, I cannot send, he is because if he overwrites the scene and if I am going to send a string, it has to contain all the occurrences of each of its characters, for example estimating I can't send it because here there is a letter outside and there are also two strong ones and I have to send it, I have to send all of these, no, if the command is there, I have to send all of these until the last occurrence of if I want to send, it's only okay because it's not There is another one and if I want to command these two it is ok because there is not another and again if I want to send and these are not ok because here there is one to excite to command these 13 is all that so here in the example they tell us that these are all the Possible chains that are brave can form it, then we are going to return a list with the largest number of possible chains. For example, if I send this chain that occupied a discount to the word, do not put any others where we can only give one, therefore this one is not If command is there then I could no longer command this one or this one because this one includes these three I could only command this one and then it doesn't make much sense for me to command it if command is taken from these two and its own commands from these three if this one is the solution but be careful there is another thing that works for me even more complicated for example in this case there are two correct solutions one correct solution is this because I can send this one of this baby and this cc not but we have the correct solution is this one you can't sending this baby is cc and it's okay, but if you come to this solution, what happened to me that time when I was solving it, they take it as bad because of the crisis of sending her to have less than the smallest number of possible characters, no, what is it? What do they tell you here, they are correct because it has more, so it's an absolute pain in the ass, so what we're going to do is do it well, explaining as I do it because if it's not going to make me crazy, we're going to be two faces, two chains, two weapons, well, two arrangements where we are going to put the first occurrence of each character and the last occurrence of each character is not going to be the I could do it alone we are going to do it like this then well he is equal to a fan and it is going to be let's go to part of the alphabet no Fortunately it tells us that it only contains the English Leathers walkies so therefore our two arrangements can be something like this let's once put it is know that I like to do because I like to put where you will start eating where I am going to put the result and coming back so I feel that it helps me shape the function so well let's start filling this doesn't know how to fill first we're going to put how he's going to have all the initial position of each of the characters we're going to fill with interior max neighborhood that is the value that the characters that do not exist will have and the other is how the last occurrence of the characters will have. We are going to fill it with minus 1 no and now we are going to start filling this, that is, the third minus point lentz also plus no and then we are going to first get the index of the letter that we are not for example we can use this example here this is our example so here we have that the help here is not there it goes here and the index of this letter is going to be that dot char and minus that is the index b where the count of this letter is going to come in these arrangements and it invex that is, for the letter a this there was a zero this is going to be more dot min and that index that we have at this moment compared to what we have already had before it would be and of course it would be exactly the same but with max in fact here we could simply put always and nothing else we don't have to do this if you are going to put the last occurrence like I don't know anything else like this and well now that we have this we are going to start evaluating all the possible possibilities this is not a brute force solution it is not that I am going to evaluate them all but well what I am going to do we are going to start like this and what it's good if we start if we grab a string that starts from here what is it going to be let's see this what is going to be the length of the smallest string that we could have no then from the outset it 's going to be from the first occurrence of 's going to be from the first occurrence of 's going to be from the first occurrence of the thing that is there where we are until the last one, not while he is there, but we also have to make sure that within these characters there is not one that comes out, it doesn't come out, we get it, ife, it comes out, and it doesn't, but let's imagine that we had a trade, then this is no longer a valid string. we have to include why this part of this string is not the case but in others that is even the case this is like being something like that wanted to call range is a function called reich to which we are going to pass and the s room and is the place where we are and the art island I am going to do this function which is going to return this external nor back in an arrangement that has 0 and has 1 2 3 4 5 6 7 no sorry 0 1 2 3 4 5 6 7 doubts it 's going to give us something like this I'm not going to do this function in this function is the key and before this I'm going to be an asset not to be arrive from arrangements between two and what you're going to try in this stand it will be the last one, let 's say the last valid string for that 's say the last valid string for that 's say the last valid string for that point, it doesn't seem like that's where we are, it starts where we are, it tells us that we have the range, we are going to do this if our stack is not empty and range but it is greater than or equal to or In other words, it means that it is ahead of injuries that we want to see if this is possible, this string that we have right now is smaller than the string that we have there and that I know about writes because if it is smaller than yes, we have more possibilities of being more extremes then we are going to do it this way 1 the right limit is less than or equal to st 1 if so then the session we have there is of no use to us and we have to remove it and we have to remove this restriction it is of no use to us we are going to put it in here If it works for us, no this then now well before continuing I'm going to make this function the function of the range that is going to have a in the lynx where we are going to start and the action so here is the interesting part and it is for What are these arrangements for us? Here, the first thing we are going to do is do a brief character cars, it was going to be char arts and then in this case here we have one and we are going to take out the raid kindly the right end of this character no then stronger rights and we must take from here it is not going to be r s less we have the right limit no so for gene j we create a new variable and we are going to start from this one is equal as long as jota is less than or equal to right and we are going to increase hotz so What we are going to do here is that we are going to start evaluating this no, the first thing we have to do is see if it is letters and if any of the others that we have here are outside the margin of this string if it is outside the margin Towards the left, that string does not work for us because it says that there is already a previous letter and that we already evaluated it before, so that does not work and if it is on the margin to the right, before we have to extend that margin, no, then, well, yes, well, here before this is going to be equal to that point at and the cancer is that if l c - a is less than and that is to say if this l c - a is less than and that is to say if this l c - a is less than and that is to say if this letter appears before the a and with which we begin the index that we have up here is that we do not It works so it won't return null if it doesn't then let's see if we have to extend the right side so to extend it simply the range is going to be equal to plus point max if it should be right this I appreciate new character so let's see the limit this character if this character comes from here for example let 's imagine that we have one from here 's imagine that we have one from here 's imagine that we have one from here after this one then our range our raid is going to be around here we don't have this because we get to the d and we see that the moment is here we have to extend it and so we get to the final stringer and r and well since we have it simply return and ins and so we already have the range and we compare it with what we have for example it looks like a grid demonstration of this would be what we would have in our stack after it after the first is our i and it we are going to eat we do not have anything in our staff we are simply going to put we have in the seven that covers all of this we are going to remove this key then it covers all of this not until here the next iteration our range is going to be equal to this so what is going to be equal from 1 to 6 then since our range is this is greater than or equal to this and this is less than or equal to this we are going to remove this because this does not work for us and we are going to put our new reich which is going to be about 62 in the next iteration we have this It's not there, we don't have any other in our range it's going to be 2 to 2 obviously this one where it's greater than 1 and this is better than zero and we're going to get everyone comfortable this is going to be our new one this is going to be the new one but our technicians we can get to efe and f the range of fe is 33 320 2 but 3 is not greater than two so therefore we are going to enter a new value of ours this is x 33 and then to the next value we have a but here it is going to return null because here it is already We have an occurrence from before is here it will return null and if double null and branch is equally null we are going to ignore it so well this point of doing nothing is going to be null let's even say that the same thing would happen that we have a null from null we take away from 13 it is going to be 0 1 2 3 4 5 6 7 8 9 10 8 to 10 it does not shrink with this one and nothing happens so this is what we have now our taxis realize this you correspond We have these three in the result so our is here we have the three this valid strings castelló from Lance's video well now we are going to create our result wire when while it is not empty we are going to make an ace pontes is also equal to 7 point pop three base points equal points your swing 2003 11 preference that the psuv exclusive sign does not include rather it includes a scam that is why at the limit we have to add one more rather it is not inclusive for I already think I am the whole problem we are going to comment on this new shortlist during the compilation nerd something like this is a nightmare and it was a lot it is on line 25 it says that st yes what else do we have and it works for this series it works for everyone it doesn't work for this one why move on because this is an interesting case and it seems to me It doesn't work because of this it is opening these two that are said to be incorrect it works let's see for the code that I have already made this is here what would happen let's see I think this could be why it doesn't I wanted to but it doesn't make complete sense how precisely this was the problem that this was the case that it took me a lot of work to do and this well and what happens view well this is the result this had to see and code that I had already done but well it was a mistake of d we are not with a solution this Tuesday and I want to see one thing if anyone can be made more efficient instead of it seems to me that the manager that is not the same the thing is that I have the theory that the than using an additive like this that is faster than using a stack but it seems that it is not good anyway this is this code connects it works this is a horrible problem the truth is
Maximum Number of Non-Overlapping Substrings
number-of-steps-to-reduce-a-number-in-binary-representation-to-one
Given a string `s` of lowercase letters, you need to find the maximum number of **non-empty** substrings of `s` that meet the following conditions: 1. The substrings do not overlap, that is for any two substrings `s[i..j]` and `s[x..y]`, either `j < x` or `i > y` is true. 2. A substring that contains a certain character `c` must also contain all occurrences of `c`. Find _the maximum number of substrings that meet the above conditions_. If there are multiple solutions with the same number of substrings, _return the one with minimum total length._ It can be shown that there exists a unique solution of minimum total length. Notice that you can return the substrings in **any** order. **Example 1:** **Input:** s = "adefaddaccc " **Output:** \[ "e ", "f ", "ccc "\] **Explanation:** The following are all the possible substrings that meet the conditions: \[ "adefaddaccc " "adefadda ", "ef ", "e ", "f ", "ccc ", \] If we choose the first string, we cannot choose anything else and we'd get only 1. If we choose "adefadda ", we are left with "ccc " which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose "ef " since it can be split into two. Therefore, the optimal way is to choose \[ "e ", "f ", "ccc "\] which gives us 3 substrings. No other solution of the same number of substrings exist. **Example 2:** **Input:** s = "abbaccd " **Output:** \[ "d ", "bb ", "cc "\] **Explanation:** Notice that while the set of substrings \[ "d ", "abba ", "cc "\] also has length 3, it's considered incorrect since it has larger total length. **Constraints:** * `1 <= s.length <= 105` * `s` contains only lowercase English letters.
Read the string from right to left, if the string ends in '0' then the number is even otherwise it is odd. Simulate the steps described in the binary string.
String,Bit Manipulation
Medium
1303
70
Hello hello and welcome to another interesting problem in a series of wedding this time it's called climbing stairs is amazing problem let's get you to climb stairs steps to reach the top is this time till one or two steps in which you can climb to the top Suryavansham Examples Which Will Tree To Understand Diagrams For Example Of Various Tools Tips Number Staircase Okay Day We Invest Buddha Vihar To That Tech Morning In Front Of Science Calendar Style They Always Celebrate Basic Such Supoch Hai Zero Steps And Win Over 200 Website Address Novelty Balance Possibly Have Only one step when you have one where it is from Dahez traffic jam to the first epistle to have two steps you have to Vaishnav exam the first step in the second step is one way or another way from this Ruchi Delhi Jammu to the second step difficult climb To step by step climbing once upon two steps OK knowledge to want to the case when they have three lips in this case what we can observe its benefit investment so you can claim the first step in thoughts or you can play in the second step and you Can go to the third point is the scene who is this point sunidhi part of the solution is me this point to the solution soi the 251 basically 2015 way tours and travels and tours subscribe 2.2 and take one or two tours subscribe 2.2 and take one or two tours subscribe 2.2 and take one or two song subscribe example tips 123 456 soi A Big Brother Fold Has Gram But Instead Of That We Can Do If We Know Dear All The Best Time To Step 4 Day Special All The Adventures After 10 We Can Be At Least Nine To Step 600 Always Were Taken To Lines For Is Not Did in this way the sacrifice of another possible case will be one a speech and take all the best commando to climatetemp.ino day you can reach tips by climatetemp.ino day you can reach tips by climatetemp.ino day you can reach tips by jumping one-stop-shop for any given jumping one-stop-shop for any given jumping one-stop-shop for any given values ​​in this page you can either acid values ​​in this page you can either acid values ​​in this page you can either acid or Subscribe as soon as possible to find the best to reach subscribe and 232 to 234 100 This What is this problem know the two to subscribe if you subscribe Very simple and easy to one can just returned back to leave way is equal to Ajay Devgan Vijendra Don 2-The Co Interview Ajay Devgan Vijendra Don 2-The Co Interview Ajay Devgan Vijendra Don 2-The Co Interview to be Sales Which Can Just Doodh Records Approach Soul Street Don Climb Stairs of - OnePlus Climb Stairs of - 200 Om of - OnePlus Climb Stairs of - 200 Om of - OnePlus Climb Stairs of - 200 Om Vipal Pimple and Note Suggestion Simple Record Solution But What is the Solution Subscribe Button Summit and See What is The Problem Solution News Dynamic Programming Approach To Waste Macrame Changes To This And Die The In Programming Approach Dead Bodies To The Values ​​Which Are Known To Be Added To Into Make Dead Bodies To The Values ​​Which Are Known To Be Added To Into Make Dead Bodies To The Values ​​Which Are Known To Be Added To Into Make Quite Very Easy And Very Fast So Let's Declare Om Vectors And Rhythmic Quality You Is Dynamic Programming And Let Me Give Space of Interest to Eliminate Life Twenty-20 First Nine to Give 020 the Twenty-20 First Nine to Give 020 the Twenty-20 First Nine to Give 020 the First Step They Have No Steps to Climb Even went to ways to that ok also sone instead of this will give in this lesson equal to duos-2 ok otherwise what we can do it is equal to duos-2 ok otherwise what we can do it is equal to duos-2 ok otherwise what we can do it is can edit and point is equal to three eye lashes sainik way to in i plus so they can take Already Stored Values ​​Of The Number Of Waste Clients Values ​​Of The Number Of Waste Clients Values ​​Of The Number Of Waste Clients Tips City Of I Villagers Painted Epf I - One Plus Five Minutes To Like To I - One Plus Five Minutes To Like To I - One Plus Five Minutes To Like To Climb 6 Tips From This Cold White World Client For And Weakness Give Don D O L N Slow This Fruit Work Plate From Shift Working Select All Vitamin C Is The Time Limit Exceeding And Not In This Case Solving Is Expected 151 So Let's See What Is The Problem Here Input V One End Outputs 251 Return Gift 2 Editor In Chief Air Tight Is The Problem That Admission Mithai Ansh Working On Switch walking and see in hundred percent of see plus online submission sperm in this very fast here run type of this is very fast and a beauty of dynamic programming approach
Climbing Stairs
climbing-stairs
You are climbing a staircase. It takes `n` steps to reach the top. Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top? **Example 1:** **Input:** n = 2 **Output:** 2 **Explanation:** There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps **Example 2:** **Input:** n = 3 **Output:** 3 **Explanation:** There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step **Constraints:** * `1 <= n <= 45`
To reach nth step, what could have been your previous steps? (Think about the step sizes)
Math,Dynamic Programming,Memoization
Easy
747,1013,1236
236
hey everybody this is larry this is state dirty of the june eco daily challenge you've made it if you're here the last day of june hope you did the entire month uh hit the like button hit the subscribe button join me in discord let me know what you think about today's problem the lowest common ancestor of a binary tree so this one is a very well researched problem uh or at least at some point i don't know if this is a well-known thing don't know if this is a well-known thing don't know if this is a well-known thing because people keep on telling me about this but i actually a fun fact of one's quick little story is that um my professor in college actually it taught this as part of the algorithms uh and actually goes into that uh linear time processing constant time query lookup um yeah algorithm which gave birth to a lot of competitive algorithms that are kind of have names that when i learned it did not have those names back then like sparse table um what was the other one uh there are a couple of things i forget what they are now so maybe i made that up but in either case uh in this particular problem let's take a look at it first it seems like you only get one query so you don't really have to be that optimized and you can't really be that optimized anyway to be honest because um yeah because you have to look at every well i was gonna say you have to look at every um every node to kind of find the items right um because you're not given the note oh actually no i was wrong you are given the notes themselves so um but i think in the worst case it's still gonna be linear because you have to look at the entire tree like if you have two linked lists essentially that meets up at top um i don't think there's any way to avoid it so yeah so it's gonna be linear anyway but it is a fun algorithm you if you uh want to read up on that algorithm the of n algorithm is actually pretty cool of pre-processing and all one query pre-processing and all one query pre-processing and all one query um and you can even do the um you can do an n log n with all one querying pretty assembly as well without with just sparse tables so anyway that's kind of a funny uh fun trivia for those of you who are into the harder competitive ones otherwise uh it's totally unnecessary but i am a big fan of lca and as a result i'd say does have a soft spot in my heart as an algorithm anyway so yeah let's take a look at this one so you're just given two notes directly even though the input doesn't look like it i don't have to search for it which is why i was a little bit whatever but yeah so then here what can you do right um i mean the i think the straightforward way is the off and space way um yeah and i guess that's i don't know if you can do any better i don't think you can only because in this particular case even i said that you didn't have to search for them i think you do anyway because you have to find the uh the parents and stuff like that because you know just to give an example if you have a p note and a q note with just like a common parent there's no way of you to know if i'll kind of traversing the tree so you still have to find the notes so that's one and then the second thing is basically you have two paths one to p and one to q and there are a couple of ways you can do it forwards you can do it backwards you can do a sort of um yeah and then just a linear you know slide through the win uh foo in a way or whatever i mean that's what i'm going to do because i think all these cases are off and anyway um and there are some options it depends on how you want to optimize for this problem a couple of optimizations here and you can chat about it because you can just use one array you can use two arrays but with viewer code because it went away then you have to kind of write special code for each the p and the q but if you use two arrays then it's you can you only have to write one code so this is what i'm parting against because you could just write one finder for both p and q and then just do like a common prefix type thing right and that's basically the idea i think i'm gonna do that so let's get started uh and i know that this is okay because like i said the lower bound is going to be at least linear time because you have to look at the entire tree to find um to find the nodes and yeah don't um yeah i think that's what i'm gonna do i'm trying to think about what's a good api for this i think a good api for this is by reasonable here's a node um let's just say for now it will return a tuple oh uh which has a uh um a flag found um a brilliant flag either is found and then maybe the array that gives you the path you can do it either way you can maybe even use this uh like a variable outside the scope or something like that but i don't know i'm gonna play around with it so note is none you return force whatever um yeah if node is equal to oh i guess i have to give the uh looking for i'm trying to think about name and let's call it x or target is good all right target um i know that so what i'm looking for right now is just double checking for a second i guess they're unique because what i was looking for is that you know this is a pointer equality check and technically unless you know what you're doing you should not be doing that or if you know your language i guess depending on language as well um so you can either do something like this or you could just do what i did because i think in this case it'll be okay because we're looking for exact note or at least assuming that they give you the exact note that's already in the tree versus um a replica of that which i guess is actually not clear so let's stick with that route to kind of make sure that we return true um and then no say otherwise if find node.left if find node.left if find node.left okay let's just go left as you go to find note.left find note.left find note.left if left of zero that means that we found it on the left then we return true um this is a little bit awkward i think if you ask me i would maybe have a class or a name tuple for this tuple so that it can be a little bit clearer a little bit easier to use um and a little bit less error problem but for the purpose of time i am a little bit lazy so that's what i'm going to do this is the way plus um no all the other way around actually whoops because we wanna okay we also do it for the right of course we have to actually do the recursion first and then otherwise we also return force at the very end if you cannot find in the left or the right and now what's left is that we have to find the root of p and find the root of q and let's just call it um p node maybe i don't know naming is really hard for me um and then oops or maybe p path and q path and now we can just look uh for x y in sip of okay so for p node q node in sip of p path q path if p n that value is not equal to p or q n that value then we return the last node maybe and then we set the last node is equal to um just pian i guess i don't know because the root is always the answer per se um and then if this goes out of the thing then the last one will be the last one so i think this is okay maybe i have some off by one issues but the idea is basically that talked a bit today about it but i think this is i don't i think the hardest part for this particular problem i forgot to search for something i think the hardest part about this problem is just proving the lower bound perhaps and if you're in an interview obviously uh talking about um the lower bounds and stuff like that so that you can kind of move on at least that's what i would look for when i was an interviewer um because i think the implementation once you get the album down is uh pretty straightforward and if you are convinced that you can do whatever then it's pretty straightforward this is a weird looking interface for the tree am i doing this right i guess that's right why does this give me an unknown error that's what omni is okay so it worked that time um okay so does it have at least two notes yep okay so i guess that's the thing that i would have looked for is maybe do one nodes or no nodes um and this is linear time as we said we'll kind of um go over it in a sec but that's why i didn't really take a uh i didn't really worry about the complexity this one doesn't really matter they're just unique right and we don't really do any arithmetic so let's give it a submit and here we go the last problem of june done so what is the complexity of this well this is just a depth first search or pre-order traversal of the tree so or pre-order traversal of the tree so or pre-order traversal of the tree so this is going to be linear time and we do it twice so it's still going to be linear time in terms of um yeah and this is also linear time because you can in the worst case and that's what i think about when i think about time analysis in the worst case you have just two linked lists and they point to the same note or maybe roughly the same note um i don't know if they have to be different i guess they have to be different but if you have a linked list and they're like next to each other but in a node this is going to be linear time but neither case this is all going to be linear time in terms of space um this is also going to be linear space because we put the path of the array here i don't know well the truth is you cannot actually do that much better because in the worst case this fine is going to take up the stack space of linear stack space again using linked lists as we talked about um so yeah um can you do it any better in terms of space because time we proved the lower bound can we do an over one space um i don't know maybe no i guess not because you still need to know parents and stuff like that so i think that's always going to be a little bit tricky like even if you do some kind of traversal of the tree that um it's lower you still i don't know maybe i'm wrong on this one let me know in the comments or if you looked at the comments or whatever i guess we could take a quick solution look but uh but i don't think so that's my guess i'm not always right so let's see if i learn anything new um backtrack okay yep irritatively that's what i was saying you had to leave without parenting okay well it's still uh yeah i don't know okay didn't really read that much but i think these are the same for ideas anyway um okay that's really all i have for this one let me go back to the code so you could take a gander what okay so yeah uh that's all i have for this one this is end of the month hope i see you next month which is tomorrow uh stay good stay cool to good mental health thanks for uh chilling and kind of do problems with me for this month i don't know i just enjoy doing it so anyway i'll see you later bye
Lowest Common Ancestor of a Binary Tree
lowest-common-ancestor-of-a-binary-tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)." **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1 **Output:** 3 **Explanation:** The LCA of nodes 5 and 1 is 3. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4 **Output:** 5 **Explanation:** The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. **Example 3:** **Input:** root = \[1,2\], p = 1, q = 2 **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[2, 105]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` * `p` and `q` will exist in the tree.
null
Tree,Depth-First Search,Binary Tree
Medium
235,1190,1354,1780,1790,1816,2217
1,701
hello friends today we are going to solo elite code problem that is pro number 101701 average waiting time if you directly want to see the code then this is our code you can see it and if you want to uh if you want to know about the question and i haven't read the question till now then the question is that we have given a 2d array uh named as customers in which first element is the arrival time of the customer and the second time second is the time taken by the this to be prepared by the safe these two things are given and we have to calculate the average waiting time by the each customer to be wait in the restaurant we have to calculate that time and before we calculate this then we can see that this problem is very much similar to the first come first problem in operating system you can relate directly to that problem first come first server algorithm so let's see what how we can approach to this problem uh we have given this data if we analyze that then the first uh the first customer uh arrived at the first second and it's my last suppose uh first minute and it's this take preparation and this will be prepared in two minutes by the self the second customer will come at the second minute and it will and it's this will take five minutes to be prepared if we see out and see it on a number line uh sorry timeline then let's assume it is zero and here is one first customer appears at here and its food will be served for two seconds two minutes then it will be three comma two the second customer arrive at second minute and it's over take five minutes to complete so but the but here we have given a constraint that the sf can will be doing will be preparing one food at one time so the chef will prepare the food of the second customer after he finishes the preparation of the photo first customer then that means he will start preparing the food of second customer from three and it will go up to the five seconds let's say it is comes to here and the time taken then the time will be right now is 8 minutes before the 8 minutes we have seen that there is another customer number 3 which arrived at the 4 minutes and its food will be served at and its food will be served in four and three seconds three minutes and but our safe is busy it will be free after eight minutes then he will invest his time to prepare the food for the third customer so for adding 3 then he will add in here 3 and it will raise to the 11. from here we can see that the uh the food of the first customer when he arrived is one minute and he will be served at the third minute then the average then the time waited by him is 2 minutes and for second customer he arrived at 2 minutes and his food is served at 8 00 8th minute then his total waiting time is eight minus two that is six minutes and uh for the third customer he arrived at the eleventh uh he arrived at the fourth minute and uh his food is served him to him it at 11th minute the average waiting time for him is 11 minus 4 that is 7 minutes and the total time taken by the total waiting time for each of the customer by the by adding each customer's waiting time will be 15 and we have to calculate the average waiting time so we will divide the total number of customers that we have in this case we have three customers then we will divide it by three and we get the result our five note that the question is also saying that we have to print the result precisely up to 10 raise to power minus 5 units okay so for precision we use double is actually precise the results up to uh up to the 14 decimals but we need ordinary only 10 raised to the power -5 then it's okay this is our basically we have understanded the first example let's see we can build an algorithm from it how we can build an algorithm from it um okay this is this first we will see that first we have made it a timeline we note that we have made a timeline and we here we are and here we are doing our calculations and from this with the help of this timeline can we calculate can we made a can we make a algorithm from it uh then we if we closely see then we make a variable name as counter which counts um which will be responsible for each customer to say that let's suppose is which will tell the safe that basically counter will store a time at which the safe will start preparing the customer for the is customer ith customer food is customer dish and basically the counter is storing a that time where he will start preparing the food for the 8th customer let's see somehow we find the a variable find the starting time of the preparing of the dish of the eighth customer and then we add the time taken by the him time taken by the chef to prepare his mail then we subtract its uh that internet and that we that the final answer we will get is serve time then we subtract the serve time from the its arrival time and the net time we will get is the waiting time so serve time minus its arrival time will be the waiting time if you didn't understand then we will we i can help you to understand from the code first of all what we are doing we are making a counter which stores the information about the when he will when the chef will start preparing the dish of the ayat customer uh let's suppose he was he was on the custom the save was once to make the this of the first customer at the first unit of time then counter will store here information is how you how he will store the information and basically this will be the max of the previous uh previous customers serving means preparing time start preparing time and the finish time last customers finish time and is customers starting time arrival time it will be the max of those in these two the serve time will be the addition of the his starting time plus time taken by the disk of the ith customer to be prepared by the safe the serve time then we will subtract the time from the customer's arrival time we will get overall waiting time and we are adding the waiting time simultaneously to our tottenham to find our total waiting time by the each customer by each and every customer in this who is coming into the restaurant so we are adding in it into the rest and then we calculate the rest and after calculating the rest we are dividing by the total size and total number of customers that come into the restaurant so that we can get an average waiting time and hence finally we are printing the result this is the basic solution of this problem i hope you have understand this program very well thank you bye
Average Waiting Time
remove-max-number-of-edges-to-keep-graph-fully-traversable
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:` * `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order. * `timei` is the time needed to prepare the order of the `ith` customer. When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers **in the order they were given in the input**. Return _the **average** waiting time of all customers_. Solutions within `10-5` from the actual answer are considered accepted. **Example 1:** **Input:** customers = \[\[1,2\],\[2,5\],\[4,3\]\] **Output:** 5.00000 **Explanation:** 1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. 2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. 3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. So the average waiting time = (2 + 6 + 7) / 3 = 5. **Example 2:** **Input:** customers = \[\[5,2\],\[5,4\],\[10,3\],\[20,1\]\] **Output:** 3.25000 **Explanation:** 1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. 2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. 3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. 4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. **Constraints:** * `1 <= customers.length <= 105` * `1 <= arrivali, timei <= 104` * `arrivali <= arrivali+1`
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use Type 3 edges first, and connect the still isolated ones using other edges.
Union Find,Graph
Hard
null
144
hello and welcome to the another series of coding today we will solve lead code problem binary tree pre-order traversal so binary tree pre-order traversal so binary tree pre-order traversal so insist of reading this description let me take into the demo board then you will get the further and the understanding okay so what is pre-order reversal what is pre-order reversal what is pre-order reversal in pre-order traversal mean that pre-order traversal mean that pre-order traversal mean that first root will come okay pre-order traversal mean first pre-order traversal mean first pre-order traversal mean first root will come then left child will come then right child will come okay this is suppose that uh here was a node there are two and this child was one and this child was five okay so first the preorder traversal of this should be two then one then five okay then five so this is a move mantra of this pre-order traversal pre-order traversal pre-order traversal so this is only of three nodes in the tree okay how you will get the when n number of nodes in the pre and the tree so how you will get the pre-order traversal of n number of nodes pre-order traversal of n number of nodes pre-order traversal of n number of nodes so we will apply the same rule okay first we will make a empty list okay we have make the empty list after that what we will do we will point our node to a root node okay so this is our root node what we will do here we will first print this root node in our list okay we will append this root node value into our list after that what we will do we will recursively call our function that to our left sub tree okay then it will go here and it will append this value to the list okay this up and it will append this value to the list after that it will go again in the left side because we will first we will go left and left after that when no node will found then it will come into right ok so then it will come here now it will come here because the left node exists of this node so it will come here and then it will print append one after that the pointer will backtrack to here and see that first it will check that if this node has left or right child no this node has no left no right hand then it will backtrack to this node and then it will see that this node has a right child yes this node has a right child so it will append that right child into the list again it will backtrack to this node so the left child of this node was printed in the list okay but there it in this node check that if this node has a right child yes this node has right child so it will append this right child in to the list again it will check again our function will check of this node if the left node exists of this node no left node doesn't exist then it will check at the right node exist of this node yes the right node exists of this node so it will append this value into the list and then after it will check that if the left node of this node exists or write node so no left no right egg node exists so it will return none and after that we will return this our list to our main answer okay so this is a basic concept so let me jump into coding then you will get the further understanding so first we will make a helper function okay first we will make a list after that we will make a helper function we will call it a recursively again and again so we will name it pre-order okay reorder because you can pre-order okay reorder because you can pre-order okay reorder because you can name whatever you like but i'm giving pre-order drivers reorder okay i will pre-order drivers reorder okay i will pre-order drivers reorder okay i will give pre-order only and what the give pre-order only and what the give pre-order only and what the parameter we are going to pass here root and after that first we will check if root exist then we will perform something if the if there is no root then we will return none okay whatever the root node is after that what we have done we have come here okay we have come here we have started from here so we will append this value this root value this value into the list so we will that we will do up array append what will append root dot well then after we will recursively call this function on the left subtree first we will call on the left subtree so we will call on this okay we will call on this first then we will say pre-order oh sorry spelled wrong pre-order pre-order pre-order reorder and what we will do root dot left and then we will call this function recursively on right subtree reorder root dot right then we will call this function from outside of the loop we will pass the parameter root and we will return the our list okay what we have done here we will just let me explain again we have came here okay we i we started from here so we appended this value into in this our list after that we have called recursively the our function on the left sub tree so it came here so the current node become this so it will append here again the left node of this exists so it will come here and it will append this value into the and again it will check that if the left node i exist no then it will check the right node exist no then it will backtrack to here and then it will append this well value into list okay so this is a process so let me run and see that it's working fine what happened pre-order so something went wrong pre-order oh sorry i spelled wrong okay it is working let me run this it is pretty efficient okay i need taking order off and space complexity and order of n time complexity and thank you guys for watching
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
47
hello everyone welcome to day 12 of my leak code challenge and i hope all of you are having a great time my name is sanchez i am working a software developer for adobe and today i present day 681 of daily lead good problem the question that we have in today is permutation 2 it's a medium level question on lead code and i also feel the same here in this question we are given an array of integers and we need to return all possible unique permutations that too in any order let's walk through an example here the input number is given to us 112. so there are three permutations possible which is one two one and if you kindly look at this output then none of the sub list is getting repeated here that means we have to take into consideration that no d repetition of the same sub list occurs more than once let's walk through the other example here the elements are one two three and in total there are eight possibilities that could be generated two raised to power three gives us eight therefore they have specified us with eight possibilities and none of the element gets repeated as a result of which all of them are unique in nature now comes a concern how are we going to solve this problem up if you carefully look at this question then the question itself gives you the hint that the way to go in all such permutation and combination questions is backtracking how to solve backtracking problems i know some of you might be aware about it some of you won't be so all backtracking questions can be solved using a generic template i talked about this template few days back as well when we witnessed combination some three problem in daily record problem in this month itself so if you are looking for learning this template then this video is for you and once you have learned this template go to this backtracking playlist and choose any question out of this playlist i promise you will be able to solve it some tweak in the code is needed but the answer is definite the same template gets applied to all these backtracking problems it will act as a revision opportunity for you and if you don't trust me don't worry i have an honest opinion from the nanje kumar who sold combination some one combination some two combinations some four using this backtracking template that i showcased in combination some three problem and all he had done is change the code a little bit and that it worked for him this also gave him the confidence to solve any backtracking problem in future now you will say can you please show us how can this backtracking template be applied to today's question the answer is yes so let's get back to that question and let's try and extract the maximum out of it so we want to avoid duplication of each and every sub list that may occur for that what we should use sets for it so as a result of which i have created my answer in form of a set of list so that in case duplicate elements gets added onto it set automatically takes care of it along with this we should also keep track of whether this one was added or this one was added so in order to do that whatever i use i have used a visited array so these are two differentiating factors from the regular uh backtracking template and this is exactly the same so let's walk through it so this is the answer list that i have created in the end i'll simply cast this set back to my answer list so that's pretty straightforward let's skip it now comes the question how have we written the backtracking algo so it accepts four parameters the nums the input array the set answer that i have created over here the visited array and new array list for the current sub list that i am looking out for let's quickly go and look at that helper method and the first corner case that i have written or the aborting condition that i have written is if my sub list dot size happens to be equal to nums what do i simply add my current sub list into the result so this is a standard way of writing the back tracking template and moving ahead i have written a for loop starting from i equals to 0 up till nums.length and with each iteration i'm nums.length and with each iteration i'm nums.length and with each iteration i'm implementing the value of i what do i do next i simply go ahead and check if my current index has been visited or not if it is not visited then what do i add it to my current list so sublist dot add nums of y then moving ahead what do i invoke the backtracking helper method and i pass in result i pass in visited and i pass in sublist also i should be updating visited since i have used it once i am using the ith index therefore i should update visited and once i have done this what should i do i should revert back and i should remove the last added element from the sub list dot size -1 -1 -1 so let's try this up and i hopefully it will work accepted looks good and yes we are done so if you carefully observe then i have followed the exactly same template as i talked about in combination some three and i genuinely hope you enjoyed this video if you did please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and do check this video and playlist out it's definitely gonna give you some confidence for solving the backtracking problems thank you
Permutations II
permutations-ii
Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._ **Example 1:** **Input:** nums = \[1,1,2\] **Output:** \[\[1,1,2\], \[1,2,1\], \[2,1,1\]\] **Example 2:** **Input:** nums = \[1,2,3\] **Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\] **Constraints:** * `1 <= nums.length <= 8` * `-10 <= nums[i] <= 10`
null
Array,Backtracking
Medium
31,46,267,1038
502
hello everyone that's all for today's problem IPO we are given n project and profit array what we can earn from a project and the capital array is needed captured to start the project at first we have W capital so we can start the project which needs less than or equal to W capital our goal is to maximize final capture at the end of K times project selection process look at this example since we have only Capital zero we can select project zero index and we can earn profit one now we can select project one and two because we have chapter one we can select project two because its profit is bigger than project one we finish it two times therefore our final maximized capital is zero plus one plus three so it's four at example two since we have on a capital zero so we can select project zero we can earn profit one now we can select project one because we have Capital One so we can on and we can select project two because now we have Capital three and two is less than three so we can select this and we get on profit three we finished three times first time second time and third time therefore our final maximize capital is 0 plus 1 plus 2 plus 3 plus so it's six we can solve this problem using a heap at the example one if we have profit and capture assorted by capital and then we can push profit value to the Heap if capture value is less than or equal to our Capital so in this case we can push profit one because Capital zero is less than or equal to our now profit zero and then we pop it and we on this and our profit is now one first index and second index is less than or equal to one so we can push these values to the hip and then we can pop bigger value this is Maxi hip and then we on three capture we iterated twice so we can return the our maximized profit four okay we made it let's cut it we make a list of tuples with profits and capitals there is no assumption about capitalism sorted in this problem so we sort these tupers by capture ascending order and we make it DQ to make it pop easily we declare our hip to get largest profits and I is 4K times iteration during K times if profit can capture is exist and the first one is capture is less than or equal to Capital what I have now then pop that one and push its profit to the hip this time we need Maxi so we add minus sign to the value we do it again until the condition meets if there is no profit in the heat then we break if not we pop the largest profit from the Heap and change the negative to the positive number we accumulate The Profit to our profit and we trade it during K times and we return the maximized profit that we've earned so far these Solutions time complexity is Big of Androgen because the sword here and there are end times projects with hip operation login and the space complexity is big or oven because the rest of tuples and hip can be enlarged up to n I hope you enjoyed this video and it was helpful and I will see you soon bye thank you
IPO
ipo
Suppose LeetCode will start its **IPO** soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the **IPO**. Since it has limited resources, it can only finish at most `k` distinct projects before the **IPO**. Help LeetCode design the best way to maximize its total capital after finishing at most `k` distinct projects. You are given `n` projects where the `ith` project has a pure profit `profits[i]` and a minimum capital of `capital[i]` is needed to start it. Initially, you have `w` capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of **at most** `k` distinct projects from given projects to **maximize your final capital**, and return _the final maximized capital_. The answer is guaranteed to fit in a 32-bit signed integer. **Example 1:** **Input:** k = 2, w = 0, profits = \[1,2,3\], capital = \[0,1,1\] **Output:** 4 **Explanation:** Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. **Example 2:** **Input:** k = 3, w = 0, profits = \[1,2,3\], capital = \[0,1,2\] **Output:** 6 **Constraints:** * `1 <= k <= 105` * `0 <= w <= 109` * `n == profits.length` * `n == capital.length` * `1 <= n <= 105` * `0 <= profits[i] <= 104` * `0 <= capital[i] <= 109`
null
Array,Greedy,Sorting,Heap (Priority Queue)
Hard
null
967
oh Jesus hey everybody this is Larry this is me in Turkey still in uh Antalya but I'm giving you some ice cream action hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Farm um so yeah I this is still the morning I still just woke up so let me know what you think I'm a little bit off but today's problem is numbers with the same consecutive difference let's see what that means we turn all the non-negative integers of linked and such non-negative integers of linked and such non-negative integers of linked and such that absolute difference between two consecutive digits is K note that every number is in the answer must not have leading zeros because I'm moving the it's not my lap I'm on my bed because there's no tables or anything good here uh in this so yeah uh let's see every number in Anthem must not have leaving zero one okay absolute difference between every two consecutive digits is K okay so oh I see so it goes one and then goes seven okay um because K is seven I mean this seems pretty okay I think this is just proof for us I think there's not that many possibilities maybe I have to do the math on that one but yeah because I think so the way to Upper value before you calculate is that if you have say nine digits right we have nine digits um and that means that this eight signs between them and each of the sign can be plus K or minus K so then that means that there's two to the eight uh possible cases so now knowing that two to the eight is what like uh 256 or something um so yeah so that's basically me saying that okay now I know that it is uh now and I know this is good enough to uh to start right so let's do that uh because we can just brute force is what I mean well actually uh that's given the first number so this is this times ten or nine because no leading zeros so it's the first digit is nine so then that's like either way it's still less than two thousand right so or maybe a little bit more than two thousand but about two thousand SEC so that's good enough for me to get started so yeah I'm gonna do this recursively so remember current away and yeah that's it I guess turn is you go to n then we're good and then we uh We join this and then we enter and then we put it in answer and then we return otherwise we go uh last digit is you go to current the last number and then we either go um pass press k uh so this is in between nine right I mean we can curse con Plus plus k uh it's not an else but if this is the case as well do I have to sort it no we don't have to sort it so we could do it either way I know I have a typo handgun uh I do this right yeah I should be okay I was just wondering about the signs and stuff because it's absolute difference right so yeah okay I mean this is good um and then now we just do for first start and range from one to ten uh because let's start and then we're coming to an answer someone like this right I'm a little cloggy um I still a little tired so yeah uh hmm what did I was sweet interfere oh because this is uh this list is I want this to be a string I and we can ship and add I'm just a little bit lazy so uh don't do this at home actually this is kind of bad code but I'm just tired okay let's go let's give it some it that looks okay I got what oh I hope I don't get long answer twice this time oh no oh dupes hmm I should have tested the zero case uh well all right silly City I made the same mistake again uh I probably should have tested it but I um I don't know I just woke up that's my excuse okay 886 Day Street gay I always kind of did the Nazis here before I did it otherwise you know you may because uh sorry friends otherwise you might think it may timeout and stuff like this right so yeah uh so you have to do the analysis first I what did I do last time at work okay so I huh why did I forget the thing that's weird oh I actually don't do this do I huh but n is not one that's why but what did I do this oh what was even more hmm I guess they I just had no leading still a little differently um cool that's all I have for today let me know what you think stay good stay healthy to good mental health I'm gonna go hiking again or we'll get waking up and then go hiking and all this stuff see you later uh yeah bye-bye
Numbers With Same Consecutive Differences
minimum-falling-path-sum
Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**. Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed. **Example 1:** **Input:** n = 3, k = 7 **Output:** \[181,292,707,818,929\] **Explanation:** Note that 070 is not a valid number, because it has leading zeroes. **Example 2:** **Input:** n = 2, k = 1 **Output:** \[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98\] **Constraints:** * `2 <= n <= 9` * `0 <= k <= 9`
null
Array,Dynamic Programming,Matrix
Medium
1224
1,448
EPF big let's all the best quote problem 148 account good notes in binary tree union ministry approved and axis given industry made it tiffin apart from route 2X during notes with jewelery track number note seervi note's value with this rule for the first to ghaghare [ Sangeet] [ Sangeet] [ Sangeet] Subscribe 4 A Famine Laptop Left Vihar-3 Liye Broad A Famine Laptop Left Vihar-3 Liye Broad A Famine Laptop Left Vihar-3 Liye Broad And Aware Of Life Line Here Behave Way In Her Right Side Website Facility And Tree To Give The First Floor Example Will Start From This Is Not With Its Being Provided With No Vir Is Not Fair Will Beat Dainik 123 Labs Contains A Grade Three Lena Hridaya Nikal Three Liye Withdrawal 40 Subscribe To Pat So Garhbor Yes-Yes Welcome This Is One Is Pat So Garhbor Yes-Yes Welcome This Is One Is Pat So Garhbor Yes-Yes Welcome This Is One Is Great Dainik Doob 49 Will Power Total Veer Vasundhara Ahirwal Switch Off Way Big Show Will Solve This Problem Using Subscribe To Had Good Day That Meditation Hair Only But If It Root Educational Simply Written Pledge A Devil And The Lawe The Year Will Tree To Rule And Subscribe Must Start Pure Scientific Research First Winner Updater Maximum Level To My Daughter Will keep track of maximum volume send a devil and he will return top subscribe must dot right subscribe The Channel Please subscribe and subscirbe 9 Tags Page 10 Torch Light meter1 Kasam 10961 Al Kama 631 300 Gram Sugar Only One She's The Best And see what is the result so what is active on Thursday I slept also contact hai this is so normal this is but let's computers calculator time complexity of this time complexity simple bihar basically scanning all notes time complexity assembly subscribe must subscribe my channel thank you for watching my video subscribe
Count Good Nodes in Binary Tree
maximum-69-number
Given a binary tree `root`, a node _X_ in the tree is named **good** if in the path from root to _X_ there are no nodes with a value _greater than_ X. Return the number of **good** nodes in the binary tree. **Example 1:** **Input:** root = \[3,1,4,3,null,1,5\] **Output:** 4 **Explanation:** Nodes in blue are **good**. Root Node (3) is always a good node. Node 4 -> (3,4) is the maximum value in the path starting from the root. Node 5 -> (3,4,5) is the maximum value in the path Node 3 -> (3,1,3) is the maximum value in the path. **Example 2:** **Input:** root = \[3,3,null,4,2\] **Output:** 3 **Explanation:** Node 2 -> (3, 3, 2) is not good, because "3 " is higher than it. **Example 3:** **Input:** root = \[1\] **Output:** 1 **Explanation:** Root is considered as **good**. **Constraints:** * The number of nodes in the binary tree is in the range `[1, 10^5]`. * Each node's value is between `[-10^4, 10^4]`.
Convert the number in an array of its digits. Brute force on every digit to get the maximum number.
Math,Greedy
Easy
null
1,670
hey there everyone welcome back to lead coding in this video we will be solving the question number three of lead code by weekly contest 40 name of the problem is designed front middle back queue the problem description is we have to design a queue that supports push and pop operations in the front middle and back so we have to implement the following functions which are given to us let us first see what a queue is so when we insert into a queue let's say if we have a queue like this and we are inserting an element into the queue so let's say this is the first element and this is the second element so one is the first one that will be popped out and then two will be popped out so this is the basic implementation of a queue now for the purpose of inserting at the front and then removing from the front and inserting at the back and removing from the back in constant time we have another data structure called deck and those who don't know about that can search the same on search the same on search the same on so here's a entire information about the deck data structure in this data structure you can insert at the front and at the end in a constant time and remove from the front and from the end in a constant time but there's another operation that we have to handle and that operation is to insert at the middle and remove from the middle now what we can do is we can create two such data structures two such decks so this is the first deck this is the second deck and let's say n1 is the size of first one and n2 is the size of second one initially both of these are zero so d1 represents the first deck and d2 represents the second deck now let us say we have to insert an element at the front so we will be inserting so we will first of all will consider these two deck as a combination of these two deck as one single deck so whenever we want to insert some element into this deck we will be inserting in the first deck and that also at the front so let us say the first element is one and one will be inserted in the first stack at the front now n1 will be increased and one will be one now let's say we have the second element is two and we have to insert two at the end of the queue so at the end this is the end and we have to insert from the end so we are inserting but then nothing is there in this second x so eventually this two is going to come at the front and the size of this will increase now and 2 will be equal to 1. now let's say we have another element the element 3 and we have to insert the element three at the middle so when we have two elements let's say one and two we can insert three in the middle so for that what we are going to do is we are simply going to insert 3 into the first deck and that from the end so 3 will be inserted from the end now the size of n1 will be 2. another thing that we have to maintain is the balance between n1 and n2 now let's say we have another element that element is 4 and 4 is being inserted from the front so that will be inserted from the front so 4 will be inserted here but then the size of n2 will become three and there will be a disbalance so we can give priority to the tech one but we can only have one extra element than the deck two and not more than that so let's say 4 is coming here so the total number of elements in the first stack becomes 3 the total number of elements the second deck is still 1 so we cannot have a difference of 2 we can have at most the difference of 1. so now as the difference is increasing what we are going to do we are simply going to remove the last element that is three from the back of the deck one so we are going to remove three and we are going to push three into the second deck that is from the front of the second deck so three will come here and four will be inserted into this so the final configuration will be four then one then three in the second deck and two in the second deck so this is how we have to balance the size n1 and n2 now let's say another element is coming that element is 5 and 5 is to be inserted in the middle so whenever we want to insert an element in the middle we are going to insert it into the n1 first but as the total number of element is 4 so 1 four one three and two five will be inserted here and we can insert five and if you want to remove an element from the middle we can simply remove it from the back of n1 all right so we can see a few examples here this is another case that we have to handle that when the total number of elements are odd then in this case the element which comes in the middle will be in the side of n1 or the deck one similarly while popping we should be popping if the total number of elements are even then we should be popping the element from the end of deck 1. now things will become more clear when we start coding this approach so we can jump to the code so while writing the code if there is something that i have to explain i will come back to that first of all we are creating two decks of type int d1 and d2 then two variables integer variables for size n1 and n2 now in the constructor i'm going to initialize this the size of first deck n1 as zero the size of second deck n2 as zero now when we are pushing at the front this is the first operation push front so what we can do is what we have to do is we have to simply push into the first deck and then we will see if there's a disbalance in the sizes so first of all we are simply going to push into d1 push front the element and then if n1 is equal to n2 if both of these the both of the size of both of these decks are equal then we are simply going to push into the first deck because we are giving it the priority otherwise what could be the other case could be when the size of n1 is already greater than n2 so in that case we have to push one element into n2 so as to balance the size one element into deck two so as to balance the size now for that what we can do is so let me draw that configuration and explain what we are saying is this is the deck one this is the deck two and one element two elements are here and there's no element here and there's only one element here all right so this is the configuration that we are going to tackle now there comes another element three and we have to insert this element now as we have to insert this element at the front we will have to insert it into the deck one so we will have to insert it here so you will be inserted here but then there is a disbalance in the size so in order to balance that what we can do is we can simply remove the element two from the back of the tech one and insert that element two into the front of deck two this will not disturb the uh configuration so we are so which element did we move i think two and one here so this will balance the size that's what we are going to do here otherwise simply push back into d2 push front into d2 d1 dot back and remove from d1 pop back and we have to increase the size of the second deck so coming to the push middle in this also if sizes are same n1 is equal to n2 then what we have to do is so these sizes are same we can simply insert the coming element let us take this element as 5 into deck 1 so we can insert it here but in case the size of n1 is greater than the size of n2 so the configuration is 3 1 5 2 and 1 and as it is given here that whenever such an element comes so that should be inserted at the side of n1 so for that what we have to do is we have to shift this 5 to deck 2 and then insert the coming element at this position so let us say the coming element is 6. so we have to remove 5 from here and put six here and then shift five to the deck two okay now we can code the same if the size are same then we don't have any problem we can simply push at the back of deck 1 and n1 plus otherwise d2 dot push front one element from d1 dot back and d1 dot pop back now we can insert this element so we can insert it into d1 dot push back this value and n2 plus because eventually the size of deck 2 is increased next operation is the pushback operation now in the push back operation we have to push from the back and that means we have to push at the back of the at the back of tag two so if n2 is smaller than n1 then we don't have any problem we can simply push at the back of d2 so d2.pushback this value and if the size is smaller then we don't have to make any changes simply increment n2 otherwise if the sizes are same then in this case we have to remove one element from the front of deck 2. so let me draw that as well this is deck 1 this is deck 2. one two three and four now we want to insert an element at the back we can insert it from the back here but now the size of n2 is greater than n1 which we cannot allow we can only allow n1 equal to n2 or n1 greater than n2 but here n2 is greater than n1 so in this case was in this case what we have to do in order to balance sizes we have to remove the front element from the deck 2 and push it at the back of deck 1 and then change the sizes so now n1 and n2 are balanced this is equal to 3 this is equal to 2 which is the balanced condition we have already inserted now what we have to do is we will have to push into d1 from the back so push back d2 dot front and d2 dot pop front n1 plus because eventually the size of n1 is incremented now coming to the pop operations pop front if n1 is equal to 0 as well as n2 is equal to 0. what does it mean it means that both of the decks are empty and we have to return 0 i think minus 1 yeah you have to written minus 1 in this case otherwise the answer will be the front element that is d1 dot front and we have to pop it so d1 dot pop front and minus and 1 minus now if n1 is smaller than n2 now this is the this position this configuration is not allowed because we have already discussed that n1 could be greater than or equal to n2 so we have to balance it now in order to balance it we have to transfer one element from that 2 to deck 1. so d1 dot push back d2 dot front and d2 dot pop front and two minus and n one plus and then return the answer now we are popping from the middle as we already discussed that whenever we are popping from the middle we should be popping from the back of n1 now the base condition going to remain same that is if both of them are empty then written -1 -1 -1 otherwise answer is equal to d1.back and d1 dot pop back now this could also disturb the equilibrium between n1 and n2 so if n1 becomes smaller than n2 then we have to again balance them so in order to balance them we have to insert one element from the front of d2 to the back of d1 push back all right d2 dot pop front and two minus and n one plus and then return answer each of these operations are constant time operations as you can read about decks here all of these functions the push front the push back front and back all these are constant time operations now coming to the last operation that is pop back again if n1 is equal to 0 and n2 is equal to 0 written -1 in this case we have to take the element from the back so answer will be equal to d2 dot back and d2 dot pop back and two minus if now we have removed one element from the back of deck two so let us say this was the configuration and we are removing the back element that is 5 so this is removed now again there is a disturbance in the equilibrium because n1 is equal to 3 and 2 is equal to 1 the difference between them is 2 which is greater than 1 so now we have to again make changes so that we can attain back our equilibrium so we have to remove one element from the back of deck 1 so we can remove 3 and we can insert 3 at the front of deck 2 instead of 3 here so if n1 if n2 plus 1 is smaller than n1 then d2 dot push front d1 dot back and d1 dot pop back n1 minus n2 plus and return answer now there's one more thing that we have to handle in the pop back operation so let's say when we are popping the next element 4 so this will be the configuration again this is not disturbing the equilibrium because n1 is equal to 2n and 2 is equal to 1 so the difference between them is 1. so it is not disturbing the equilibrium so we are again popping back another element from the back so it will remove 3. now it is disturbing the equilibrium because now n2 becomes 0 and the difference becomes 2 so we have to remove an element from here and we have to insert it here now again popping back we will be popping this and it is not disturbing the equilibrium n1 is equal to 1 and n 2 is equal to 0 so the difference is 1 but now when we are going for the pop back operation as we have one element in our entire structure so this is our entire structure the combination of these two and when we are removing one element from the back we are always taking it from deck 2 but there is no element in deck 2. so we have to handle this case because in the entire structure we have one element that we can remove so that we can handle if n 2 is equal to 0 if the second deck is empty and there's some element and there can only be one element in the first deck so our answer will be equal to d1 dot back or we can take it as d1 up front as well and d1 dot pop back n1 minus and return answer let us try to run this i think it is giving correct answer let us try to run this on okay there is only one test case let us submit this now and it got accepted so for n elements and operations it is going to take big o of n time and for each operation it is a constant time operation and we are using big o of an extra space here for n elements so this is it for the solution if you like the video please subscribe to the channel thank you
Design Front Middle Back Queue
patients-with-a-condition
Design a queue that supports `push` and `pop` operations in the front, middle, and back. Implement the `FrontMiddleBack` class: * `FrontMiddleBack()` Initializes the queue. * `void pushFront(int val)` Adds `val` to the **front** of the queue. * `void pushMiddle(int val)` Adds `val` to the **middle** of the queue. * `void pushBack(int val)` Adds `val` to the **back** of the queue. * `int popFront()` Removes the **front** element of the queue and returns it. If the queue is empty, return `-1`. * `int popMiddle()` Removes the **middle** element of the queue and returns it. If the queue is empty, return `-1`. * `int popBack()` Removes the **back** element of the queue and returns it. If the queue is empty, return `-1`. **Notice** that when there are **two** middle position choices, the operation is performed on the **frontmost** middle position choice. For example: * Pushing `6` into the middle of `[1, 2, 3, 4, 5]` results in `[1, 2, 6, 3, 4, 5]`. * Popping the middle from `[1, 2, 3, 4, 5, 6]` returns `3` and results in `[1, 2, 4, 5, 6]`. **Example 1:** **Input:** \[ "FrontMiddleBackQueue ", "pushFront ", "pushBack ", "pushMiddle ", "pushMiddle ", "popFront ", "popMiddle ", "popMiddle ", "popBack ", "popFront "\] \[\[\], \[1\], \[2\], \[3\], \[4\], \[\], \[\], \[\], \[\], \[\]\] **Output:** \[null, null, null, null, null, 1, 3, 4, 2, -1\] **Explanation:** FrontMiddleBackQueue q = new FrontMiddleBackQueue(); q.pushFront(1); // \[1\] q.pushBack(2); // \[1, 2\] q.pushMiddle(3); // \[1, 3, 2\] q.pushMiddle(4); // \[1, 4, 3, 2\] q.popFront(); // return 1 -> \[4, 3, 2\] q.popMiddle(); // return 3 -> \[4, 2\] q.popMiddle(); // return 4 -> \[2\] q.popBack(); // return 2 -> \[\] q.popFront(); // return -1 -> \[\] (The queue is empty) **Constraints:** * `1 <= val <= 109` * At most `1000` calls will be made to `pushFront`, `pushMiddle`, `pushBack`, `popFront`, `popMiddle`, and `popBack`.
null
Database
Easy
null
1,007
welcome to october's leco challenge today's problem is minimum domino rotations for equal row in a row of dominoes a and b represent the top and bottom halves of the ith domino we may rotate the ice dominoes so that a i and bi swap values we turn the minimum number of rotations so that all the values in a are the same or all the values in b are the same either the top row are all the same number or the bottom row are the same number so there's a big temptation here to start thinking recursively how can we swap these values how can we find all the you know do some backtracking and get the base condition where all the values are gonna be the same but i would suggest you don't go that route rather think about what conditions need to be met for our top row or bottom row to all equal the same value so forget recursion just think about this straightforwardly well if we were able to swap values and all the values would be the same on the top row of the bottom row we could look at the very first item on both a and b and check our values here it's two and five what we should do first is make sure that this is even possible we can take our value 2 and check to see if 2 exists on every i index between a and b so here with 2 we can see 2 is in index 1 on b it's in index 2 on a index 3 on b and 2 on a so that means that we could swap values and get all the values to be 2 on either the top row the bottom row if for instance for 5 we can see 5 does not exist in any of these indexes but even if it didn't exist on 1 then we wouldn't be able to swap index values to get all the rows to be that's value five right so that's the first thing we'll do we'll go through our a and b and check to see if all the values between the top row and the value on the bottom row exist in between a and b so is this even possible all right so the first thing we'll do is initialize our n that's going to be the length of a or b doesn't matter because they're equal to one other and i suppose we can just say if not a return negative 1 for an edge case so let me count this out so first is this even possible well to do that let's take our values 1 and 2 which will be value on the top row and the value on the bottom row and the very first item so this would be a zero and this would be b zero so if this was possible either v1 or v2 should be on every index value between these indexes so for i in range of we can start with 1 since we already took the first value to n is v1 in either let me make a tuple a i or bi and all of this should be true like this is going to be true for all these if v1 is the value that we're indeed checking for so what i'll do is make this a list comprehension i'll make this a list and if all these are true then it's that v1 value that we're looking for then we can go through also and check the bottom value and check v2 same thing um so here i can call this let's say hmm and say it's on the top value or the bottom value so if both of these aren't true then we could return to false or rather we return negative one because this isn't possible otherwise we have indicated one of these two should be true right now it's possible both of these are true but if that was the case then that actually means that it's an equal number of values for two and five between these two rows so the minimum number of rotations would be the same if they were both true then they're like equivalent so the answer would turn out to be the same so we can keep that in mind and we'll say all right here we'll check which value should we check to see and once we check that all we need to do is go through the top row and the bottom row and see how many of those are not that value so here we're already chosen two we know that two is going to be the value that we want to make equivalent for the top row we can see that there's two values that are not two and we know the two is on the opposite side right so we can just count these up we can say well one isn't equal to two but we know it's on the other side so rotate that and four isn't equal to two but we know it's on the other side to rotate that so that's a value of two there's going to be two rotations to get all twos on the top row well at the bottom row well we can see that there's three five six and three that are not two so that would take three rotations so between that the minimum number of rotations would be two so that would be our answer okay so if top value we're going to take v1 check cv one and we will um i apologize for the noise uh initialize an output like this so if top value what are we going to do all we need to do is check to see which values on both a and b are not equal to v1 right okay so for i in range of n if this value for a of i is not equal to v1 then we'll just output a 1 and we'll get the sum of that and this would be the min number of rotations for the top row and same way we'll get do it for the bottom row we can just do for b right here and between these the minimum between these is going to be our output all right so i realize that's a handful but hopefully you're getting it now else if the bottom value we are going to uh check for v2 not v1 2 and v2 finally once we're finished there we just return our output okay so let's make sure this works this should return two and it does let's submit that and accepted all right so this was a straightforward answer right i realize it's all over the place we could simplify with some other methods definitely optimize is this optimal well it's of n but it's definitely not the optimal solution but it does work i don't think i'm going to go too much more into this than that because it's pretty straightforward so thanks for watching my channel and remember do not trust me i know nothing
Minimum Domino Rotations For Equal Row
numbers-with-same-consecutive-differences
In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the `ith` domino, so that `tops[i]` and `bottoms[i]` swap values. Return the minimum number of rotations so that all the values in `tops` are the same, or all the values in `bottoms` are the same. If it cannot be done, return `-1`. **Example 1:** **Input:** tops = \[2,1,2,4,2,2\], bottoms = \[5,2,6,2,3,2\] **Output:** 2 **Explanation:** The first figure represents the dominoes as given by tops and bottoms: before we do any rotations. If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure. **Example 2:** **Input:** tops = \[3,5,1,2,3\], bottoms = \[3,6,3,3,4\] **Output:** -1 **Explanation:** In this case, it is not possible to rotate the dominoes to make one row of values equal. **Constraints:** * `2 <= tops.length <= 2 * 104` * `bottoms.length == tops.length` * `1 <= tops[i], bottoms[i] <= 6`
null
Backtracking,Breadth-First Search
Medium
null
110
hello and welcome back to app for you in this particular video we are going to discuss a new problem from balanced binary basically from trees so before we proceed with the problem let us understand what is actually a balanced binary tree so the definition that is given here is clearly states that uh given a binary tree we have to determine a height whether a tree is height balanced or not now what do we mean by that so a height balanced tree is nothing but a binary tree in which the left and the right subtree of every node differ in height by not more than one so in simple words a height balanced tree or a balanced binary tree is that particular tree for which you know the height of the left sub tree and the right sub tree the difference or the absolute difference of the left subtree height and the right subtree height okay is always less than or equal to one it will never exceed one right in the point so for every node so please note this so basically a balanced binary tree are those trees for which in whenever you consider any node you will find out that the height of the left subtree of that node and the right subtree of that node you just compute them and find the difference between the height of the left sub tree and the right subtree of that node you will find out that the difference has never exceeded one right so if the difference throughout the tree never exceeds one then you'll find out that okay your tree is basically a balanced binary tree so the thing that is given in the example that is given here is you can just refer it basically this is the tree that is given if you consider this node the left subtree height is nothing but 1 the right subtree height is nothing but 2 and you find out the difference is 1 it's fine now if you consider this sub tree you'll find if you consider this node the height of its left sub tree is 1 the height of its right sub 3 is 1 the difference is nothing but 0 and is less than equal to 1 so true so you will find out for every node if you compute this leaf node also if you compute this leaf nodes their left and right subtree are null and their absolute difference is obviously less than or equal to one so they are automatically a balanced binary search tree right now if you consider the second example this particular example you will find out that from the first node itself if i consider this node itself the height of the left subtree is nothing but one two three the height of the right subtree is nothing but one the absolute difference between the left height and the right height or the absolute difference between the left subtree and the right subtree up for this particular node is nothing but three minus one which is equal to two and this exceeds one right this is greater than equal to one so this is not a balanced binary search tree right if you detect at least if you detect even a single circumstance where you found out that the height of the left subtree and the right subtree difference is exceeding one okay it might be in this particular node itself or even if you find that okay somewhere here that particular rule is being violated somewhere suppose any point it can get violated so if it gets violated that is the condition is the absolute difference between the left height and the right height should be less than equal to one if this condition gets violated at any point inside the subtree then you will say conclude immediately that balance binary search tree is not possible so this is not a binary search tree right now the thing is how do we approach this particular problem so prerequisite for this particular video will be please watch my video on finding the height of the subtree so height of the binary search tree sorry not binary search tree height of the binary tree right so please refer my the video that i have created on finding the height of binary because for this particular problem the algorithm that i'm going to use is exactly same as finding the height of the binary tree so i will first of all find the writer code for finding the height of the binary tree and then i will explain by making a slight changes how this particular problem can be solved so let me just quickly write the problem for finding the height of the binary tree so i hope you have watched my video on that topic finding the height of binary so that particular topic i will not be explaining much in detail in this video okay i'll just give you an overview i'll be giving more intuition on how to solve this particular problem anyway so this is the function is balanced that will check whether my tree is balanced or not the root node that i have received here so what will i do first thing so remember my algorithm says that first of all write the code for finding height of binary tree how do we find the height of binary so that is the code that i'm going to write so first of all what i'm going to do is i'll check that if my root equal to null so since this particular function is balanced is going to check whether my tree is balanced or not what if it receives a root node so there should be a base condition what it what if it receives an if it receives a null that is if it does if the tree is empty what if the tree is empty so if the tree is empty it clearly indicates that definitely the tree will be a balanced okay so we will return true so if the tree is empty we will return true else we will think about checking whether the tree is balanced or not right so else we will just call the function check or better write height okay because i said you that i'm going to write the function for computing the height of the binary tree so integer h equal to height and i'm going to pass the root node so you remember this particular function what will it do height root this will be a call on the function height and once this function has successfully executed it will return the height of the binary tree that is what i have just written here so for that particular reason i am going to write the function integer type function height and what it is going to receive tree node star root right so i hope you are familiar with this problem how to find the height of the binary so let me just write the code so the code for finding the height of the binary tree says that you will first of all check that if root equal to null what do we return 0 no doubt with this otherwise what do we do is basically we compute the height of the left sub tree so integer lh is equal to nothing but compute the height of the left sub tree that is root left and also compute the height of the right sub tree that is height root right so compute the height of the left sub tree compute the height of the right subtree and what we used to return one plus maximum of the left height comma the right height right so i hope you are comfortable with this particular problem of finding the height of binary tree so far what did i write i just wrote the function of computing the height of the binary tree so no doubt with this right so now i want to actually do i just want to actually find out whether this particular tree is you know balanced binary search balance binary or not how do we check that whether it is a branch binary or not as i said you the condition was that for every possible subtree right for every possible subtree that you are considering the absolute difference between the left height of the left subtree hl and height of the right subtree should be less than equal to one so for this particular reason what will i do is whenever the whenever i find compute the height of left sub tree and right subtree whenever i will compute the height of left subtree and height of right sub tree i will keep track of the maximum difference observed please keep in mind i will keep track of the maximum difference of the left height and the right height observed whichever difference is maximum i will be just keeping track of that maximum value i hope you're getting the point so what is the concept is throughout the execution of this particular problem i will be keeping track of you know the difference between the left height and the right height of absolute difference of every possible stat from every possible node and i'll just update my maximum value at the end i will check whether my maximum value is greater than equal to greater than one or not so if the maximum difference is found to be greater than one it clearly indicates that there was at least one instance somewhere in the mid middle or somewhere in the inside this tree where the difference between the left subtree and right subtree had exceeded one and we know that once this condition becomes true we will immediately conclude that my tree is no more balanced binary okay so let's keep things simple the concept is keep track of the maximum value of this absolute difference between the left height and the right height so where am i calculating the left height and right height so this is my left height this is my right height right so i should now calculate the difference okay and update my difference mx equal to maximum value of the difference of you know absolute difference of left height minus right height comma mx so mx is what let us suppose initially mx is a very small value mx is equal to integer mean okay so this variable mx will keep track of the maximum value of the difference maximum absolute difference absorbed so you can just see this particular line here we'll just every time check and update the mx to the maximum of the mx value or the absolute difference whichever is maximum will get updated here getting the point that's it so you can just see that how this function is actually helping me to solve my particular problem this particular problem is basically finding the height of the subtree height of the tree sorry height of the binary tree this problem is basically finding out the height of the binary tree and this line here is just using this particular function to do it to meet its purpose right how let us see now you know when the problem will be successfully come executed okay when the program will be successfully executed when this function will be successfully executed okay what will it return it will return the height of the tree so the height of the tree will be returned in the variable h but i don't have to do anything with the variable edge sorry this was not my this was not of my interest was just to run this particular program of height wherein i will just be using this particular line to keep track of the maximum value of the absolute difference so my concern is about mh so what will i do i will say since mh is a global variable i can say that if mh is basically less than or equal to 1 which means the difference observed maximum value of image that you observed so far after completely executing the tree and after completely going through all possible sub trees is less than or equal to one you will return what true return true means your tree is definitely a balanced binary such tree right no doubt with that else what will you return else we will return false you know why because if your difference if your maximum value of this mh which was keeping track of the absolute difference has exceeded once has exceeded one which indicates that definitely there was a one circumstance where the difference between the left subtree and the right subject exceeded one that is why amh has exceeded one isn't it so if it exceeds one will return false which means it is not a balanced binary search tree sorry not a balanced binary tree okay please uh consider it to be a balanced binary i'm just saying it balance binary search tree i don't know why but it is a battery spinal tree so if the difference exceeds once we will consider it to be false right that is it is not a balanced military oh that's it so let us uh run the code i hope you are not doing any silly mistakes mx okay mx is not declared so integer mx actually right sorry for that all right if mh less than equal to one what is the issue all right integer edges if mh okay ymh it is mx actually sorry for that again semicolon missing all right the test case has passed and you can definitely see that the problem has also successfully executed right so and you can see that it is basically run time is 80 millisecond and it is faster than 90.9 percent of submissions 90.9 percent of submissions 90.9 percent of submissions anyway it was very good approach to solve this particular problem you know using recursion and while finding the height of the binary now in case you are interested to see the working so i'll just continue the video rather than completing it here i will show you how the problem is actually working right so if you're interested you may continue watching so let us see how the problem has actually worked so for that explaining that what will i do is basically i'll consider an example so let me take an example so suppose so i had used an example here yeah so this is the tree that i'll be using to explain you the concept so let me just increase the size of the screen now i wonder if this is a full screen anyway so let us continue so remember we have a tree uh 75 okay we have a 375 any node suppose we have 100 we have here 49 values does not matter because here we are just finding the height 87 8 11 50 63 100 and obviously this is the left subtree 26. now see initially what will happen is each balanced will receive the root node when each balance function receives the root node we know that root is equal to null return true but obviously the root is not null which means we have something in the tree so definitely we will start doing what the else part here says that call the function height which means compute the height of this tree so we are interested in computing the height of this tree right because the height function is called once the height function is called we are basically interested in finding the height of this subject now how will it work so first of all it will check that whether root is null definitely root is not known so if it is not null it will just keep on calling root left you see height root left so what will be done so initially this was my root node right so it will call root left which means it will focus on this left subtree let me write like this so it will focus on this subtree where this is the root now if this is the root again it will call what root left because this is a recursion so again it will be doing a call on this subtree now this is the root if this is the root then what will it do it will call a recursive call on the left sub tree which is 63 and again this is the root now so it will do a recursive call on the left subtree but here the left subtree is nothing but null so what will happen is here from the left side valid what it will return what will it receive from left side you know that if the value of root is equal to null the integer lh equal to root left so root is this its left is what null so we know that if it is null it will return zero so which means the value of lh if you are standing at this node the value of lh that you received is zero the value of rs that you will receive is zero because i write subtree is also null and remember we have already declared mx to be very small value extremely small value mx equal to minus supposedly large value negative of a very large value so now right now my mx will be updated to what the absolute difference of these two so 0 and 0 is 0 and mh is very negative so which is bigger 0 is bigger so this will be updated to 0 done and it will return what one plus the maximum height of the left sub tree and the right subtree so left is zero right is zero one plus zero is one so one is returned so right now i have i'm back to this node so i am standing at this node this is my root node and what is the height of the left sub tree right now it's received as one so let me just drop these things so remember the height of this left subtree it has received is one so after it has received the height of the left subtree we know that again it computes the height of the right sub tree root right so root write again i will be this particular function will be called now this node will be considered this is the root node right now 100 so it's left is zero right is zero so lh will be zero rh will be zero the maximum of zero minus zero comma zero is again zero only so no change is observed here now if you return what it will return one is the height one plus maximum so one plus maximum of the cycle zero one plus zero is one right so one was returned now you are at this node so it has received from left node one from right node it has received one so lhcc one rh is one for this particular node lh is one rh is one mx is equal to maximum of the absolute difference of left height and right height left height is one right height is one absolute difference is zero maximum value right now is zero comma zero maximum will be zero only it remains zero and it will simply return what one plus the maximum of the heights so one plus maximum of one and one is one so it will return two so i hope you are following the points so what does it say it says that it will return what this node will return to which means the height of the left sub tree of hundred now right now 100 is the root node right the height of the left subtree of this hundred is two now basically it will compute the right side because the left height is already computed now we will compute the right height so that is the height of the right sub tree so for that this particular subtree there will be a recursive fall again this eighth note the root eight when root will be pointing to eight this will be doing a recursive for another node 26 again 26 will be doing a recursive call but here you will find out the left lh is 0 and null rh is null so lh will be equal to 0 rh will be equal to 0 maximum of this is zero only absolute difference will be zero only and absolute difference and mx value will be zero only so no updates instead it will just return the height is one plus maximum of this is nothing but zero so one will be return which means that this particular node eight has received a value from the left sub tree which is nothing but one right now it received one so the left height now if you are considering this node a right now i am standing on the node eight the value i received from the left side was one which means my left height is what one so what is the value i received from left height is one right height will be what zero because you see its right height is null its right child is null so if right side is null which means what will be the value return zero so rh is zero so what is the absolute difference of lh and rh one so one comma mx value right now is zero so one comma zero what is the maximum value one which means right now i observed a maximum difference of one so i updated this mx to one where did i observe in this particular node isn't it so right now again i this will be returning what the height of the tree so height of the right subtree will be what one is maximum of left and right is one plus one will be two so if you consider the node hundred i am back into node hundred so node hundred is considered to be the root node right now from the left i found two from the right i found two which means the height of the left sub tree for this particular node the height of left subtree is two right subtree is true difference will be what zero comma maximum zero comma one maximum only one only so one will be remaining here no updates initiate what will be returned one plus maximum of left hand side so one plus maximum of two and two is two so one plus two is equal to three will be return this is nothing but the height of the left subtree i hope you're following the points because this problem is nothing but finding the height of the binary search tree so i found out the height of the left subtree for this particular node because i'm back to this node i'm standing here if i'm standing here from the left sub tree i found out the height to be 3 now this will be doing a recursive call on the right subtree because the left subtree height i have already computed because i have received a value from left side after you receive the value from left side now you will just call the function on right so on the right side what did you call so remember from left side you got three right side when you do the call root is on 49 this log into a recursive call on the left part that is 11 this will log into a recursive call but again you will find null left null right so again no updates here because the difference will be zero and one maximum will one only this will just return one so height of the left subtree of this node is one again for this right node again there will be a recursive fall on this node and this node again left is null right is null so again this will be returning one so if you consider this node because i'm back on this node the difference between the left hand right is zero one minus one is zero and obviously zero is less than one so no updates will be taken place what will it return it will return two so right height will be written will be two right now i'm on this note from left side i receive 3 from right side i receive 2 the maximum value of 3 and 2 is what uh absolute difference of lh and rx will be 1 so 1 comma mx that is 1 maximum will be 1 only one only is keeping here one only is kept here and you can just find out that what will be returned that is one plus maximum of these two so maximum of left sub tree and right separator is nothing but three so one plus three nothing but four this will return four and four is nothing but the height of this subtree one you know four is nothing but the height of the subtree right one two three and four so that's it so you can see the height of the subtree will be returned and stored in h but i have nothing to do with it because i just wanted to keep track of the maximum difference absorbed and maximum difference is nothing but one in my case and again i will be checking that if mx is less than equal to one then we return true that is it is a balanced minor tree otherwise not a balanced binary and that is what did we observed and the problem has successfully been executed that's all from this side i hope this video was helpful in case of any doubt please feel free to put it out in the comment section and just like share and subscribe and one more thing this particular problem was also available on geek for geeks you can see i actually wrote the same code on geek focus also and this logic actually due to some issues was not running in this particular platform however the logic is exactly same the same code i have used for on lead code platform also here it has successfully executed and here i don't know why it is giving some issues so anyways just for your information so you can see just now we showed that this tree is basically a valid one so it should return one my code should return one but i don't know why this platform in this platform my code is turning zero anyway i hope this video was helpful so please like share and subscribe thank you
Balanced Binary Tree
balanced-binary-tree
Given a binary tree, determine if it is **height-balanced**. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** true **Example 2:** **Input:** root = \[1,2,2,3,3,null,null,4,4\] **Output:** false **Example 3:** **Input:** root = \[\] **Output:** true **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-104 <= Node.val <= 104`
null
Tree,Depth-First Search,Binary Tree
Easy
104
201
Hello everyone, we continue with the resolution of lit code problems This is the video of the problem 201 bitwise End of numbers Range that we can translate as bitwise end of a range of numbers problem classified as medium already asking for your like if you like This type of video if you like the series and consider following the channel to keep up to date with the latest news, it's a lot of hassle, let's move on to the approach and implementation of the personal problem, what does the problem of two numbers say, left right, which is the smallest value and the biggest thing is to return the bitwise end of all the numbers in this range, including so here, for example, it gives left 5 or right 7, we're going to do five end six, it's going to give a result and it's going to do this result end S, right? the end bit by bit and at the end This here will give four, it is important to note that this range goes from 0 to 2 to the power of 31 - 1, that is, as in the TR example, here it 31 - 1, that is, as in the TR example, here it 31 - 1, that is, as in the TR example, here it gives a very large number, right in the house, I think 2 billion and 100 million is no point in trying to do this Hand bit by bit, number by number, as we will see now here in the very personal approach, although it is tempting to do the end bit by bit, right, for each of the numbers we understand that with 2 billion, right, for us to work on this, it won't work, so the approach here is as follows, let 's just understand some details here about the 's just understand some details here about the 's just understand some details here about the binary system, right, I brought here numbers from zer to 9 with their binary representation hey, notice that each from the least significant bit to the most significant, the values ​​that these guys significant, the values ​​that these guys significant, the values ​​that these guys represent are powers of two, right, so here is column 2 A z0 which is volume one column from two to 1 which is volume two column 2 A2 which I o volume in the column of 2 The TR which is eight and so on, right here we are dealing with 30 bits of numbers up to 30 bits and also notice the following, right here in the column that represents one, the numbers are interspersed between zero and one of one in a row, right, so the bit, the first bit here from zero is zero, the first bit from one is one, then 0, a quanta here in the column of 2is to one, which is worth two, these numbers will be interleaved every two of two in two lines let's say like this and in column two what is four these numbers are interspersed every four So we will use this as important information to solve the problem another question we have here is it asks to do the end bit by bit between all the numbers in the range when a is doing the end bit by bit let's say here, one by one this here this end bit by bit Oops It will result in one if we get this result here do the end bit by bit of another one this thing It will result in one so as long as there is one this It will result in one But if we have a zero here in the middle of the way we will get this one here which was the result it will do a bitwise end with zero will give zero and from then on, no matter how many ones we have, the result of these successive operations here will be zero, so the question of the problem is simply man, I gave you any interval, right, all bits in a given column of the numbers contained in this range are one so here for example Puts dude has zero and there is one I already know that here it will give zero let me get another interval here so we can have a positive example let's say it gave here for us the range between 4 and 7 so he's asking like man is there any column here or which columns in which columns are all the numbers here in this range equal to one Oops here we already know that there is zero here we already know that there is a zero here is a column that only has ones and ones, right and here there is a column that has only zeros so the result of this here will end up being 0 1 0 which by chance in decimal this represents the number four so with that said folks as What is the approach to this problem? We first need to know the size of the interval, sorry, first we need to know what the size of the interval is. So, let's say here our example between 4 and 7. What is the size of this interval? here is 7 - 4 which size of this interval? here is 7 - 4 which size of this interval? here is 7 - 4 which gives 3 + 1 So the first information gives 3 + 1 So the first information gives 3 + 1 So the first information we need to obtain is the size of the interval So I'm going to call T the size here, right? It's equal to left minus WR plus 1 letter, it's not pretty but I believe it Here goes give the size range Is this right here, we have the range of four numbers 7 - 4 3 plus range of four numbers 7 - 4 3 plus range of four numbers 7 - 4 3 plus 1 It will be 4 and the second the first question since this is the first question, right the second question we can now ask is If the number on the left between the number on the right, what is the result of this, right? Because we know if there is any zero here in any column, join, this result is already zero, so for example, end 7, right, here in this bit is the zero bit. and bit 1 we already know that it gives zero here z0 and 1 will give zero here it is one and 1 so here's the thing, I'm not going to say that this is one but I'm going to say it like this man this guy is a candidate to be one and here zero and zero I already know it's zero So guys, what's going to make this candidate confirmed or discarded, we need to know if the difference between the quro and the seven or the number of lines, right? 4ro and 7ete, that is, this T here that we have already determined, we will need to compare and see if this guy is bigger than the size of the interval that these numbers are interspersed with, so here in this case is if in this column the numbers are interspersed every four, right, and my interval is less than or equal to 4, I know that this guy has no risk of going from one to zero and back to one, let me give you an example here where this could happen. imagine if we were looking here at the interval between two and seven then I would suddenly be deluded here, right? great Actually, I need to say that this guy is a candidate and then I need to check, wait, and the difference between these guys is less than or equal to the size in the interval in which these numbers are interspersed, which here in the case of this column is two put, isn't it? So this here tells me that these guys were one, they went to zero and then went back to one. So this candidate here is not a valid candidate, basically this is the reasoning we are going to do to solve the personal problem, let's go here to our implementation as per Habit I bring here a little test code to check if Our answer is correct, the first part is easy, right? We said that t was the number on the right minus the number on the left plus one and we also did a partial calculation here of the number on the left and bit by bit with the number on the right, now comes the slightly trickier part, firstly we want to generate all powers of two from 1 to 2 to 30, right? So here we are using this shift left which it is a bitwise operation n times for n eh in this Range here that goes from zero to 30 eh and then guys this here basically represents each of those columns that we saw in the approach and I just want to consider the columns eh with two that have two conditions, right? The first condition here is if t is less than or equal to the number of rows in this column, and this column changes between zero and one, intersperses zeros and ones, right, so here our T needs to be less than or equal to the number of lines that what the column uses to interleave which by chance is also this A shift is n times okay I'm going to put a parentheses here to make it clear and also this same number here in bit by bit with our partial needs to be bigger than zero, why am I not putting it here equal to one or equal to a number because this number here will eventually be one, it will be two, it will be four, it will be eight, it will be some power of two, we just need to see if it is greater than zero to know if it's ok and at the end we get these guys who are so valid what we need to do is add them all up to return the bit-by-bit end of the guys to return the bit-by-bit end of the guys to return the bit-by-bit end of the guys in this range fine done the sum here we need to return this value, right, you can't forget it and we're going to check if everything is ok by running our test, which showed that everything is ok, right? So we're ready here to send the polit code Just remembering, right, imagine here an example where we're doing this, just checking the column of 2is The TR which is 4 is so here if when n is equal to 3 This here will give what we are talking about here man 4 is less than or equal to the number of lines that I am considering here if it is less than or equal This here will give true and that end bit by bit with my partial is also giving something greater than zero, so here it is proven that it would not be proven, right, it would be verified that in the column there of 2 The TR this guy returns The number greater than zero and then I'm saying the following, it adds up to four in my final answer, okay And then all the for all the columns that this was this the condition is true we will add adding and will generate the final result, which is what the problem is waiting for, adjust some details here before submitting, I'm going to remove these parentheses here, I don't know if it makes any difference when sending and this condition here won't stay where it is, I was thinking if it was worth it Bring it forward, I don't know, let's submit it the way it is here. Answer pasted, submitting guys, there's a problem submitted, beating 38% of people's, but submitted, beating 38% of people's, but submitted, beating 38% of people's, but these runtime problems are very low, guys, I'm not going to waste time here trying to improve this answer, not everything. Well that's it guys Problem solved submitted don't forget to leave a like if you liked the video and if you want to be part of the news don't forget to follow the channel for today, just a big hug Y
Bitwise AND of Numbers Range
bitwise-and-of-numbers-range
Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_. **Example 1:** **Input:** left = 5, right = 7 **Output:** 4 **Example 2:** **Input:** left = 0, right = 0 **Output:** 0 **Example 3:** **Input:** left = 1, right = 2147483647 **Output:** 0 **Constraints:** * `0 <= left <= right <= 231 - 1`
null
Bit Manipulation
Medium
null
1,675
hi everyone let's work today's daily challenge that is minimize deviation and array so in this question we are given an array Norms of n positive integers and we can perform two types of operations on any element of the array any number of times so if the element is even you divide it by two if the element is odd you multiply it by two so the deviation of the array is the maximum difference between any two elements in the array so what you have to do you have to return the minimum deviation that you can have after performing some number of operations so let's understand what the question is so here you are given the saree so there are two kinds of operations that you can do right so the first operation is that if you have an even number right you can divide it by two and if you have an odd number you can multiply it by two so you can do this to any a particular number any number of times right so right now if you see the deviation of this array so how can you first calculate the deviation of the array so deviation is nothing but because you have to calculate the maximum difference you can only get by taking the maximum value of the array and the minimum value of the array and subtract them right so that is the maximum difference to that so that is what deviation is so right now if you see the deviation it is 19. so now let's try to do some number of operations and you know get a minimum value that we can get so what can we do so if you say this is very large but it is even so but for even values what we can do we can divide them by two so if we divide this by 2 what we will get 10 here now if you see the deviation the maximum value is 10 only and minimum value is 1. so the deviation will become 10 minus 1 that is 9. now again you see uh if we can decrease this maximum value so decreasing the maximum value uh you need to check if it is even or not so it is even so we can decrease it so what we will get so to decrease you will divide it by 2 because it is even so you will get 5 here and 3 here now if you check the deviation what is it so if you see 5 and 1 it is 4. now you see that the maximum value is odd so can we you know reduce it further no because for odd numbers we can only multiply them uh them by two so we cannot reduce it so what we have to do we have to multi we have to do something to this minimum value so that we can you know increase it so our deviation will be lesser so if you see this is a not value so for odd value we can multiply it by the uh them by 2 so that we can increase them so we can multiply this by 2 what we will get 2 and here you will get this and now your deviation becomes 5 minus 2 that is 3. now let's see if we can do any number of operations or not so you see this is the minimum value and this is the maximum value you cannot reduce it because this is odd you can only increase odd values and you cannot decrease 2 because we can um sorry we cannot increase two why because this is even so for even values we can only decrease them right so this is the only condition we cannot change the minimum maximum value so that is our answer that is the minimum answer that we have is 3 in this case you can't do any other operation to get a minimum value then three right so that is the result for this adding so now let's uh observe a little observe some things here first thing that you observed here is for this even case that let me write it here for even values wait even values can only be decreased because we are dividing them by two and the odd values can only be increased because we are multiplying them by 2. so this is the first thing right now the third thing is we need to get a minimum and a maximum value out of this for each and every iteration so how can we do that so for that we can have a Max Heap right that is the best way that we can get a minimum or maximum value right because after performing some number of operations our values are changing right so for that we need to maintain it so we need to uh maintain the maximum value or a minimum value to get uh to get that we can only use Maxine because the other approach is to then sort it right sort uh sort this array again and try to get a maximum value so that is why we are using a Max Heap so what is a Max Heap it is just a binary tree in which the root is always greater than its children right and once you delete the root it adjusts it in such a way that the root stays the maximum right so that is what Maxi and priority queue is also the same uh just that it is a queue but the top of that queue always has a priority that is it is always maximum right so um what we will do we will create a Mac CPU now you might say that a similar thing we can do for the Min I but wait we will see why we are not creating another Heap right so we will create Maxi then the fourth observation is can we you know try to reduce the number of operations right can we radicate one of the operations here right that is either this first operation or the second operation so what we will do we will eradicate the odd operation so how can we eradicate the odd operation that is by making all the odd values inside of the array even so if you see all the odd values are so our R is four one five twenty and three so now our array will become what so now our array will become 4 2 and what are the other values 4 to 10 20 and 6. now you may ask why are we only radicating odd and why not even it is because for odd values if you multiply any odd value by 2 it is guaranteed that value will be even because you are multiplying it by 2. but for even values if you divide them by 2 there is no guarantee that the number that you get is even or odd right you might be getting an even number so that is not possible right that you eradicate the even operation because still you can do even number of operations right because for this only you can see that the array contains 20 if you divide 20 by 2 you will still be getting an even value so an even operation is still valid right so that is why we can only do this for odd because if you multiply any odd number by 2 it is guaranteed that you will get a an even number right so that is why um we are eradicating the odd operation so let's write it here eradicate the odd operation right now let's see what we will do so we will put these values inside of the priority queue and we will also here maintain a mini variable which will contain the minimum out of these values that is 2 in this case now what we will do we will be traversing inside of this priority queue and we will be performing our operation that is the even operation dividing the number by two now let's see how will we do that so now what have our um our array has become this now let's Traverse in this array right um so we will be having a priority queue right so the priority key will be containing values like this right so this was what our priority will be containing this is the first iteration right now what we will do we will take the maximum value out of this priority queue and the minimum value we had already calculated so what we will do we will take a deviation variable and inside of it we will be calculating the deviation that is maximum minus minimum so what we will get 18. then what we what will you do you will uh divide this value by 2 because it is even right and you will push it inside of the priority queue so now your priority queue will become also update the Min I here by whatever the Top Value is divided by 2 so that is a minimum of 2 and 10 so it will still be 2 in this case right okay wait now let's do the second iteration in this first iteration our priority you had would have been become 10 6 4 2 because what we are doing we are removing this top element and we are dividing this top element if it is even and again pushing it inside of the queue so now we will again click the top so our deviation will become what it will be uh 10 minus the Min I value which is 2 so 10 minus 2 is 8 right and we will again update our midnight to 10 divided by 2 that is 5 so still it will be 2. now the third iteration let's see for the third iteration what will happen we have 10 here right so right now um after this particular operation what will would have happened uh we would have removed this and we would have divided this by two and put it inside of the two so we would have now our Q will contain uh six five four two these are the values which our Q will contain again calculate the deviation it is it will still same stay the same and Min I will also still stay the same that is 2. let's perform the fourth iteration right so let's see what we will get um now our priority will be looking something like this right because take the top divided by two push it inside of the cube so we will get you will get five now uh again calculate the deviation that is 6 minus minimum value that is two so you will get four update the minimum value that is six by two that is three so minimum of 2 and 3 is still two so minimum is still two now we have to do a fifth iteration here so what we will get here now our array our priority queue will look like this okay now let's see now you see uh first let's calculate the deviation we will get 5 minus this minimum that is 3. and then again um okay don't update when I now if you see that this 5 is an odd number it is odd and this is the maximum element right if the maximum element of the priority queue becomes odd you cannot decrease it by performing any operation right because odd numbers as we saw can only be increased by multiplying by two so you cannot decrease this odd number so that means there are no other operations that you can now do right to get a minimum deviation and there is no use of still iterating inside of this priority queue because our maximum is 5 right and it will stay 5 because we cannot change the value of 5 by any means because it is odd so we will at this point we will break outside of a priority queue and we will return deviation right so that is uh all the things that you have to do so first thing we saw that even values can only be decreased and odd values can only be increased then what we said we can create a maxi right you see here that we are calculating this Min I in every uh iteration so that is why you don't need to declare a Min Heap here right so only Mac C can work for us because minai we can calculate it in each and every iteration right so we are having this Maxi and what we will do we will eradicate the odd operation because we can right so why not remove these operations because we don't need a headache of a number of operations so we have removed this operation so now we only have one operation that is take the even value and divide it by 2 so that is what we are doing we are taking on traversing inside this priority queue and we are taking the top if it is even just divided by 2 and keep calculating the deviation until the top element becomes odd so because when the top element is odd you cannot do any number of operation as is as it is odd right and odd values will only be increased so I hope now uh the process and the intuition of the question is clear now let's code it out right so first what we will do we will create our priority queue right um it will have integer as value and PQ right let's also declare our answer variable here right answer will contain the deviation right so uh it will be initially int Max and with it also let's declare our Min I variable when I will be also end of Max right now let's reverse first let's um right so what we have to do we have to Traverse in this um Vector right from stored size and I plus now what we have to do we have to see if the value inside of it is odd right we have to remove the eradicate the odd operations and as well as uh make our priority queue so we'll check if the number is odd if nums of I modulo 2 right if it is odd then what we will do nums of I will become num so 5 into 2 right and after that do what put it inside of the priority queue EQ dot push nums of I and also calculate the minimum value here that is this right and numbers of I now our priority queue is complete now what we will do we will Traverse inside this priority queue while let's reverse like this because uh the condition at which we have to you know jump out of the loop is when the top element becomes odd right not when the priority queue is empty right so let's now perform the operation so first what did we say we said uh that calculate this deviation value that is answer minimum of this answer value and the maximum value so let's take the maximum value inside of this current variable so we will say take the top out of this priority queue and remove the stock and do operations with this top element that is calculate the minimum value of this answer right that is the deviation so how will you calculate that is maximum minus minimum so maximum is what that is inside of this current and minimum value is min I so after we have calculated this we have to check right if this element if this top element if this has become odd so at that point as we said we have to jump out of the loop so what we will say we will calculate current element we will check if it is odd we will say break out of this Loop we don't need to do any more iterations otherwise you have to divide it by 2 is equal to 2 right you divide this current value by 2 and also update your mini variable with minimum of this Min and current and also push this inside of this priority queue so we will say p q dot push this current maximum value after we are done with this after we will come to this position we have to break and we have to return our deviation that is our answer right so that is all that you have to do let's quickly run it foreign okay so that is how you have to solve this question
Minimize Deviation in Array
magnetic-force-between-two-balls
You are given an array `nums` of `n` positive integers. You can perform two types of operations on any element of the array any number of times: * If the element is **even**, **divide** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].` * If the element is **odd**, **multiply** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].` The **deviation** of the array is the **maximum difference** between any two elements in the array. Return _the **minimum deviation** the array can have after performing some number of operations._ **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 1 **Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1. **Example 2:** **Input:** nums = \[4,1,5,20,3\] **Output:** 3 **Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3. **Example 3:** **Input:** nums = \[2,10,8\] **Output:** 3 **Constraints:** * `n == nums.length` * `2 <= n <= 5 * 104` * `1 <= nums[i] <= 109`
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
Array,Binary Search,Sorting
Medium
2188
1,094
Once Hello Everyone Welcome Back To My Channel Today Were Going To Solve The Problem Problems Car Pooling Early Morning Pyuda Video Please Like And Subscribe My Channel And Without Further Delay Started So In This Problem Delhi Government With Capacity To Be Given A Car With seating capacity and they still need rise it means Idli Travel in One Traction 19 Changes Traction Tolly Travels in One Direction Love You Are Ki Band Interior Ka Paste Hue Bread Trip and Beach in India There is the President of Senses and from Ascendant and Indicators The location from the giver kilometers from the location of the pick up that Sunita into this possible to pick up and drop off all passengers from given tips or for judges a little water problems I to let one to 30 tipsare given to states and cities of The individual to reduce the country and the has to investment replaces to ka one comma five that dangerous to is the number of central number officer this one is the pickup location and decided to withdraw wap.in and decided to withdraw wap.in and decided to withdraw wap.in torch light 34 passenger stupa centers where to pickup from One end is active pack and hear what we need to tell weather will be able to pick up all the senses and drop observations that possible or not and being given capacitive or pet you are so they can not have more than senses mind and senses In all possible only if any point of solid CO2 200 23 th so they want to have more we don't put snacks classification size so it's policy capacity 400 fit what are means water jams will do a minute to eliminate all this passengers car mintu is voice percentage What will cry when love you to have one more person Sahakar we will first pick and friends senses which will drop alive to president on senses with senses will drop it will rock you because they want you like me maximum number of Centers Card So Is Vipad Se Wait Dropping Carrier Means Or Dropping Passengers Cleared And Space Will Increase In If Which Smell Increase That Show What They Want This Pick Up The Passengers Ali Draupadi Malik Pickup The Family To Family Tubelight Type This Literature Available At Rate Times and the percentage 123 is the meaning of so basic tank like oo want to have so changes kind of withdraw and two drops through two passengers so this is the early problem this is the leader of track political will on 21 presence and will reduce percentage wise And Baking Dish First Recorded This Will Drop Later Let A Tear Dropping 80 Will Get Out Of The Car And Seven Days Will Drop Get Out Of The Car 520 War Will Stop This Post Exempt Working Committee Member Nau Let's Eat In I Let Me Rajesh Account tomorrow morning test source 215 ki and free jo women to kab maine aisi sport car ki wherever they are so si the pickup time and withdraw 100 pickup near into percentage sarkar to wake up B.Ed 2ND wake up B.Ed 2ND wake up B.Ed 2ND year to senses and eliminating 2% from The eliminating 2% from The eliminating 2% from The 180 It's Something Similar To Click So Packing Of Virat Passenger Car Driving With Subscribe Similar They Can Give Rating 200 Degree Passenger Car Tracking Date Passengers From The Car At 7pm Placid PM To 10 With Rope In A All The Observer Time Is Kilometers Whose Kilometers Don't Confuse Tweet Time Sleep Seena Disdain Someone Like And Neetu Pick The One Four Three Idiot In Early Times Points Hands Free Profile Will Develop A Fast And They Will Drop Passenger Shruti What We Will Do It Is Will Have some data structure in which will be adding wedding pick up likely have one should not be updating of will and in the advertisement that and willard water peer wedding 2% willard water peer wedding 2% willard water peer wedding 2% charges enter that jahangir voting will be operating 2% swarnakar placid on its operating 2% swarnakar placid on its operating 2% swarnakar placid on its axis bank Subscribe to the channel Attacking 353 This is the kilometer distance and how many percentage of that and when they are dropping in the morning Topic is seventh that and where talking to media presence in loot cases that and now they need to take them in water lake view take them and You Can See His Adopted Daughter Wife Mother Daughter Call Me To The Work Soon As Possible So Way Ki Picket Value To Switch Off Baroda Assistant Producer That Distance Royale Take Like A Temple In Question Is Clearly Mentioned Diet Absolutely Digest Vehicle Only Digest You Can You said that what we can do it will pick the water and will be difficult one and half inch that and will a can go back liquid distant from one kilometer i one kilometer away peaking and dropping f5 kilometer 16 right initially car was initially double No Sense Thus Morning Packet Vansh Chotu Passenger Running Car and Drop 15 16 Senses in Thy Work Jio 80s Days Will Go Back and Will Pick Thee Passengers 840 Kilometers from Kilometers 50% What We Cannot Go Back They Cannot Go 50% What We Cannot Go Back They Cannot Go 50% What We Cannot Go Back They Cannot Go Back Science And the point question is clearly mentioned by others on register a better not to venture out and tried so they can not go back and need two hands with me to take them in order for the first one kilometer day three kilometers to one kilometer Willard 2 % 1023 Kilometers Apart And Sea kilometer Willard 2 % 1023 Kilometers Apart And Sea kilometer Willard 2 % 1023 Kilometers Apart And Sea Passenger Train Delhi Photo Five Kilometers Which Attractions 2% When Intermediate Kilometers Which Attractions 2% When Intermediate Kilometers Which Attractions 2% When Intermediate 272 Kilometers Seven Kilometers And Subtraction Slightest Submit A Comment For Kids Navratri Concludes On This Night All The Journey To Take And Order So Come Here Motive Can Do You can support him love you can start ambassadors on these values ​​who love you can start ambassadors on these values ​​who love you can start ambassadors on these values ​​who is the distance or you can you sir meaning so that every time is the minimum value of monkeys so what is to be understood why we are taking a minute of water before death important meeting And Sorted Water Because I Can't Go Back Worry Not Go Back Thanks Me To Take Them In Water 123 Same Plate As Your Key And Appeared In The Soil On Fuel Minimum One Will Be Plus Two 60 Distant Don't Waste Time With Three Landing Tips Enters Maiden Speech Will Come When Will Toppings 2% Urj To Speech Will Come When Will Toppings 2% Urj To Speech Will Come When Will Toppings 2% Urj To Senses And Dropping And Behave The Way They Are Talking Tips Enters Sushil At Current Affair Ka Bhed 100 Out Of 100 Will Initially Be Adding To Senses With Sense And Tasty Also Come To Sudesh Gas Eliminated And Will Get Destroyed Evidence Minimum Close Distant Villages Will Be Able To Perform Any The Soul Will Vidya Veer Pocket &amp; Virat Kohli Vidya Veer Pocket &amp; Virat Kohli Vidya Veer Pocket &amp; Virat Kohli Passengers Begum Fight A Plus 3 Ki Sushil Total Pregnancy Size Earth Coming Five Buttercup Festivals 400 Way Cannot Have 5 Senses Take out the vendors on board in value this Vikram Grater Vitamin Ray Vikram Grated Ginger Fact I can return forms It's not possible to avoid all the percentage in if tune in for this approach to hear the festive 5.5.5.5 inches Subscribe Possible Five Senses at Will Give You Will Value - In 2036 That 9810 123 - C Weakness In 2036 That 9810 123 - C Weakness In 2036 That 9810 123 - C Weakness Entries And Show's Value Silent Boarding Vikram Grading's Paste Daily Problem Day In Return For This And Sudesh Poswal Approach In Which Will Be Using Thi To Time Activate Also Login This That Bigg Boss Using He and Space also 30 From Ukraine This The Number Of All The Values ​​Which Should 30 From Ukraine This The Number Of All The Values ​​Which Should 30 From Ukraine This The Number Of All The Values ​​Which Should Avoid All In One Sentence So Like It Share And Phone Number Of Tips Keep Watching The Number And Tips And Two Of Two In Will Be The Total Values ​​Which Will Govind Cheap Total Players Values ​​Which Will Govind Cheap Total Players Values ​​Which Will Govind Cheap Total Players How To Buy Government Came Into Force For The Self But Will Go On And Officials To Beat Fennel And You Can Visualize The Planet Of The Apes And Give Them Newly Created One More Approach That If Servicing Duty Approach Right Like Over In Order To Keep visiting for kids and want to have shifted to turn of events at all way can you speak that know what the same approach same just or new understanding which will be very interesting is that graph birdwing behind you come on file in this regard and 331 Commerce 760 Teg Bahadur Hai What Women Look Vivo Doing But When Will Get Va 181 Kilometer Where 2% Na Get Va 181 Kilometer Where 2% Na Get Va 181 Kilometer Where 2% Na 185 Kilometer Rebellion 2% 30 Par St Witch 185 Kilometer Rebellion 2% 30 Par St Witch 185 Kilometer Rebellion 2% 30 Par St Witch They Have Taken A Kilometer Nuvve 10383 Kilometer Text Passenger Five-Seven Kilometer Hai Joint Right Nau What Will What to do when we are one Kilometer That They Will Drop Them Subject And Minus To Meet 80 Vihar Face 3 Some Selfish Kilometer Thrill What They Are Doing Person Kilometer Hearing Los Angeles RC Who Invent 720 Subtracting 0.5% Subscribe - 2 720 Subtracting 0.5% Subscribe - 2 720 Subtracting 0.5% Subscribe - 2 Ki 1610 Model No One Will Nau Be Operating FR Viscera Traversing this point show me and they are adding more passengers during Russian painter 9 seater car targeted that capacitive screen so week month year with you for - 2 picture wedding 2% month year with you for - 2 picture wedding 2% month year with you for - 2 picture wedding 2% is necessary and clear e will reduce to Record 2% Edit Dakar Show Rest You Record 2% Edit Dakar Show Rest You Record 2% Edit Dakar Show Rest You Vestige Two's Sailors Only A Special OK VR Next 90% Must Total Capacity Name VR Next 90% Must Total Capacity Name VR Next 90% Must Total Capacity Name Type Vikram Higher Science in Primary Schools - - - Tenth Update of 90 Writing More Passenger Chilli Capacity Sovendra Capacitive Co. Return Gift Return for This Torch Real picture of light dissolve status, candidate list for the best Yadav, father testis's f-35, some such father testis's f-35, some such father testis's f-35, some such website, fuel, jp54, vikram's 2%, definitely 2%, admit card of vikram's 2%, definitely 2%, admit card of vikram's 2%, definitely 2%, admit card of hanging, improved member team, nine wickets, air chief against sirvi studio and Win Vs Rottweiler Remove And - - Tips Remove And - - Tips Remove And - - Tips Main Tujhse Bhi To And Easy To - After Vikram Main Tujhse Bhi To And Easy To - After Vikram Main Tujhse Bhi To And Easy To - After Vikram This Partnership Tomorrow Morning That Show That Self Teaspoon Talk Time What Ever Values ​​To Here Values ​​To Here Values ​​To Here Subtracting Sit Value From The Cloth That Angry Time's Paste Development License Unit For A period of time will be a photo copy and when is the you can see number of district which gives one number and tips and of pay switch of name with name is the total number of top stars phone number of talks then it can take The Shadow Of 101 Records Max Kilometer Good Wishes 1010 That's A Given To Approach And The Cockroaches Sophia The First Approach The Code Is This One So Let's See Surya Singham In Free Attack In Senior Member In The Cockroaches Oggy And The Giver The Time Jobs In Positive Subscribe To That Solid Positive This Negative Energy Surya-Putra Chingari And The Weapons One By Surya-Putra Chingari And The Weapons One By Surya-Putra Chingari And The Weapons One By One From The Left Any Point Of Time Who Voting Value Also America Testing Return Form Incident Through Appropriate Swift Code Excited Committed Jhal Effigy Second Approach You They have second approval wing instituted of wasting of their only tor to 2400 to research of side 101 Gautam etc roads 2000 talk on 27 2010 hai so din what you doing and fast key print sanctuary going to each rate and with lord in the sense w dot Pickup Location And Drop Location Adult Writing Friend Passenger Values ​​And Daniel Waver Cigarette Passenger Values ​​And Daniel Waver Cigarette Passenger Values ​​And Daniel Waver Cigarette Strips Top Player To 101 Size Judge 2805 Se Zinc Vyas Peeth Shubhchchhuk Great Kar Denge Ek Pacific Places Song That And Capacity Fame Priority Value From Across The Benefit Last Added Last Commented NGO 12322 Other wise like it when you visit for capacity for the upcoming - visit for capacity for the upcoming - visit for capacity for the upcoming - 150th comments and it will not get day zero return for this here open to the code and approach that they need admin no comment like video please like and share and subscribe my channel Senior Editor in Chief
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,851
hi uh so for this video i will discuss problem number one eight five one minimum intervals to include each carry so it is marked as hard let's see uh you are given a 2d integer array in the in intervals where intervals will contain left and right describes the ith interval stands for left starting at left and ending it right so very basic one we have 2d arrays with left and right so basically this is a interval this is an interval which start from left to end right then the size of the interval is defined as the number of integers and it contains or formally left minus right minus left plus 1 that means both are included if we have not included then it will look like this like left is not included right is not related but every element in between is included but not just this case but everything the sizes right minus left plus one simply like if i have two and four then the size will be four minus two plus one that is three that means two three four now you are also given an integer array queries is the small is the smallest interval size of the smallest interval i says that left uh greater less than equals to qe j and less than equals to greater than yeah less than equals to right i if no such interval exists then the answer is minus one redundant array containing the answer of the cubes okay so let's take this example and try to run it we'll try to understand what he wants to say okay so let's take this example so what he's trying to say is we have intervals one two four let's uh i didn't immediately agree so let's represent this on a line one to four another one is two to four another one is three two six another one is 4 so this is just like four now what do you want to do is we want to check uh smallest interval size we want size the smallest interval size which actually contains curie number so okay so let's suppose a q a number is 2 so we want only those intervals which actually contains two so one comma four contains it two comma four contains it this doesn't contains it this concept so we have only two candidates which can be our answer and we have to pick the smallest one so what will be the answer for us is the size of this is uh four this is the size of three is three so the answer for this one will be three yeah you can see that three now for the three this one will consider we'll consider this one as well and not this so that means the size of the is 4 3 that means the answer would be 3. now for the 4 we'll consider this and this all will be considered but the size of four comma four is minimum it's only one then the answer will be one for five we'll consider not consider the first one will not consider second we'll consider third but not four so we have only one option so we just can't do much but just say three plus one four is our answer so that's how we have to solve this problem now let's see how we can solve this so if you see the pattern in this problem let me copy that so if you see the pattern what we want to do is for every element for query element we want minimum size of interval which actually contains it yeah so let's discuss what we can do first thing is let's sort yeah sorry for that let's sort queries in ascending order and also sort are intervals in ascending order with the like with our first element based on our first element and then on second element what that does mean is this one is sorted let's pick another one which is not sorted okay so let's see what will happen if we sort the queries uh in ascending order they will look like 2 5 9 22. if we sort the intervals in ascending order they will look like 1 8 2 3 2 5 and 20 25 so base first based on the first element then based on the second limit you can see here like two but we've given preference to three because this one because it has smaller second element now what we can do is uh we can use a min heap we can use priority queue we can use tree set and what we can do like because we have now let's say i want i iterate over the queries and let's say i have first element as 2 now i know my intervals are also sorted so in my any of these data structures i will just add only those intervals which are relevant to my query so for two i will just add this one not to this one and i will stop from abc any of these data structure will help me to get my answer is the size of uh the minimum but these this is the set i have to consider if i have my query element is 2 now let's move forward we'll see uh why sorting will help and why this will become a sliding window kind of a problem right now sliding window and then mini heap kind of a problem now we come to five now we see uh now these many are already in our data structure okay so let's see we see like uh let's try to see if this is this became relevant now or not still not so we'll not add it but now again we check it one more step out of the relevant elements previously we had for two how many are in relevant now so 1 8 will still be relevant 2 3 is now in relevant to me why i can remove this element from my data structure because i know all the next elements after 5 will be greater than 5 right and if this element is not relevant for 5 it will not be relevant for any of any further element right similarly if any element is relevant for two right it can be relevant for five as well so we had abc we tried to add one more we had tried to add further intervals but that wouldn't help for 5 but now we are removing this b from our data structure because we know anything after 5 will not this will not help now coming to two and five yeah this will i need to keep now for five i only have two elements and my again uh again my data structure will help me to get the size of the minimum interval now come to nine now i will try to see if i can add uh the next set inside it okay so i cannot uh that wouldn't help for nine i will see if a is relevant no and it will not be relevant for nine it will not be relevant for any other element because this is sorting it sorted in ascending order 2 3 it's already gone so we will not see that in data structure not this one so our answer for this will be minus 1 so for this minus one uh for the previous one will be uh we had this one for five and answer would be this one will be five minus two plus one four two we had one abc and the answer would be the minimum one is two let's see we'll confirm the answer for 22 now we have nothing to consider but let's see if we want to add this yes we can add this so this will be in our data structure and this will be only element in our data so because we don't have anything else uh we already removed it so answer would be simpler simply for this will be 6 let's see if i've answered it 2 minus 1 4 and 6 right so answer is right two minus one four and six right so for us answer for two was two yeah for us answer for two was to correct for him as well answer for 5 was 4 right answer for 9 for us is -1 for 9 for us is -1 for 9 for us is -1 for him okay this is 90 but the answer is uh same for nine and nine because we don't have any element for nine any interval for nine both four will be minus one for 22 the answer is six yes we also get this so let's move to the implementation so let's go to implementation and let's see how we'll implement this so i'm using tmap but anything else can be used any data structure mean heap or priority queue okay and now we need to sort them first sort series and then sort the intervals so we have to sort it based on the first element and second element um yeah and then let's iterate over the intervals for each key like we did in the dry run for each query we'll try to see if we can answer it if not will the sign minus one but first of all we'll check what are the valid intervals for it and valid intervals i mean add intervals and remove intervals right and then we'll check so let's see so if my interval is less than interval length i still have intervals to be considered i am not over with all the intervals and intervals particular interval start is less than one is less than or equal to my query then i just need to put that into my also like we discussed um also like we discussed we'll use this uh data structure to get the element get the answer view what we want right now what we'll store in this right so what we can store is the size because we want the size minimum size if we keep the size as our primary element then always in min heat i will have the top element with minimum size and that will become my answer straight forward right and another thing i can keep is the right so as soon as i inserted some element as soon as i inserted the element i'm making sure uh by sorting like this will this can be also well uh important or valid for further elements but once i know uh but once i know that this particular element or any element is uh this particular well uh this particular interval is not relevant for any of the value in query any of the query value we have to answer we just not we don't need this interred at all for further elements in this element so to remove that element i will store right and to get my answer i will store the size let's see that in the hold so what i'm doing is i'm making the primary key for my map as size and then i am keeping this value is my right okay this is done the insert one for the removal part will do the same right we have to check if our map is not empty if we don't have anything in our map then what we'll remove and then simply the top element if the top element value that is the right this represents the right value of a dollar this is less than my curies element let's remove it we don't need that entry anymore right and then we'll go to the answer the order for our queries and order for the input queries is different to maintain that what we can have is we can simply have a hash map for it so let's say and just say answers and here what i do is if pq is empty like we saw for nine we don't have anything we don't we can't we have any interval for this so we'll just simply say for the query i element our answer will be minus one but else consider put what will we answer so our answer would be whatever we have on the top the key because the key is size and then okay and are originally curious as well and so now this just gonna create over it original carries we have i equals to whatever answer we have for that value whatever answer we have that for value in our answer now that will be sufficient and you can just write down let's see how it goes the compiled return integer dot compare new comparative and do we need another bracket yes we need times limit exceed y we have not incremented it so it will just keep on considering the same it doubles again and again yeah it works let's try submitting it yeah it won so yeah this is it for eight five one uh just feel free to comment any other problem you want me to explain with by whiteboard and implementation and uh yeah thank you guys
Minimum Interval to Include Each Query
maximum-number-of-events-that-can-be-attended-ii
You are given a 2D integer array `intervals`, where `intervals[i] = [lefti, righti]` describes the `ith` interval starting at `lefti` and ending at `righti` **(inclusive)**. The **size** of an interval is defined as the number of integers it contains, or more formally `righti - lefti + 1`. You are also given an integer array `queries`. The answer to the `jth` query is the **size of the smallest interval** `i` such that `lefti <= queries[j] <= righti`. If no such interval exists, the answer is `-1`. Return _an array containing the answers to the queries_. **Example 1:** **Input:** intervals = \[\[1,4\],\[2,4\],\[3,6\],\[4,4\]\], queries = \[2,3,4,5\] **Output:** \[3,3,1,4\] **Explanation:** The queries are processed as follows: - Query = 2: The interval \[2,4\] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3. - Query = 3: The interval \[2,4\] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3. - Query = 4: The interval \[4,4\] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1. - Query = 5: The interval \[3,6\] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4. **Example 2:** **Input:** intervals = \[\[2,3\],\[2,5\],\[1,8\],\[20,25\]\], queries = \[2,19,5,22\] **Output:** \[2,-1,4,6\] **Explanation:** The queries are processed as follows: - Query = 2: The interval \[2,3\] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2. - Query = 19: None of the intervals contain 19. The answer is -1. - Query = 5: The interval \[2,5\] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4. - Query = 22: The interval \[20,25\] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6. **Constraints:** * `1 <= intervals.length <= 105` * `1 <= queries.length <= 105` * `intervals[i].length == 2` * `1 <= lefti <= righti <= 107` * `1 <= queries[j] <= 107`
Sort the events by its startTime. For every event, you can either choose it and consider the next event available, or you can ignore it. You can efficiently find the next event that is available using binary search.
Array,Binary Search,Dynamic Programming
Hard
1478,2118,2164
232
Hello friends, welcome to your Day 39 of Lead Code Challenge, so let's go straight to the screen and let's start. Today's question is okay, so today's question is opposite to yesterday's, it is completely opposite. Yesterday we did it, we implemented it. Tha stack using queue, today we have to create queue using stacks. Okay, so some basic details are written in it as we have written, you implement FIFO data structure. What is FIFO stack, basically LIFO and what is queue is FIFO. This means first in first out is leafed but last in first out, so basically they have told us that you should only have two stacks, we have also given a hint to use two stacks, it is okay here, so the approach should be like yesterday. This one is basically normal, we have to implement it, inside which we will have push pop peak and MT function. Okay, so let's go straight to the screen. First, we will understand a little bit about the nature of K, we will understand the nature of the stock and then we will start implementing it, which method. If an approach can be made then first of all I have to achieve the nature of Q because I have to achieve the nature of K from whose using stack, so basically the stack looks something like this. First let us understand the nature of Q inside K like 10 20 30 40 Lets These elements are coming, so first of all we put 10, then we put 10 in the stack also. Now if I achieved the nature of Kya, oh sorry, I made a little mistake here that I made Kya and the stack opposite, then I got the opposite. No, let's make beans, I gave the data stack thing to So sorry for the mistake, I had to do something like this, so the stack is implemented in this way, that is, it is shown and Ku is shown in this way, now let us understand the nature of Ku. Pass data came 10 20 30 We have to put all this data in both the data structures. Now first of all we put 10 in A, then we put 10 in the stack also. Okay now if I take out the element then what will come out? 10 will come out from both so far. Both the beans are absolutely fine, as of now we are not facing any problem. Now I have to put 20. I put 20 in A. Now I put 20 in the stack. Now what will happen if I take it out now? I will get 10. If I take it out from the stack it is 20. If I get it then this thing will not work. Now I have to design some stacks in such a way that if I take them out first then 10 will come out and then if I take them out then 20 will come out. I have to implement something like this. I understand that we have to do something like this. So what do we do for this, basically what will we need for this also, for this we will need two stacks, so once we understand this thing also, I have to achieve the nature of two queues, so first I also create a queue. So you have a reference to know what should have happened, what is happening, okay so I make two stacks, so I made one stack like this and let's make one more stack, okay so I made these two stacks This is our queue whose nature we have to achieve, queue task and this will be our main stack and this will be our helper stack, so we make two stacks, we have given names to both of them, now we start adding elements again, what elements will we add 10 20 30 40 After putting all four elements, we will keep checking one by one and keep writing the steps. Okay, first of all, why is there 10 in main? Okay, put 10 in main also, there is no issue yet because what do we need to do right now, if main I have 10. If I have gone 10, then only 10 will go. What will happen if I pop? Basically, by popping, 10 will come out of both and only 10 should come out of both. Okay, after that came our turn of 20. Now on 20, I am mine, what is the step in this? Basically, the steps in this will be something like this, first of all I have to put all the items from the main and all the elements in the main into the helper. Okay, so before the main, let's put them into the helper. See how this step is done. I took it out from the main and put it in the helper. Okay, after that I will do D in the main stack, so main dot D But let's put it in main and then let's see, then again I have to add these three steps, so I won't have to work in any other function, so I extracted it from helper and put it in main. Now if I pop, what will happen if I pop? If I take it out from here, I will get 10. If I take it out from here, I will get 20. After taking out 10, it's okay, so I hope this part is clear to you as to how it happened, do it one more time. From 30 to 30, it came here in Q, now what will happen before 30 comes here, put all the items from the main in the helper, push it, 10 came out from the main and went to the helper, 20 came out from the main and where? It went into our helper. It was something like this. Okay, main dot add element. 30. Perfect. After adding it to the main, what do I have to do now? Now basically, where do I have to remove all the elements from the helper and put them in my main? If you want to put it in the main then now let's put it in the helper, then take out some more from the helper, put some more in the main, put 20, after that then what will come out, 10 will come out and where will it go, it will go in my main, okay, so it is, this thing is okay now. Out of the number of ways to remove 10 from here also, 20 should come out here, 30 should come out, then 30 will come out. Okay, so I hope it is clear to you that in what way we can manipulate its function a little. The work will be done and then in the pop function we will have to get the pop done directly from the main and in the peak function also we will have to get the pop done from the main. Okay, so our approach has been made in this type. Okay, let's go and write about what to do first. We have to put from main to helper main then add element to main then put element from helper to main ok so let's write these things now what we have to do is basically make a stack two first of all I have come to this function In this we are given constructor, push is given pop peek and MT ok so first of all what do I have to implement first of all I have to create two stacks so let's create two stacks I will again make both the stacks private why to make private because I don't want that the stacks that I am creating can be tampered by anyone from outside because if they are tampered with, if someone spoils their data, then the data of my entire class can get spoiled. Okay, so I don't want that. Should I make it private? What happens by making it private? Basically no one can access the class variables from outside. It is okay to make the class variables private. If you are not able to understand all these things then just write it now, we will see some other time. If you people understand them then we can think about making videos about it is okay, right now there is no plan, if you see the truth then it is okay, but in future, we can make it, if you people mean, then you people will say. We will have to do it, okay, so if you want us to make a complete video about the bus, then write in the comment. Okay, so now I will make a stack, okay, so I made a stack, I made an injury type of stack, so I have corrected the spelling of Ijar. One main stack and one will become our helper stack. So I created the stack and int jar and now what will I do. Now I will do treatment. Now what is the constructor function? What does a constructor function look like which has a name like a class? Same is the constructor function, okay, so now I will implement it, okay, so where will we give memory to main, in which function, in our constructor function, main is equal to new stack is okay and we will give memory to our helper also. Equal to new stuck okay so now we have to write the push function our three steps in the push function so I write the first three steps okay do all the elements of main to helper first of all we have to do from main to helper means this a little So apart from this, we have to remove things from the main and where else to put them in the helper, after that second, whatever will remain of our second part will remain in it, we have to add it in the main dot main, what do we do after adding it in the main. After this we have to do basically do all the elements from helper to sorry the mistake is happening again and again from helper to main means we want to say that brother remove all the items from helper and put them where in main ok Just now we had come to see how we have to do it, so while straightening it, I wrote down this stay, first of all I have to put a while loop, which one is the main one, so I remove this one, this will probably be a little confusing. If there is any, I have removed it. Now what to do is to first remove it from the main. As long as the main dot size is bigger than which zero then I will have to run the loop basically and till then we will add what help will we add in the helper. Helper dot d in the helper. Where will we add? After removing the main dot, remove it. Sorry, our ad will not be included in it. It will use push function which is the function of stack, it is push and q is of add. So if we are using stack, then I will use push function. Helper. Dot push and I will pop from main. I hope it is clear to you. What I did is basically pop the element from main, it will come here, pushed it in the helper, add x to main, now x element which is ours, put it in main. If you want to push in then main dot push x in Is greater than 0 What to do until the size of the helper becomes zero Add it to the main Sorry sorry push to the main and pop it from the helper Dot pop it from the helper If you are okay then I hope So it must be clear to you that the way I wrote the code was quite similar, okay, now we have to pop, if you look at us, when our Joe was in it, we saw that pop, then I will return directly to 'Y' written pop, then I will return directly to 'Y' written pop, then I will return directly to 'Y' written main dot pop, okay. If you want to see two peaks by popping them from the main then what can you see? Just look at the peak of the main because on the peak of the main there is the same element which should come out and this is the MT function. Now look at this MT function, in what way it is written. Let's write it smartly. So I wrote main dot size if equals to is equal to two is zero key now what happens basically if anyone is not able to understand how I wrote it like this then this is Boolean expression what is this called Boolean expression is called if If main dot size is zero then how will it be converted to true, it will give us true, it is ok and if this main dot main size is not zero, if it is not zero then how will it be converted, it is ok then something like this It works fine, so I hope it is clear to you that how I was able to write this part. Okay, what will we do now? Okay, now let's run it once and see, everyone is feeling fine. There will be some mistake, so see. I will take it, okay, the rest seems to be fine, everything is accepted, once we submit it and see if it is submitted, then we will do its dry run, then it is also submitted, okay, now we will do its draw run to dry run it. So I went straight to my white board, after coming to the white board, now I have to make it a little bigger and then let's dry it, okay, so this is the main function, so I have brought this, okay, so that you guys can understand. If possible, first of all I create a queue because I had to implement Ku, so queue just for reference as to what element should have come out and what is coming out, to see how the elements are. Are you able to achieve it or not, otherwise I both have prepared all these things for the try run, okay, so I wrote something like this, okay, so here I wrote why we wanted this is our answer in a way. Answer Bol Lock Answer There is nothing here Ok and we have created a stack main and a stack we have created a helper again by pushing the data and let's see, we have data 10 20 30 40 so we have all this data, first of all the main one. Na stack became helper, a new stack came 10 why I am directly 10 d here zero is greater than zero ok it came in main to be pushed so this will work no loop did not work main dot push in main I gave 10, okay, so this one of my items has been pushed, now the helper dot size is greater than the size of the helper is still zero, so this code will also not work, okay, so now only which part of ours has worked, okay if now If someone tries to pop, what will pop? Basically 10 should have been 10. There should have been 10 from both the places. So there is no problem in the first part. Now it comes to 20 of 20. So the nature of direct is to achieve. If yes, then we will put it directly in 'K', ' yes, then we will put it directly in 'K', ' yes, then we will put it directly in 'K', ' 20' came out 'Y' but ' 20' came out 'Y' but ' 20' came out 'Y' but ' Ek' brother, I want to come, now Ek' brother, I want to come, now keep pushing in the helper till it becomes zero, after popping which element from the main, 10 came out from the main and where else? But the push is done, it is put in our helper, after this, what do we have to do, after this we have to do that now after having all these elements, when the loop stops, then push x in the main. What was 20? So I did 20. In the third step, until the size of the helper becomes zero, keep pushing in the main, pop it from the helper, take out 10 from here and put 10 here. Okay, I hope this thing must have been quite clear. Why did we do this? Okay, so it is quite clear, now if I try to pop it, then it will pop 10 from here too, exactly after 10, if after 10, someone pops it again. So 20 will be popped. From here also 20 will be popped. I hope this is clear to you. Let's try it once more. In this case, if anyone had any doubt in this, then it's okay. Now it's time to talk about 30. Now 30 has come and said 30. Brother, keep me also 30, what are you doing, push me too, okay, I will push directly, because now we have three steps here, let's see all the three steps, first of all, remove all the items from the main and put them in the folder. First of the two mains, 10 came out, 10 went away, then 20 came out, where did 20 go here? Okay, after this, what will happen after this is that 30 will be pushed into the main, after that the size of the helper will increase until it becomes zero. By then the element will come out from the main. We will put the element in the main and will come out from the helper. First 20 came out from the helper. Then what did we come out? 10 came out. Okay, our helper is empty. The helper is empty then the heat is broken and now let's see again. So first. 10 should have come out of q. 10 came out here also 10 came out late then 20 should have come out 20 then 30 should have come out then 30 came out. I hope you have understood how we achieved the nature of q. Using two stacks is ok. How to use main and helper. If you understand very well then like the video. Ok and if you have any doubt then you can join our Tegra channel and ask your doubts there. Ok. It is not that you can only ask doubts on these questions, there discussing means everyone discusses, you can come and discuss there, you can find the link in our bio, in the description, if the video is fine, then in this case If you have any doubt then you can come there and ask, till then stay tuned and see you guys tomorrow where we will be doing the next question, so thank you.
Implement Queue using Stacks
implement-queue-using-stacks
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`). Implement the `MyQueue` class: * `void push(int x)` Pushes element x to the back of the queue. * `int pop()` Removes the element from the front of the queue and returns it. * `int peek()` Returns the element at the front of the queue. * `boolean empty()` Returns `true` if the queue is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid. * Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations. **Example 1:** **Input** \[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 1, 1, false\] **Explanation** MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: \[1\] myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is \[2\] myQueue.empty(); // return false **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`. * All the calls to `pop` and `peek` are valid. **Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.
null
Stack,Design,Queue
Easy
225
15
hello everyone welcome back to lead coding i am your host faraz and we are going to discuss another really interesting problem so we saw in the last problem that we were supposed to find two numbers the summation of which is equal to a given target now we extended the problem slightly now there are three numbers and the submission is equal to a specific target and in this case the target is given as zero it could be anything it could be five six seven whatever number but they decided to give it as 0 okay so now instead of two numbers we have three numbers and so is the name of the problem so find all the unique triplets in the array which gives the sum of zero notice the solution must not contain duplicate triplets all right so we are going to approach this problem in a similar way we did with the two sum problem so we will be sorting the array let us first sort the array this is the first step sort nums dot begin to numbs dot end now this array is sorted so what should be the next step so i want this problem to get reduced in the two-sum problem the two-sum problem the two-sum problem so for that i should know one of these numbers a b or c so if i know one of these numbers then i will be left with only two numbers and that problem statement will be same as the two sum problem so for that i will be running a loop for in i is equal to zero i is smaller than n i plus int n is equal to num star size so now int a is equal to nums of i so now i have a okay now i'm left to find b and c so i have to find two's numbers b and c i already have a so now like my target was zero initially now what is my target i have to find two numbers and my target should be negative of a so in t is equal to negative of a okay this should be my target now we can apply the same algorithm here that we did in the two sum we can have two pointers the first one is start and it will point to i plus one because we will be searching from the next number we are at the i position and we'll be searching from the next number and then we will have another pointer and that should be equal to n minus 1 while start is smaller than end if nums of start plus nums of end if it is equal to the target and the target is t which is equal to negative a actually you can look at it like this a plus b plus c should be equal to 0 and as we know a b plus c should be equal to negative of a okay so now numbers of s numbers of and if the summation is equal to t we got the triplet and the triplet is uh the triplet is i comma s comma e so these three are the indices for which this submission is equal to the given target which is zero okay so these three are the indices now we need to store them so first of all let us create a vector of int answer so this is a 2d vector okay like 2d arrays this is a 2d vector and this triplet should be inserted inside this answer so answer dot push back i'm inserting a vector into this answer so to create a vector i can use these curly braces i s and e inside these curly braces is a vector so this thing is a vector i'm inserting a vector inside a vector here like this using a using the operation pushback i hope this syntax is clear and if it is not clear just let me know in the comments i will make another video in which i will be explaining how to insert a vector inside a vector so this is a vector and this is how you insert a vector inside a vector of vector all right so we found one triplet okay if it is not the case if nums of s plus nums of and if it is greater than the target then in this case what i have to do i will have to reduce this summation and to reduce the summation i can do and minus otherwise i can do s plus i want to increment the summation and to increment the summation i can move s to the right side and i will do s plus if you are not clear with these steps you can watch the previous video in which we have discussed the two sum problem and the algorithm is exactly the same all right so finally i will return the answer from here okay let us try to run this and try to debug this if there are any errors so we are having tle because when we go inside this if condition we are doing nothing we will be we will still remain on this s and this e and again we will come to this loop so what i should do is i should do start plus and end minus so that i can move from this position okay so now we have this as the output and this is the expected output uh why is it so all right so first of all um we are inserting the indices here we are inserting the index i index s and the index e but instead of that they want us to store the values so nums of i nums of s and nums of e okay and let me try to run this now still there's going to be some error and we will try to debug that as well so now we have minus 1 2 minus 1 0 1 then again minus 1 0 and 1 why because -1 is coming two times okay why because -1 is coming two times okay why because -1 is coming two times okay that is why there is this repetition minus 1 0 and 1 for this pair and then minus 1 0 and 1 for this pair again and we want to eliminate this repetition we want the answers to be unique now for that what i can do is let me just try to minimize it and maximize my code here the first thing is when i'm running this uh the for loop so after this what i can do is while nums of i plus 1 is equal to nums of i can just keep incrementing i plus okay i can just keep incrementing and at the same time i will be checking this i plus 1 should be smaller than num start or we can use n here i plus 1 should be smaller than n and till the time this condition is satisfied we will increment i so as to skip the numbers which are repeating okay another thing is here we can do while nums of s is equal to nums of s plus one and s is smaller than end i can do s plus okay while nums of and is equal to nums of n minus 1 start is smaller than end i can do and minus just to eliminate the elements which are repeating so we used these two conditions over here and this condition to increment i over here now let us try to run this and it is giving us correct answer let us try to submit it now it got accepted now i want you guys to figure out the time and the space complexity of this algorithm please comment down below what is the time complexity of this algorithm and what is the space complexity of this algorithm if you have any doubt you can ask me in the comment section as well so this is it for the video i will be coming up with more videos in future also you can connect with me on linkedin and on instagram both links i have provided in the description as well thank you guys you can practice these questions by yourself and we will meet in the next video
3Sum
3sum
Given an integer array nums, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`. Notice that the solution set must not contain duplicate triplets. **Example 1:** **Input:** nums = \[-1,0,1,2,-1,-4\] **Output:** \[\[-1,-1,2\],\[-1,0,1\]\] **Explanation:** nums\[0\] + nums\[1\] + nums\[2\] = (-1) + 0 + 1 = 0. nums\[1\] + nums\[2\] + nums\[4\] = 0 + 1 + (-1) = 0. nums\[0\] + nums\[3\] + nums\[4\] = (-1) + 2 + (-1) = 0. The distinct triplets are \[-1,0,1\] and \[-1,-1,2\]. Notice that the order of the output and the order of the triplets does not matter. **Example 2:** **Input:** nums = \[0,1,1\] **Output:** \[\] **Explanation:** The only possible triplet does not sum up to 0. **Example 3:** **Input:** nums = \[0,0,0\] **Output:** \[\[0,0,0\]\] **Explanation:** The only possible triplet sums up to 0. **Constraints:** * `3 <= nums.length <= 3000` * `-105 <= nums[i] <= 105`
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Two Pointers,Sorting
Medium
1,16,18,259
316
hello friends now let's of the remove duplicate letters problem given a string which contains only lowercase letters remove duplicate letters so that each letter appear once and only once you must make sure your result is a smallest ink lexicographical order among all possible results until these two examples the first example if the input is PC ABC then we will return a PC because as we can see there are only three different letters which is B C a and there we need to return a smallest in lexicographical order if we put s be in the result string and then we put this C and we put a we'll find that very there are B and C after this B after this a so we can put this a at first and then put this B and then put these three so we because a is the first letter in the dictionary so ABC is the smallest éxito graphical older actually this question has something you needed to understand that if we are given to word one is AZ ZZ and the other is B a which one is in their smaller X equal graphic order it should be a Z because we just compare the first two different characters there is a because the words in dictionary starters from a is smaller than other words they are starter from B so that's the something you needed to understand so for this example we know that there is C B ad for four different letters and or we can choose a because there are another C and B after this a so we can choose them after a we can pick a and first and then we pick this C and they will pick this D finally pick this P so that's the reason a C D P is in the smaller lexicographical order then a DC b ADCP because the C and the D C comes first then the D so this one will be the smallest in lexicographic order among all possible results so let's see their intuition firstly we need that you mark the position of the each letter because if we want to pick this a we need to we have knows that we have to know that there are another C and B after this a so we will not put a CP before a because we can pick a C and B afterwards so we need to mark the position on each letter and another thing that we needed to use every letter or once and only once so this part is easier we can use a pulley array to mark that and then we also need u compares order of different characters so we can try to generate as a result string builder and therefore every current or char we need to compare that with the end of this result string builder because we need to Delta lexicographical smaller letter appear earlier so our solution is that we will use a culture array to counsel appearance of each letter so in this example P will be 2 and the C will be 2 and a will be 1 and will and I say that we will use a boolean rate you mark whether we have used that letter before and we will iterate from this string and the try to append that County into our result her string and if the current chart is smaller than the Ender well it should be smaller if it's a smaller then the letter in the end of the riddle Street which means we need to try to append a caricature before there's at the end of the result string so we need to check whether there is another letter before the current letter if there is we can't delete to the end over the result string and appended occur in the string so for our algorithm let's see how we get to this result first let's see the string builder first this B will be a panda in our string builder and then we append a C because b c mmm is increasing order and when we try to append a we will find the a smaller than C so we needed to check whether there is another C after this a there is because we can't get that information from the count of C code of C is greater than 0 that means there is another C after this a so we can delete a C then we compare B and a is smaller than B and there is another B after a so we can delete this be so current distributor will be just a and there we append a B and C so we get ABC let's see a cedar seven-term example we let's see a cedar seven-term example we let's see a cedar seven-term example we first appended C and then when we try to append this B we will find that B is smaller than C and there is another see after B so we delete the C and the pen the B and then we try to append a we find that a is smaller than B and there is also another B after a so we will delete a B and another stream below will just be a and it will try to append see okay C is the larger than a so we just append the C and then we try to append e okay is greater than C and a we try to append see no because we have already used to see now we try to obtain the beep B is smaller than D but they're wrong no another D up to B so we just append the B and then we try to obtain the C we already use the C so the result just be a CD B so our algorithm is correct so let's now let's write a code we need a stringbuilder SP there will be our results dream builder and we will use int array there will pick out so size should just be 26 because there is only lowercase letters and we also needed a podium used to array the size also be there 26 and the way first okay we can get to the charts there will be s to char array okay then we first to iterate to these characters array we get a lock out C minus a because we convert that character to int plus then we will iterate this chart again to generate our result string builder so we will let the cow - C - a - - will let the cow - C - a - - will let the cow - C - a - - because then the culture see - a kill it because then the culture see - a kill it because then the culture see - a kill it has no whether there is another character after this character so that means when we get this beat right we led to the cow to be decrement by one so when we can't you see we know that cat P is greater than 0 that means there is it another be after this C so that's a reason if we have used her C minus a we just continue if we haven't use it why order s dollars great the end 0 and C is smaller than SPHR at is be the very last character chart is smaller than it end or we should make sure the couch over there SB char at SP doll dance - 1 ok is SB char at SP doll dance - 1 ok is SB char at SP doll dance - 1 ok is greater than 0 this means there is another their character after the C we will let it use them SP Dolan's minus 1 there should be SP char at okay there will be SB Darlins minus 1 minus a equal to force because we deleted that so SP delete char at SB Dolan's minus 1 in the Z will just appender Tennessee to our result final return s PQ string do not forget to mark the this is C to choose which means we have a pen that have used their letter okay I made a mistake there should be boolean okay thank you for watching see you next time
Remove Duplicate Letters
remove-duplicate-letters
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "acdb " **Constraints:** * `1 <= s.length <= 104` * `s` consists of lowercase English letters. **Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/)
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
String,Stack,Greedy,Monotonic Stack
Medium
2157
705
hey everyone welcome back and today we'll be doing another lead code problem 507 designer headset this is an easy one designer hashtag without using any built-in hash table libraries built-in hash table libraries built-in hash table libraries Implement headset class void at a function void add key that takes the keys or the value in the headset Boolean contains key that will return if a key is present or not and remove just to remove a value or you can say a key from the headset so we'll be making a list so self dot list is equal to our an empty list and if not but you can say if key not in self dot list then we are going to add it so it will be like cells dot list dot appendated with key in the remove if key is present if key in self dot list so we are just checking here if key is present if key is not present then only we are going to append it because we do not have duplicates element in our uh headset so let's dot remove this Dot remove the key and here we can just return if the key is if key in self.list self.list self.list so that's it foreign yes it works now that's it
Design HashSet
design-hashset
Design a HashSet without using any built-in hash table libraries. Implement `MyHashSet` class: * `void add(key)` Inserts the value `key` into the HashSet. * `bool contains(key)` Returns whether the value `key` exists in the HashSet or not. * `void remove(key)` Removes the value `key` in the HashSet. If `key` does not exist in the HashSet, do nothing. **Example 1:** **Input** \[ "MyHashSet ", "add ", "add ", "contains ", "contains ", "add ", "contains ", "remove ", "contains "\] \[\[\], \[1\], \[2\], \[1\], \[3\], \[2\], \[2\], \[2\], \[2\]\] **Output** \[null, null, null, true, false, null, true, null, false\] **Explanation** MyHashSet myHashSet = new MyHashSet(); myHashSet.add(1); // set = \[1\] myHashSet.add(2); // set = \[1, 2\] myHashSet.contains(1); // return True myHashSet.contains(3); // return False, (not found) myHashSet.add(2); // set = \[1, 2\] myHashSet.contains(2); // return True myHashSet.remove(2); // set = \[1\] myHashSet.contains(2); // return False, (already removed) **Constraints:** * `0 <= key <= 106` * At most `104` calls will be made to `add`, `remove`, and `contains`.
null
null
Easy
null
11
hey everyone in this video i'll be describing the solution to container with most water so in this video i'll be introducing the problem explaining the solution and how to implement it and then wrapping up with the runtime analysis so in this problem you're given an integer array which is essentially a height map so each integer in the array represents a line of the with the height that the number in the array is and at the index of i so you're supposed to find the two lines which can contain the most water if they made a container so that might be a little confusing so it's really easy to just look at the test case to see what they mean so in their test case you would have these lines here represented by this array so the first line would be a height of one then this one was a height of eight six etc and the two lines which can hold the most water would be this line here and that's because eight and seven um so uh the smaller wall would be a seven length so the height essentially of this rectangle is seven and the base between them is just the difference between their indexes so this is at index one and this is at index one two eight yeah so this is index eight so eight minus one that's seven so the base of this rectangle would be seven and the height of this rectangle would be the minimum of 8 and 7 which is 7. so um 7 times 7 is 49. so essentially you're trying to maximize this area of the rectangle all right so now let's get into how the solution works so we know we are trying to maximize the area of the rectangle so let's first define what the area of the ranked rectangle is so if we have um this rectangle the base would be let's just say we have a pointer i and a pointer j so i is one index a number one index and j is the number the other index so let's just like say i is this one and j is this one so the base would be j minus i so that's the length of this base and the height would be the minimum of um array i and array j so that's the height so whichever one of these lines is smaller that's going to be the height of our rectangle because then you can hold this much water and so we're trying to maximize this area base time height so we can apply a greedy approach to solving this problem we can first start with the rectangle with the largest base so we start i at the first number in the array and j points to the last number so this maximizes our base and we can simply perform a computation to get the area of this initial rectangle say it's with let me just clear out the screen a little so say the initial rectangle is with one wall this high and one will decide we can just compute the area of this initial rectangle with the maximized base now an important observation is that to get a rectangle with a larger area we must shrink the base because we already have the largest base and the second important observation is that when shrinking this base it's futile to try to shrink the taller wall because let's say we found a super tall wall next to here and shrunk this to here and hoping that we can hold more water with this taller wall it won't help us because this short wall is still here and ruining our plans so the gree approach comes in where we know that to make a larger area we must shrink the base somehow and try it out so what we do is we move i over one because i is smaller is the smaller between these two walls like j is this tall eyes this tall so we will want to move i one over and see if that makes a larger area because that would be the only possible way to get a larger area with a smaller base is if you somehow run into a taller wall on this side well now suddenly you can get more water and then you just keep on doing that until you cannot shrink the base anymore so until like i and j meet up somewhere in the middle here and yeah and you would just repeatedly um repeatedly use this greedy logic so let's just say i shorter here let's just say now i is a little taller here with this bass now you can use the same logic um we need to test if we can shrink the base and get a larger area um so in this case we would move j because moving i is pointless because i is already the taller wall so we want to move j to see if we run into an even taller wall to make our height larger so yeah and just to summarize that in a concise way it is the algorithm essentially first starts off with the maximum base and then tries to see if can i make the base smaller but increase the height enough so that the area is larger and that's exactly what we do by readily changing the smaller wall to see if we can increase the height and let's see how to implement this strategy with code so here's a solution i coded up and as you can see we'll use i as our left um i guess left wall and j points to the index of our right wall and so while we can still shrink them so while i is less than j we compute the area formed by these two walls so j minus i that's the base and then the minimum height of each wall so in this case we would start with i pointing here i is one and j would be seven and then so we'd find an area of seven and then we to set that to our max area because that's the biggest one we found and then so uh then we try to shrink the base and see if we can compensate with that enough for an increase in height so if our wall at the index of i is shorter we'll move i one over and otherwise we'll move j one back and so this will greedily move the walls so that the smaller one will always get shrunk in to try to find a taller wall and we just keep on shrinking this base until we can't shrink it anymore and then we just return the maximum area we ever came across um like doing this algorithm and yeah let's just submit this to prove that this works um yeah this was uh i just submitted a couple times before and yeah as you can see it's really fast because we're essentially just um going through the array once by starting i and j at either end and forcing them to get closer and closer to each other so this will be an ofn algorithm so yeah that's about it for the video i hope you guys enjoyed it and found it um a good video and yeah i'll come back with another video tomorrow thanks for watching
Container With Most Water
container-with-most-water
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`. Find two lines that together with the x-axis form a container, such that the container contains the most water. Return _the maximum amount of water a container can store_. **Notice** that you may not slant the container. **Example 1:** **Input:** height = \[1,8,6,2,5,4,8,3,7\] **Output:** 49 **Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49. **Example 2:** **Input:** height = \[1,1\] **Output:** 1 **Constraints:** * `n == height.length` * `2 <= n <= 105` * `0 <= height[i] <= 104`
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle. Area = length of shorter vertical line * distance between lines We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
Array,Two Pointers,Greedy
Medium
42
338
lead code problem number 338 counting bits so this problem gives us an integer and the goal is to return an array on of length n + one right such that for on of length n + one right such that for on of length n + one right such that for each integer inside uh from zero to n the basically each value of it is the number of ones in the binary representation of I so for example here you see Zero is zero 1 is one two is one zero and since there's only one in one zero so it has one here right same two 1's two one 2 one two and so on right so you can easily solve this problem using a for Loop which it through true from 0 to n and basically for each number we will apply the haming weight function and if you don't know what's the Heming weight function I've explained this in leode video number 191 I explain how this function works as well as this two uh bit wise operation right so basically this function will help return the number of ones in the binary representation of n right in which this case n would be I which is from 0 to 5 in which it will populate the result vector and return the vector result as this right so basically that's how this function works and there's also another way to solve this which is to use a buildin function in C++ I'm not sure whether any other C++ I'm not sure whether any other C++ I'm not sure whether any other programming languages has something like this but if you use buildin pop count it will return the exact same result as what the Hing weight function would right which is returning the number of ones in the binary representation so you can see the code is exactly the same the only difference is I had to implement the Hamming weight function myself while here I'm using the buildin function okay so this is a fairly simple it is a it is question built on top of the existing needco problem 19 191 so do check it out if you want to know more about how this function works anyways that's all I have to show thanks
Counting Bits
counting-bits
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`. **Example 1:** **Input:** n = 2 **Output:** \[0,1,1\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 **Example 2:** **Input:** n = 5 **Output:** \[0,1,1,2,1,2\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101 **Constraints:** * `0 <= n <= 105` **Follow up:** * It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass? * Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
Dynamic Programming,Bit Manipulation
Easy
191
316
hey what's up guys hi this is sean here so uh actually i want to talk about briefly talk about today's week uh daily challenge problem which is number 316. remove duplicate letters i think this is a very like interesting problem you know okay so you're given like a string uh you need to remove the duplicate letters so that every letter appears only once and you're not only asked to remove the duplicate letters but you need to remove that letters in a way such the remaining string should be the smallest in the lexical graphic order among all the possible results and okay and this problem is the same as the question same as the uh this one's just a smallest subsequence of these things characters is equivalent to that one so basically you know you have a b c a and b here as you guys can see here we can remove b c a b and c so for this string here since b and c right we have 2 b and 2 2c which means that we can remove 1b and 1c but which one to remove right so in this case we need uh we should remove a b and c because the a is smaller than b and c so basically we're trying to remove anything that's before a right because a is smaller than that so that abc is the smallest one and then the second question is c b a c d c b c so this one is more a complicated one so basically as you guys can see we have three c's we have one two and the three c two b and one d and one a so for d for a and d would there's we cannot remove them right but for the c and b here right so we can remove c and b here because we already have we have some b and c later on here so we have b and c and then here we have for c here we can remove the uh you know between the this two c here right so we want to remove the c right here because if we remove c here i mean we will have d here right so basically d is greater than c right so d is greater than c that's why we want to keep the c that's be before d here and we'll remove c here so b is the we cannot remove it because b there's no more b left right so c here we can also remove this c because we have we already have a c in the string here okay cool so and the length of the this s is like 10 to the power of four okay you know every time when you see like this stream problem it's asking you to find the smallest or biggest thing you know and now one way of doing this i think i'm not sure if we can solve this one with the uh this dynamic programming um probably yes you know we have us but for this problem you know a better way of solving this it's just using a greedy uh solution which means that you know greedy plus a stack so if you guys and this one requires you a bit of observations now since i think some of you may have already uh noticed that right so the strategy after the removal after removing is like i mean if there's any if the card letter has uh as for example if we add a here right the reason we can remove c and b is because you know we have c and b later on here right uh later appears uh more than one times in the string here so that you know when we have an a here we can simply remove the c here so what i mean is that we have a stack here right so the stack is this so first time we have c okay we have c and then we have a b okay and every time when we have a new uh letters comes in right we compare this letter with the i the item on the top of the stack okay and if that's that if this i if this letter has some remaining uh if the counter for this one is still greater than zero then we know okay we can simply remove it because you know by removing this one we can uh because the current one let's say the current one is b right so the current one is b so by removing this c here we have uh we have a b at the beginning of the string which will give us like uh a smaller lexical graphic order string here so that's why when we have a b here we're going to remove c here right and now same thing for a right so a so when a comes right we check okay so does a is a smaller than the top one of the stack yes it is and we also need to check if the b has the counter of b is greater than zero or greater than one because if there's no such b here if there's no b here then we cannot remove b here because if we remove it then we're so the string will one will be missing a ladder right but since in our case as you guys can see here so the b counter is two here right so we can simply we can safely remove this one so now we have a here now the next one is c right so we have c here but c is greater than a so which means that we cannot remove c because if we remove a here you know the string will become bigger right so and then the next one is d okay so d is the same one since d is like it's also greater than that than the one on the top of the stack okay and then we have b here so b yeah so b as you guys can see so b is smaller than d is also smaller than c but the problem is that you know uh sorry so the but the problem is that you know okay we're only comparing with the top one but the problem is that you know the d does not have any remaining uh letters for us to pick because d only has one here right so that's why we cannot remove d assuming if we have a d here right and then when we have a b here we can simply remove it because we know the b d is great it's smaller than the d and b but in this case since we don't have any additional a d here later on so that's why we cannot remove this d here and then the last one is it's c right so when c comes in um yes it's already uh in this stack here right so it's already here so that's why we can simply skip that yeah i think that's the basic idea here right i mean so the implementation i mean as long as you can make this observation right i mean the implementation should be pretty straightforward enough right and so uh we will need a stack right so the stack is this and yeah and then we simply do this right we just do a four character in ass here right and then um so uh oh yeah so first thing first we need to count the appearance of each of the ladders that's why we do we use it like a butane python built-in we use it like a butane python built-in we use it like a butane python built-in function we call counter which will give us like a dictionary right which is where the key which key is the uh where key is the string the letter and the value is the appearance is the times that the letter appears in the string so here you know every time when we have a letters here we simply do a counter do a count we do a count off the c minor minus one first right so that's what so we decrease it by one so that later on we can check right so later on when we have a different numbers here we can check okay so if this number if this letter has anything left uh later on uh right otherwise we cannot keep track of that right because we have to remove the ones we have seen so far so that's the first thing here right so and then uh we need to remove the uh we'll check first one if the stack is not empty and the uh the current letter is smaller than the uh the ones on the top right so the ones on the top okay so that's that so and if the counter the count of the stack on the top is greater than zero then we can simply remove it right so we can simply remove the uh stack dot pop okay and so once we remove that right we can simply add this thing append this c here to the stack and in the end we can simply return the uh we can just return the string that we join uh by joining the stack okay join stack okay oh and one more thing here is that so we haven't had no this the last c here so the c here even though it's uh even though the c uh so because for the last c here since it's already appeared in the stack here right so we need to simply uh skip that okay which means that if the c is in stack uh we simply continue okay um but one thing i think we can improve here is that you know uh to search this uh string in a stack uh i think it's all of end time right um so that's what we can do here we can do a like uh have a set here okay we do a scene set here instead of searching the in the list here we search in the scene here okay so to do for that and we need to maintain this uh besides the stack here we also need to maintain this uh scene the set here so which means here scene dot add c and when we remove it we also need to remove it okay so we can simply uh you know we have removed here right removed and then we can also remove the scene and dot add sorry yeah add removed yeah so this is just like uh a little some additional improvement so that we can keep our time complexity to o of n right so here we have o of n and so here is o one but we have a while loop but as you guys can see we will only uh since we are keeping since we keep popping uh the letters from the stack here so in total we will only be doing this like uh this pop uh end times right so oh so let's try to run the code for what uh did i do anything wrong here let's see here um count we have a here b and c stack is that scene is this so if this is in scene we continue as removed oh here so uh so what when we pop the things out instead of add we need to remove right so we remove the scenes from the scene set okay so let's run the code okay so now it's accepted let's try to submit it right cool so it's also accepted you know yeah so basically you know that's pretty much it is for this problem you know it's a i think it's a good uh medium level problem you know the only things you need you guys need to be careful is that not careful to remember is the uh to get the smallest right we sometimes we either use a dynamic programming or we use a binary search but in this case it's not applicable or the greedy right so with the greedy you always can get the smallest or the maximum and for this problem greedy is a proper way of solving it right basically you know you have to basically you need to make some observations basically uh you need to see uh how can we how can you uh greedily remove the ladders we don't need right and then just and then we can keep the ones uh we keep the ones that we cannot remove and we remove everything we can remove following this kind of strategy okay yeah and space compliance time complex is o of n because here this is n here and here you can think it as a one here because the stack is not we will so each of the lighter will only be removed uh once in the stack so here's like also of in total it's o f n so here's o often right and uh yeah and the time space complexity is also often right of this cool i think that's it for this problem yeah thank you so much for watching this video guys stay tuned see you guys soon bye
Remove Duplicate Letters
remove-duplicate-letters
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "acdb " **Constraints:** * `1 <= s.length <= 104` * `s` consists of lowercase English letters. **Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/)
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
String,Stack,Greedy,Monotonic Stack
Medium
2157
73
Bluetooth Hi Everyone Welcome To The Channel Once Again Another Very Important Problem Set Matric Shyu Nimit This Problem Is Like Subscribe And Planning To For Company You Must For This Problem Long Time Back To You Should Not Remember You Can Solve This Problem Solve Problems He Gives rise to modify in place where 2012 updates all elements in the same way problem myjio one digit thursday will update the values ​​in 200000000 subscribe problem update the values ​​in 200000000 subscribe problem update the values ​​in 200000000 subscribe problem solving subscribe's to-do solving subscribe's to-do solving subscribe's to-do list sunao pilot soft will solve the very root for the best code do admin tried To This Award Winning Lead Over Business Copy Din Matrix In Some Temporary Matrix All Elements In The Sacred Thread Through One Middle Age Person Channel Radhe-Radhe And Subscribe 0 The Calling All Cars In A Row And Column With Them And Similarly In The Blank After 10 And The problem is zero Final answer is like this whole matrix with all your actions Display System Original 120 Dhawan Solution Very Fruitful Marinate Solution Acidity Problem St. Martin To Do The Time Complexity Of Solution For A Process Which Subscribe And Subscribe The Video Then Subscribe To the Video then subscribe button Eminem is plus and maximum fine what will oo again the matrix soft will create two vectors and 2 and e are and this point and that don't like share and subscribe skin and information2media dr I'll be in to the road And Current And See The Amazing Subscribe Button More Similarly 20 2010 Subscribe Is All The Hero And Column Index Of This Were Dowse In The Recent Past 10 Years In First 500 In Secret Password Me To Be Voter Ready To Vote For Sure To The Number Of Sentence continue and long modified will start from 50000000 subscribe due to be seen that dr is not any rose water and did not any problems will not do any change he well one off the road tax in the robot boy weir what is the time in Subscribe Complexity of plus maximum of one subscriptions is specific water seeps so can we do you for the more optimize some of it like not lead to guest teachers but you can share your singh bhi row and column better can we use in Andharon and Columbus the story THIS IS A BIG BOSS ME ENTRY EME SOMBIR 120 PROBLEM AS WELL AS ALL ENTRIES 0 PROBLEM BE WATER AND YOU WILL DIRECTLY INTO DIFFERENT STROKES SUBSCRIBE AND DISAWAAR YEAR 2012 HALF GOTHRO 800 WILL UPDATE 0SHARE IN THIS SIMILARLY WHEN DR0V0 UPDATED MORE THAN 300 NOBODY Can We Do Take Care Special Offices And Subscribe Will Miss 420 Like First Row First That Rose Hero And Column Rose 0 Insulin Variable So That One Officer Dr. R. D. Control In The World Will Do You Cannot Write Subscribe To Channel Like and Subscribe I changed into being tasting give any form in this site will market se zee will keep moving subscribe bath more benefit for this is not mean that you will have to so let's isro isse chali similar difference problem was solved the first one Subscribe number of columns of true for first to do this padh hai na ho is entry fennel matrix of fifth column fennel long eyebrows m1005 scanner mig-21 off sale a grade hour or they will mig-21 off sale a grade hour or they will mig-21 off sale a grade hour or they will update first festival 40 j&amp;j number update first festival 40 j&amp;j number update first festival 40 j&amp;j number of columns and hair oil VJ PLUS 900 TO 1000 SUBSCRIBE MY FAVORITE PLAY LIST THE RATE OF FROM TOE KI PLUS KI END POINTS EQUAL TO ONE JEWELERS AND A PLUS NO WILL CHECK TRICK Chhagan Singh Gautam Jain Is 0tweet U Will Update Of Sure Rose School A Wise 0 Similar aa sorry e a copy paste base line only similarity bill pro0 dr subscribe indicating her 2009 a password will be 10 Dec 09 2010 photo hair is this is 016 from this 2009 me isro entries 09 2009 thank you again 100 is jeth a message minute divide if i 10 column0 problem is world * turmeric row is igs 0 and that this matrix of for 20 row ni8 column this zil99 life in middle aged person subscribe then right basis runway copy paste this piece of knotted with this special need To update matrix of subscribe school boys throw sure olympian under to take this people vishwaveer and member vinod 2006 and dont do anything return through placement agency not only condition more vitamin b type those 10 will be the first 1110 then steam-up-your sex
Set Matrix Zeroes
set-matrix-zeroes
Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s. You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm). **Example 1:** **Input:** matrix = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** \[\[1,0,1\],\[0,0,0\],\[1,0,1\]\] **Example 2:** **Input:** matrix = \[\[0,1,2,0\],\[3,4,5,2\],\[1,3,1,5\]\] **Output:** \[\[0,0,0,0\],\[0,4,5,0\],\[0,3,1,0\]\] **Constraints:** * `m == matrix.length` * `n == matrix[0].length` * `1 <= m, n <= 200` * `-231 <= matrix[i][j] <= 231 - 1` **Follow up:** * A straightforward solution using `O(mn)` space is probably a bad idea. * A simple improvement uses `O(m + n)` space, but still not the best solution. * Could you devise a constant space solution?
If any cell of the matrix has a zero we can record its row and column number using additional memory. But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker? There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.
Array,Hash Table,Matrix
Medium
289,2244,2259,2314
107
And where did it happen Hello friends welcome to your depot software going to school problem list code 1073 2011 order traversal to cash withdrawal program so let's see what is this question so basically you will give one graph and how to return its bottom of living Product Reversal Pocket Means 16 This Is My Life Is Mishra Sudhir And Order Cancel In Reverse Order To This Is Amazing This Is That Level-1 Pims Level-2 Soin Flu Se 0143 That Level-1 Pims Level-2 Soin Flu Se 0143 That Level-1 Pims Level-2 Soin Flu Se 0143 Liye Bima Level One Of Two 990 Level Two He 9076 Difficult Supposed to do that today son Nidhi Sharma 12th I want to reverse find written after returning from this is I to Delhi are it 0083 laut na dhone ki level-2 in these anti-growth serving level-2 in these anti-growth serving level-2 in these anti-growth serving three layers strongly subscribe The Amazing Pimple 200 basically Booty viewers reverse like this point to practice setting off basically they can solve this using both beef edifice after once again * used left foot once again * used left foot once again * used left foot introduce that Davis to introduce difficult this so what will uh will just I will just maintain level side 100 ko konimesse 0f it is that ICC emerging graph 800 what is the 30 chest so basically water will do i will just tractors level order in simple way only so a great normal also only and after a bill to return to 12th and after the village And He Will Just Reverse And Will Return From This Point Left School At You Will Get More Clarity So Let's Do Some Problem Creative Work That Bigg Boss Vihar To Return Distributors And How To Be The First To Leave One Act Result So You Subscribe One Person's Roop thing red and what if it is null view to just returned this anti this mp result and null answer on this to-do list this anti this mp result and null answer on this to-do list this anti this mp result and null answer on this to-do list sorry but what will oo all search on Dual app that when search on I will pass through find result and currently Amazon Level In Surplus Days And After That Will Just Years Ago Do One Day My Result Twelfth Result Vector For Bridgestone Result Pilot Side On Due To This So Lets On Difficult To Avoid Mind Will Take Worst Drought In AProud We Three Type Of Food At This Point Notes Fruit And Will Also Have This App A Stone Result I Will That Bill Use Reference Profit And Co Maintain Labels Current Liye 1000 Sonth 20 This Point To This Reception More Subscribe What Is Page Subscribe And One More Of Liquid Liner Labs Result Police Eyes Are Just Created Is Equal To Objects 381 Vector Of Animal Science University Result This Back Banal To Opposition This Is After Death Of Villagers Who Will Explain Why Decree Solitaire Will Just Reverse Close Loop And Pushed Back To A Push Value Of Vote Twelve years after the will just benefit is the left and my result mister and now she dubai increase the that dream and enriched up the root right a hua tha with 102 y a wide uddin there on this condition backbone of subscribe button under slide show hua Tha factor size in all directions who know how to create in recent years in prison director of vector to father to right now have just now access normal twitter nature normal 12th so every attempt to write moment levels in subject my result size and same loot subscribe Do One Will Just Insult Who I Will Be TV Actor Will Be Empty End When Ever After Creating Don't Take It And Forced Channel MTV Hundred Of These Egg Pushback Form Value Approach Spent West Senior Doctors After End Of Wutz Were Pushed Back And Welcome To Z Tak Live Where Give All The States 1666 Jai Hind Se Welcome To Next9 Travels In His Lord Will Just In Adhir And Notes That Bigg Boss Roughed Up Chairman Mirwaiz Andher Specific And Electronic I Office So Lets E.t. Clearly Showing I Office So Lets E.t. Clearly Showing I Office So Lets E.t. Clearly Showing Right Left Including 9 Bluetooth Settings Show With Price And You Like This Video Please Like Press Your New Share Or Subscribe Button And You Have Any Suggestions Or Difficulties In The Comment And Solution Of The Course
Binary Tree Level Order Traversal II
binary-tree-level-order-traversal-ii
Given the `root` of a binary tree, return _the bottom-up level order traversal of its nodes' values_. (i.e., from left to right, level by level from leaf to root). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[15,7\],\[9,20\],\[3\]\] **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]`. * `-1000 <= Node.val <= 1000`
null
Tree,Breadth-First Search,Binary Tree
Medium
102,637
1,004
hello welcome back to my new video in today's video we are going to solve a lead code problem number one4 Max consecutive 13 so let's understand the problem statement we have given a binary array nums and an integer K return the maximum number of consecutive ones in the array if you can flip at most K Zer means let's see this example we have given nums array we can flip two zeros to make it one like if we flip this zero and this zero so we will get five consecutive ones but we have to found maximum consecutive ones so we will flip this zero and this zero so we will get six so let's see what hint is given to us one thing is for sure we will only flip a zero if it extends an existing video or right we can think about sliding window right okay so let's write a code then we will understand it by doing try run of this code so we will use two pointers one I would be iterating each elements of the array and J let's see what I'm saying I will be at zero index and J will be at zero index as well we have to iterate till I is less than nums do l so we have to check if nums at I is zero see if it is zero then we have to decrement K because if we decrement K means we have flipped this coin because if Char I mean num at I is zero so we have to decrement K means that we have successfully decremented it okay so we have to do K minus else if um when we decrease inent if it become negative if it become less than zero only when we have to increment J so if it is less than zero if I mean after this and this it will become zero and at this point it will become minus one so if it is less than zero have to check nums at J if nums at J is zero if yes then we have to do k++ because we are moving our window if k++ because we are moving our window if k++ because we are moving our window if J is here and num said J is zero increment the value of K that we have unflipped it so the window is like this if I will be here so the window is like this and after that we have to increment J as well and we have to return an integer the length of our window so if I is here and J is here so I minus J will give us the length of the window which is six in this case so we have successfully solved this problem let's do the dry run of this code first run the case time limit exceed I is less than let's see oh yeah we are using I but we never incremented it let's again try to run the code oh yeah we the cases are accepted let's submit the code all right we have submitted the code with 100% of users we have written code with 100% of users we have written code with 100% of users we have written 100% of users let's see the dry run of 100% of users let's see the dry run of 100% of users let's see the dry run of this code so let's see the dry run for this input we have given this array uh I would be here initially I would be here I at zero and J will be here too okay so I will run till nums do length and first we have to check Char it in iteration one we have to check is num set I is zero no so if num set I is zero then we have to do something otherwise we don't have to do these things we just have to increment the I variable so we will increment our I variable okay so in iteration two and I is not equal to zero so we will this still here like in for cration we don't have to do anything so in itation two again I is not equal to zero in iteration 3 again I is not equal to zero but in iteration 4 num set I in this case num set I is equal to Zer so we have to decrement the K so the value of K is decremented to one okay so decre we have decremented the K and K is not negative don't do anything just increment the I so I will be here okay so in a 4 is over uh in itation five we are here uh we have to check num set I is zero yes numet I is zero so we have to uh if num set I is zero we have to decrement the K so yeah num set I is zero we have to decrement the k was one now K is zero K was one now our K is zero uh after that do y ++ so K is ++ so K is ++ so K is zero okay so we went we didn't enter the condition so num said J after that when K becomes less than zero it will go in this condition it will increment the J so in iteration 6 K decre decreases is 2 k will be minus one in this case k is zero so it will become minus1 as we see in this condition so we enter the condition if J we will check n said J is zero no it is not just do in just increment the I mean it is not zero so it will not go in this condition so just increment the J uh we will increment the J here and when J will be here we will increment when num said J become zero this condition we will increment K so K again will become zero after that increment J as well yes this is zero so we have to check because see it will still is negative it will only go in this condition so yeah we will increment our J again now it is zero but we have incremented it to one now K is not less than zero so in iteration uh s in iteration 7 num set I is not zero so I the value of I would be seven and it itation 8 num set I is not one again it will increment till here until it become negative after it in iteration 10 is not zero yeah in iteration 11 num is zero at this place it is the 10th position I gu 0 1 2 3 4 5 6 7 8 9 10 so in itation 11 so K decreases by K to minus 1 so we went we enter the condition num said J would be zero so num set J if it is zero decrease the K so increment the K so J I would be 10 so in end of the iteration J was here and I was here so I was at 10th index and J was and at Fourth IND index so we will return six this is our answer and there you have it uh we have successfully solved lad code problem number one4 using sliding window technique understanding the problem and implementing is efficient solution is crucial so thank you uh we'll meet again peace out and you can take screenshot of it if you want because 0 1 2 3 4 so J would be here okay so I minus J I was at the end of the index so I minus J will give us the length of this window which is six and this is our answer
Max Consecutive Ones III
least-operators-to-express-number
Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s. **Example 1:** **Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2 **Output:** 6 **Explanation:** \[1,1,1,0,0,**1**,1,1,1,1,**1**\] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. **Example 2:** **Input:** nums = \[0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1\], k = 3 **Output:** 10 **Explanation:** \[0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1\] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`. * `0 <= k <= nums.length`
null
Math,Dynamic Programming
Hard
null
528
Hello friends welcome back if you are enjoying the content don't forget to hit that subscribe button below it really helps us out and you won't miss any future videos today we are solving random pick with weight this is an interesting probability based problem let's get into it we are given a zero indexed array of positive integers W where wfi describes the weight of the I index we need to implement the fun function pick index which randomly picks an index in the range 0 to weight of length minus one and return set the constraint to picking the index is the probability of picking an index I is equal to weight of the index I divided by sum of all the weights let's look at this example to understand the problem we are given with W equal to this and the function pick index has to pick one of the indexes is 0 1 or two and probability of picking index 0 is equal to 1 by 10 where 1 is the value at index zero and 10 is the sum of all the values in W similarly probability of picking index 1 is 3x 10 and probability of picking index 2 is 6X 10 if we imagine W as a list of candies then we have three candies right now candy zero has weight of one candy 1 has weight of three candy 2 has weight of six let's say we have all these three candies in a container like this one and the role of function pick index is to reach into this container and pick one of the candies probability of picking candy 2 is higher because its weight is six out of 10 and similarly probability of picking candy zero is lower because its weight is 1 out of 10 to solve this problem we can break these candies into pieces of weight one and on each run of function pick index we have to pick a piece of candy of weight one and return its index so this is what the list looks like if we break these candies into pieces of weight one so there are 10 pieces of candies here where each piece is of weight one there's only one piece of candy Z because candy Z has weight one and there are three pieces of candy 1 because candy 1's weight is three and there are six pieces of candy 2 because its weight is six and we divided it into six pieces each of weight one so now what pick index function has to do is randomly pick one of these indices and return its value this satisfies the given constraint because probability of picking a piece of candy zero is 1 out of 10 probability of picking piece of candy 1 is 3 out of 10 and probability of picking piece of candy 2 is 6 out of 10 the runtime complexity of this approach is Big O of T is the total number of pieces of candies and N is the number of candies do we really have to build this new array to solve this problem to find out it makes it easier if we change this array from zero index to one index like this where 10 is the sum of the original input array W so we have to randomly pick an index between 1 to 10 and return its corresponding value in this array so the question is can we find this index's corresponding value without having to build this array the answer is yes for that we have to look at the ranges of these indices for candy Z the indices range from 1 to one because there's only one piece of candy zero for candy 1 the indices range from 2 to 4 and for candy 2 the indexes range from 5 to 10 when we pick an index randomly from 1 to 10 we need a way of mapping that index to one of these ranges without having to build this new array this mapping can be easily derived from the drawing over here we thought of this as a container and these three circles are candies of different weight so the candy zero goes from 0 to 1 on the x-axis candy 1 goes from 1 to 4 on the x-axis candy 1 goes from 1 to 4 on the x-axis candy 1 goes from 1 to 4 on the x-axis and Candy 2 goes from 4 to 10 on x-axis and Candy 2 goes from 4 to 10 on x-axis and Candy 2 goes from 4 to 10 on the x-axis so if we look at the end of these x-axis so if we look at the end of these x-axis so if we look at the end of these ranges 1 4 and 10 they match with the end of ranges over here 1 4 and 10 why do they match because we are breaking these candies up into pieces of weight one and each cell in this array is a piece of candy of weight one and each unit in this x-axis is a piece of each unit in this x-axis is a piece of each unit in this x-axis is a piece of candy of weight one that's why they match for the same exact reason if we took the prefix sum of this input array W which is 1 4 and 10 and this prefix sum matches with the end ranges of each candy we saw before which is 1 4 10 so basically we have to pick a random number between the range 1 to 10 let's call this X and we have to find the first index in the prefix sum array whose value is greater than x let's say we pick the integer 6 which is equal to X and we scan through this prefix suaray and find the first index whose value is greater than six which is two so we return two next let's say we pick two which is equal to X and we find the first index whose value is greater than two which is one so we return one so once you understand this mapping it's easy to see that this linear search operation is doing the exact same thing we did using this new array we had built so that means we don't have to build this new array we just have to find this mapping and the mapping is basically finding the prefix sum array which brings down the runtime complexity to O of n but we can further reduce this complexity to O of log n because the values in this prefix some array are sorted in increasing order that means to find the first index whose value is greater than x we can apply binary search so that's our final algorithm let's apply this algorithm on a different example here is another example W sum of all the elements in W is 15 I've already written down the prefix sum array for w where the first element is the same and the second element is first element Plus 4 1 + 4 is 5 + 3 is 8 + 2 is 10 so 4 1 + 4 is 5 + 3 is 8 + 2 is 10 so 4 1 + 4 is 5 + 3 is 8 + 2 is 10 so on and so forth so now we start by picking a random number between one to 15 where 15 is a sum of w and we call it X let's say the random number we picked is seven so we have to find the first index in the prefix summary aray whose value is greater than 7 and we apply binary search for this in binary search we have two pointers left and right next we find the mid element which is L + r by 2 the mid element which is L + r by 2 the mid element which is L + r by 2 which is equal to 0 + 5 by 2 we always which is equal to 0 + 5 by 2 we always which is equal to 0 + 5 by 2 we always round down which is 2 so we check if the value of index 2 is greater than or equal to 7 which is true in this case 8 is greater than or equal to 7 which means every index after the index pointed to by m will have value greater than seven which implies we can get rid of the right half so we move the right pointer to M and we continue doing binary search now M will be 1 + 2 by 2 which is 3x 2 now M will be 1 + 2 by 2 which is 3x 2 now M will be 1 + 2 by 2 which is 3x 2 we always round it down which is 1 next We compare the value poed to by index one which is 5 to x equal to 7 5 is less than 7 that means any index below this index pointer 2 by m will have values less than seven so we can get rid of the left half so we move L to m + 1 now both the point respond to the m + 1 now both the point respond to the m + 1 now both the point respond to the same index that means we have found the first index whose value is greater than or equal to X in this case 7 so that's our algorithm as we discussed before the runtime of this algorithm is Big of n where n is the number of elements in the given input array W so let's write the code for this algorithm first we start by building the prefix Su array let's call it prefix where basically we need to maintain the running sum of Weights starting from zero for weight in W add it to W sum and append that to the perfect sum append w we also need the sum of all the weights let's call this total which is equal to W sum next in the function pick index we start by picking a random number between one and total using the python Library random dot Rand in between one and total we called it X next we need to do the binary search to find the first index in the perefect sumar whose value is greater than or equal to X we have two pointers L and R L points to the first element and R Points to the last element of the prefix sum array while L is less than R we find the mid index which is L + r - L by 2 we mid index which is L + r - L by 2 we mid index which is L + r - L by 2 we check if value of the mid index in the perefect summary s the prefix of M is greater than or equal to X that means all the values after this is also greater than or equal to X and we can get rid of the right half by setting r equal to M else we can get rid of the left half bying m + one when both L and left half bying m + one when both L and left half bying m + one when both L and R Point respond to the same element we return that index let's try to run the code as you can tell the submission goes through if you found this video to be helpful please support by liking the video and subscribe to the channel I will see you in the next video thank you
Random Pick with Weight
swapping-nodes-in-a-linked-list
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index. You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`. * For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`). **Example 1:** **Input** \[ "Solution ", "pickIndex "\] \[\[\[1\]\],\[\]\] **Output** \[null,0\] **Explanation** Solution solution = new Solution(\[1\]); solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. **Example 2:** **Input** \[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\] \[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\] **Output** \[null,1,1,1,1,0\] **Explanation** Solution solution = new Solution(\[1, 3\]); solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. Since this is a randomization problem, multiple answers are allowed. All of the following outputs can be considered correct: \[null,1,1,1,1,0\] \[null,1,1,1,1,1\] \[null,1,1,1,0,0\] \[null,1,1,1,0,1\] \[null,1,0,1,0,0\] ...... and so on. **Constraints:** * `1 <= w.length <= 104` * `1 <= w[i] <= 105` * `pickIndex` will be called at most `104` times.
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
Linked List,Two Pointers
Medium
19,24,25
258
hello guys my name is Arsenal and welcome back to my channel and today we will be solving a new lead code question that is ADD digits we will be solving this question with the help of JavaScript so let's read out the question what the question is asking from us so the question says given an integer number repeatedly add all its digit until the result has only one digit and return it okay so what we have to actually do it uh do is that we will be given a number integer so we have to return it until it's one digit so we will have to add these digits means if we add 3 plus 8 we'll be getting 11 and when we have to add it until we get a one digit number means it should be less than 9. so the point here is that when a number is less than 9 we have to return that number so we have to keep adding these that number until where we have we got the number that is less than 9. see here that a if we add 11 PV 1 plus 1 will give us 2 so we have got the number 2 which is of course less than 9 so we were starting this for solving this question so just before starting solving this question guys do subscribe to the channel hit the like button press the Bell icon button and bookmark the playlist so that you can get the recent updates from the channel so first of all my first condition would be if num is equals to zero so if it is 0 then we I will return it zero of course there is no doubt in it uh because if it is a zero then we have to return 0 since it is 0. okay so next thing I will be writing is else return 1 plus and numb minus 1 and mod 9. so why we have taken this I will explain to you so just look at it so right if we return this whole thing uh we will be getting num is like 38 uh if we divide uh if we add these two digit what we will be getting a remainder as uh we will be getting remainder so we will be getting a remainder of 2 because if you at minus 38 minus okay I will do it here so that you can picturize it so 38 minus 1 will give us 37 and 37 plus 1 will again give us 38 and 38 now we have to mod this so 38 mod 9 will give us what two because uh it will be giving us a remainder similar in um if we take any random value for example if I take um if I take which number I should take another number like um let me take 30 here so I will be adding here 30 minus 1 is equals to 30 29 plus 1 it will give me 30 and 30 mod 9 will give us three so that was all in the question guys hope you have understood that this concept it was a tricky one however it is simply a straightforward you just have to apply a logic of mathematical concept and let's run the code now and check for the answer so you see that it has been running successfully for n is equals to num is equals to 38 and if we apply for multiple test cases it should run for all of those let me take some random values here and run the code now so you see even if we have applied a multiple test cases it has been running successfully so this was all in the question guys hope you have understood this and hope you have liked the video if you have any doubt ask in the comment section I will try to help you out thank you guys for watching it see you next time
Add Digits
add-digits
Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it. **Example 1:** **Input:** num = 38 **Output:** 2 **Explanation:** The process is 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 Since 2 has only one digit, return it. **Example 2:** **Input:** num = 0 **Output:** 0 **Constraints:** * `0 <= num <= 231 - 1` **Follow up:** Could you do it without any loop/recursion in `O(1)` runtime?
A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful.
Math,Simulation,Number Theory
Easy
202,1082,2076,2264
200
okay think we're recording hey guys what's up Nick white here I do tech and coding stuff on twitch and YouTube so check the description and I'll have everything that you need to know right now I am doing leak code series where I just explain all the problems while I do them because I'm you know I'm doing myself studying right now we're doing this questions called number of islands and I was doing it in the explore page on leak code really cool this is a really common I was actually asked this in a Twilio interview which is I literally recorded not an interview but of the hacker ranks and I have that on my page if you wanna check that out but I don't I didn't solve it so here we go this is what the question is basically it wants to know how many islands are in this grid we're given a grid of chars so a char grid right and the characters are 1 or 0 and we want to find the number of islands in an island is a string of ones connected horizontally or vertically right so this is one island because all of these ones are connected horizontally and vertically but you know this is its own island and this is a separate island because these are diagonally to each other and they're not connected horizontally or vertically and then this is its own Island too that's why there's three islands here because these are horizontally connected this is its own little island and then these are this is its own little island because it's just the vertical and horizontal connections like I said one more time right diagonal doesn't count so it says yeah an island is surrounded by water one is lands here with water and formed by connecting adjacent lines horizontal and vertical you may assume off the grid or surrounded by water find the number of violence right so this was a little confusing at first for me but uh you know it makes sense you basically want to use breadth-first search to figure to use breadth-first search to figure to use breadth-first search to figure this out and what we do is we have our initial count is equal to zero right so this is going to be what we returned the number of islands and we loop through this is a 2d grid so we have you know each element is a row of it char's and so first thing we want to do is we want to do in size zero I is less than grid dot lengths to get into each row of the 2d array and then we're going to want to do inch J equals zero and J is less than grid of I dot lengths to get the columns right you know just that's just how you live through a 2d mate like array or matrices or whatever matrix or whoever just through the rows so we can get the row by index and then we go through each actual element so this so now we're going through each element and what we want to do is if we see a one as we go through then we want to what we're gonna want to do is we're gonna want to see a 1 and then we're gonna want to you know find the whole island structure of that one so we do a breadth-first search and we turn every breadth-first search and we turn every breadth-first search and we turn every single one that we see into a 0 so we go horizontally and vertically through all connected ones so we go through the whole island once we see it and we turn all the ones into zeros so that it's like and we increment the counter by one so it's like we see the island we see a one we explore all the other ones we turn everything to a zero so in this case everything would be a zero in the island count would be one and then we didn't see any other ones so there we go that's what we would return in this one we would turn all of we would see this one right away we'd find all the ones connected to it horizontally or vertically turn them all the zeros so these would all be zeros now and then we would keep going and so the counter would be one we would keep going and then eventually we would see this new one we'd check for you know horizontally and vertically adjacent ones to find the rest of that own in this case there's only one so we explore everything that's easy it's just one element so we add one to it now it's to the counters too and then finally we get to the last row and we see these two and that's pretty much it so you know let's implement the rest of this really quick so into IJ is equal to one so if we see a one as we go through then we'll do call BFS you can call it whatever you want this is the method we pass in our grid we pass in the position we saw the one that you in using the I and J and also we want to increment counter because once we see a one we know that we're we've found at least one island and then at the end of this whole loop we're going to return count which is going to have the number of islands but all we have to do now is implement this BFS method so public void call BFS and this can be implemented a few different ways but you know I like to do with the way that I'm going to do it right here into ICU taking what we passed in right the position in the grid so first thing what I like to do is I like to do the boundary checks or it away so some people like to do this differently you can use math you can do a few different ways to do these boundary checks but I just like to do it right away so if I is less than zero over I is greater than or equal to grid dot length or J is less than zero or J is greater than or equal to this is the trickier part you just have to make sure you do grid of I dot length because you know we have to check the number of elements in each row and then or if we made a mistake somehow or you know we're going to be doing recursion so we do have to do this check or if grid of I've J is equal to 0 and not equal to 1 like we would have wanted then we do return and this is basically gonna break us out of the method when we do the recursion otherwise literally all we have to do in this method is set like I said we're setting the element so we see a 1 we call this and then we do this boundary check to just make sure we're not going out of bounds and stuff so we see a 1 we call this and then we turn that one so this would be the position that we see the one we pass in the position on the grid we set the one to a zero so the first thing we would do we would see this one we'd set it right to a zero then we do the recursive calls passing in grid IJ four times now and since this is the only that's gonna fail accidently had some I put since all we have to do is check the up down left and right positions because the islands are vertically and horizontally adjacent we just want to do so I plus one because the I is the row number I minus one and then we want to do left and right so J minus 1 and J plus 1 and that should be it that's how that's all you have to do is recursively do a call and make sure that you have the syntax right and type everything right that was a semicolon instead of an or but yeah it should actually work yeah so success it works maybe I'll go through it one more time really quick before I end this video so yeah it works you want then we want the number of islands in a 2d grid you do the double for loop so you're going each position at a time once you see a 1 we explore all the ones in one single island we increment the counter each time we see an island and we turn all the ones in that island to a 0 so that we can't see them again it's gonna fix everything you do the boundary check right at the beginning there's a few ways to do the boundary check maybe look up other implementations of it you set the current element to 0 and then you do the recursive calls on the row before the row after so the up the position above the position below and then the position is left in the position to the right using the I and J index indexes so yeah that's the first medium problem we did on the channel maybe it's not even considered a medium problem really I'll give it a thumbs up but yeah thank you guys for watching there's probably more complicated versions of this I think and we'll be doing those in the future so thanks for watching let me know in the comments what you think maybe I can explain these butters in the future but thank you for watching and appreciate it see you in a bit
Number of Islands
number-of-islands
Given an `m x n` 2D binary grid `grid` which represents a map of `'1'`s (land) and `'0'`s (water), return _the number of islands_. An **island** is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. **Example 1:** **Input:** grid = \[ \[ "1 ", "1 ", "1 ", "1 ", "0 "\], \[ "1 ", "1 ", "0 ", "1 ", "0 "\], \[ "1 ", "1 ", "0 ", "0 ", "0 "\], \[ "0 ", "0 ", "0 ", "0 ", "0 "\] \] **Output:** 1 **Example 2:** **Input:** grid = \[ \[ "1 ", "1 ", "0 ", "0 ", "0 "\], \[ "1 ", "1 ", "0 ", "0 ", "0 "\], \[ "0 ", "0 ", "1 ", "0 ", "0 "\], \[ "0 ", "0 ", "0 ", "1 ", "1 "\] \] **Output:** 3 **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 300` * `grid[i][j]` is `'0'` or `'1'`.
null
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
130,286,305,323,694,695,2035,2103
83
hey what's up guys think white here are you Tecna coding stuff on twitching YouTube check the description I do the premium Lea codes on patreon and then join the discord I try and respond to everyone I just did a problem harder than this one I didn't even notice that this was a problem I didn't do remove duplicates from a sorted list given a sorted linked list delete all duplicates such that each element only appears once so you're given the head node of a linked list the node structure looks like this so each node has a value in the next node so you get the head of the length list like one and it points to one in a points of two there's if there's duplicates we want to erase them and only have one instance of each number so there's two ones so we just want to return one two there's two ones and two threes in this so we just want one two three pretty straightforward this is a lot easier than the one I just did I think I just did removing nodes of a specific value but this one is just you set a current node equal to the head node and I don't know if you guys know how to delete nodes but um it's just a leading nodes basically so you set it to the head node you do a loop and you will say while current node is not equal to null this is the main condition I guess if you're having it if you're struggling with this is the main condition you want to understand you get passed in your head node while the head nodes not null and while current node next is not equal to null and this is just the basic traversal usually is a while loop with just this condition but we're also adding while current node dot next does not equal a null so that we can check the value of the next node and we want to check the value of the next node because while we traverse we want to see if the current node is equal to the next node and if it is we want to skip over the next node if that makes sense so if current node dot next I'll is equal to current node dot Val or the other way around you could write this however you want that means that our the node that we're currently at in the traversal is equal to the next node so that's a duplicate so what we want to do is we want to set current node next equal to current node dot next and what this does is it gets the next nodes next value and sets it to the current node next value which will basically just skip over the next node we set the reference for our current nodes next node to be two away instead of just the next node so that's pretty much it if it's not a duplicate so if the current node is not equal to the next nodes value then we just do a regular traversal so current node equals current node dot next and at the end of it we can just return head because we head is fine it's still the head of our linked list we did we had current node go out and do all the traversal work and deletions and you know all that junk any moment now any moments unless the Wi-Fi is down any moments unless the Wi-Fi is down any moments unless the Wi-Fi is down there we go all right there we go thank you guys for watching very straightforward I don't know if you don't understand how to delete things but I mean just look at this line this was the whole deletion next node to the next node so if it's five six seven one more time really quick I don't know how to explain really basic stuff that well this is the current node while we traverse we just go no node but we're also checking is this equal to the next nodes value is the current node dot next val is this soup is the current node done next Val this Val equal to the current node Val yes okay then we set this current node dot next so we set this arrow to the next nodes next err whatever that's pointing to so he said this arrow to the two instead so we just lose reference to this node we just set the reference from this one's next to this one all right thanks for watching appreciate you guys love you guys thanks for all the support on all my videos and yeah let's keep going here on a roll today alright see ya genuine trying to get genuine
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,980
hey everybody this is larry this is me going over q2 of the weekly contest 255 find unique binary string hit the like button hit the subscribe button join me on discord let me know what you think about this problem whatever problems you like to do and if you're here after the contest then definitely check me out because we're gonna we usually talk about the contest right afterwards but for this problem um basically you can just first try put everything here in the set and then boot first looking for it right um because at most you know that there are n uh and unique binary strings that means that at most you're gonna do n plus one checks because of the pigeonhole principle so from that's pretty basic um given that n is at most 16 that's only 16 checks so i wouldn't worry about it um if you want to really analyze about the worst case you can think about uh let me go over and think real quick i mean a lot of this is just weird code-ish in a lot of this is just weird code-ish in a lot of this is just weird code-ish in that um but it should be okay um in that you know like i just here i converted from base two to um you know i could convert the binary string into a number and then put it in a set here i just pad for leading zeros and this is literally um you know for x from 0 to 2 to the n we check with x is in the set if it's not then we return it which is what the problem has to do again this does that most like n which is or n plus 1. so 16 or 17 checks so it's going to be fast enough i wouldn't worry about it if you do want to have you know if you want to think about worse cases that uh and instead you want to play around with randomized algorithms this is actually a fun problem to try it for because it will actually give you a better average response if you had a knowing adversary like if someone knew your algorithm then here you would get the worst case every time but if you use a random thing then you can actually get it a better expected case um play around with that math play around if you like um but yeah uh am i good here i think i am good here so yeah so what is the complexity of this like i said this is o of n i guess because uh maybe n squared you want to call it that where n is only 16 because this check requires a linear ish lookup but this is a constant or this is a linear lookup but the length of it can be linear in terms of n i don't know so this is o of n or o of n squared but now you want to phrase it um yeah that's all i have for this one you can watch me sub it live during the contest next okay um and so weird okay fine um this is not quite right because of the prefix i forget how to do it hey uh yeah thanks for watching hit the like button to subscribe and join me in discord hope you all have a good rest of the week uh stay good stay healthy uh and to good mental health i'll see you later bye
Find Unique Binary String
faulty-sensor
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "00 " would also be correct. **Example 2:** **Input:** nums = \[ "00 ", "01 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "10 " would also be correct. **Example 3:** **Input:** nums = \[ "111 ", "011 ", "001 "\] **Output:** "101 " **Explanation:** "101 " does not appear in nums. "000 ", "010 ", "100 ", and "110 " would also be correct. **Constraints:** * `n == nums.length` * `1 <= n <= 16` * `nums[i].length == n` * `nums[i]` is either `'0'` or `'1'`. * All the strings of `nums` are **unique**.
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
Array,Two Pointers
Easy
null
63
in this video we'll be going over the bottom up approach of unique paths 2. let's go over the dot process so we'll be converting the memorization approach to a bottom level approach now where do we start in the memorization approach we have cached the current row and column with the number of the unique paths this means we can create a 2d matrix paths to keep track of the unique paths for all combinations rc to keep track of the unique paths for all combinations of rc now with as itself what are the default values inside the paths matrix so when rc is out of bound or contains a1 which means it's obstacle then the number of paths will be equal to zero then when rc is at the bottom right corner then we have found one possible path the number of paths will be equal to one let's go over the pseudo code so we're going to create a 2d matrix paths to keep track of the unique path for all combinations of rc then we're going to iterate through from n minus 1 which is the total number of rows to 0. it's going to denote it as r uh this means the last row then when it iterate 0 from n minus 1 the last column to zero denoted sc then we'll first check if rc is at the bottom right corner then we can set actually before that if rc if obstacle rc if the current cell contains a 1 that means this obstacle here is equal to one then we want to continue the next iteration which means the path of the rc of the current cell is equal to zero so we can just continue to next iteration because the default value inside the paths matrix are zeros then if rc is at the bottom right corner we can play we have found one possible path so i'm place one at pass rc you can continue to next iteration then if r is not at the last row this means we can move downward so the robot can move downward so we're going to increment the current number of paths by the number of paths of moving downward by pass r plus one which is moving downward then if c is not at the last row all right last column then we can move rightward so when increment pass by the number of paths are moving rightward so r plus one then we can return the paths starting from the zero which is the top left corner the initial starting position of our robot now let's go over to time and space complexity so time complexity is mn where m and n are the number of rows and columns and then this is just an sd4 loop our space complexity is also mn because of the path matrix now let's go over the code so let's first create two variables to keep track of the number of rows and columns which are mn then we're going to create our paths matrix then we're going to iterate through from the last row to the fir to zero so r is going to minus one to zero and i'm gonna iterate through from the last column to zero then if the current cell contains a obstacle the number of paths is equal to zero so they continue the next iteration if r x goes to n minus one and c goes to m minus one that means where we're at the bottom right corner so the number of paths where it's going to be equal to one so past rc is equal to one then we'll continue the next iteration then if r is not equal to n minus one that means we can move downward so the number of paths at the current cell will be incremented by the number of paths of moving rightward uh downward and if c is not equal to n minus one that means we can still move rightward so we increment the number of paths by the number of paths moving rightward and then return the number of paths starting from the top left corner or initial starting position of a robot let me know if any questions in the comment section below
Unique Paths II
unique-paths-ii
You are given an `m x n` integer array `grid`. There is a robot 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. An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle. Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The testcases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** 2 **Explanation:** There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right **Example 2:** **Input:** obstacleGrid = \[\[0,1\],\[0,0\]\] **Output:** 1 **Constraints:** * `m == obstacleGrid.length` * `n == obstacleGrid[i].length` * `1 <= m, n <= 100` * `obstacleGrid[i][j]` is `0` or `1`.
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] else obstacleGrid[i,j] = 0 You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem. if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j] else obstacleGrid[i,j] = 0
Array,Dynamic Programming,Matrix
Medium
62,1022
502
um hello so today we are going to do this problem which is part of lead code daily challenge IPO um so what this problem um says is basically suppose lead code is going to IPO soon and we want to sell a good price of its shares to VCS um essentially you can ignore all of that but basically we have some projects that the gist of it that where we want to increase our Capital as much as possible using this project and these projects each have a profit right and once when we do a project we get that profit and that profit each project also has a minimum capital that we can't do that project unless we have that capital um now one weird thing about capitals for this problem that you need to pay attention to is that if you have capital and you do a project let's say this one you don't actually consume one Capital so you don't subtract this value from your overall Capital value um this is just how they laid out the problem so you only add the profit of two let's say your Capital was zero and you do the project at index one you would add two to your Capital overall Capital but you want um you won't subtract this one now you can in this specific case because the initial capital is zero you can't start with this one because it's bigger than the your current total available Capital right so this array of capital is only used to make sure that you um you do a project only if you have enough capital for it right so that's the distinction there now you can do at most K distinct projects um and the goal of the problem is to maximize the final Capital we have right so we have two for example in here we have we can do at most two projects initial capital is zero and these are the profits in the capital of the project and so we with the constraint that we can't do a project unless we have enough Capital uh we CA the only one we can do here is the first one because it has capital of zero we can do these two because uh they require at least one capital of one okay so once we do the first one um we get a profit of one so our capital is now one and now we have the choice to do one of these two now in this case which one is better well we want to maximize The Profit so we should take the one with the highest profit and so that's three here okay um and so the total would be uh First We Take the profit of one and then we take the profit of three and we stop because we have only two projects to take right so that would be zero plus one plus three and this is the final profit we take okay so that's roughly the idea uh now let's see how we can solve it take the first example we start out with the initial capital of zero and so initially the only one we can take is the first one right because we can't take these two and so you see that constraint that we can take these two so that is already the constraint of we take only if let's call the current capital right and so we can take only if C value is small or equal to Capital okay so we have that constraint there and so let's say we take so we take the first one so we take zero here and now our capital is going to be equal to The Profit because we add the profit so value of one okay so now we only have these two remaining and we choose the highest profit right so here it happens we have two so it's easy but if we have a lot more five or six we want to add them to some in some way to something so that we can pick the highest value and whenever we have that we need to think about using a priority queue right the other problem is what if we because of the capital we have we had to skip so let's say for example we have these two um these two uh these projects so let's say our profit are and our capital is first we have maybe two uh three two and then we have here zero one two and then the projects let's say we have three two three and then for this one we have maybe three right and then here it doesn't matter four two right so let's say we have these projects here now we start out with capital let's say equal to zero so our Capital first is zero so what happens we only can take this one so we have to take this project so we take it we get profit of three so now our capital is three okay and so now the which one we take right um we need to keep track of all of the ones we can take right because we can now we can take this one because our capital is three we can take this one uh sorry actually um we need the capital to be smaller than three so we can take this one so we can take all of them but we need to organize them by um by uh profit right and so we need to do two things first for the initial Capital we need to sort the capitals by we need to sort the combination by Capital so that we can get the smallest Capital because that one has the highest chance of being smaller than our current overall Capital right and so we need to First sort by Capital right but in that list right we want to store all the profits that are smaller than the current capital so that we can pick among those we can pick the maximum one right and so what do we need for that we need a um let's call it a priority queue right by profit okay and this one will contain only those that have Capital smaller or equal to our current capital value and if we do this we should be able to solve the problem right um so let's actually run on an example here so let's run to end this simple one first okay so with this array our capital is going to be initially zero so first we want to sort the pair right and so let's call this just um let's call it uh P because it's going to be a combination of both so we would have Z one zero for the profit in the capital and then 2 1 and then three one okay and now we want to sort it by Capital right um here it happens that it's sorted by Capital so we are fine and then we want to go through them and we want to fill the priority queue as long as it's smaller than the capital we have right and so what we do there is um we get the first one right and then we add it to our since it's smaller than the Capital we have or equal to the capital we have which is zero we added and so now we have in our priage view we only need the profit we no longer the capital will only use it to check so we only need to add the The Profit so we add the profit which is one and now we stop because the next one is bigger than the current capital so the ones after that would be bigger because this one is sorted so we just stop there and now we look at our priority queue and we add that value to our Capital so our capital is now equal to one okay and we remove it right because we added to our Capital so now our period queue is here and now we go again to our list of um list of projects and we check is this smaller than the capital we have yes so we added our periodq we want to add only the profit so two and we'll check this is this one smaller or equal yes so we add the profit there as well and now we go through the priority queue and pop the highest value so we pop three so we have POP3 we added now our capital is four but remember we want to do this only for at most K distinct project and so now since we added two we stop so we do it only 4K projects so that's roughly the idea sort by Capital first and then each time for each Pro for each project we want to pick check the ones that are eligible add them all to a queue and then pop only the one with the highest value and then do the same again right okay so that's roughly the idea here now let's implement it and make sure it passes test cases um okay so let's Implement what we saw in the overview so what we need first is we need a sorted list we said for um profits and capital so this is would be our projects and we want to sort it by so this would give us a pair of the profit in the capital right and so we sorted what do we want to sort it by you want to sort it by capital and so for that we want to use a key because that's not the default sorting and so what would be the one we sort by its capital which in a pair of profit and capital it would be in position one and let's call these projects right now each time what we do is we just get the first element so we get the we can have definitely like a an index right so let's say we have in our case Zero we had two one in the example we saw so we can have an index that just keeps track of where we stopped at but other it's easier actually to just have a DQ so that we can pop from the beginning so we'll pop this one once we process it and then we pop this one once we process it that way we don't need to maintain an index so that's actually what we can do here we can just pass this to a collection DQ and this will give us the ability to pop from the front okay so now um after that what we need to do is um we just need to have the initial Capital set to w and we need our priority queue that we will add eligible project two and so let's call that pre-altq let's call that pre-altq let's call that pre-altq and now we want to do this we want to only k at most K projects so we want only um okay the only caveat here is what if K is bigger than the number of projects we have let's say k is 4 and the number of projects is three what we want to do in that case well in that case we want to take only three because if there are no projects we can't take them the problem also says at most K and so an easy way to solve that is just to say k is equal to the minimum of K and the length of the price the number of projects which is just the length of the profits so that would be it would solve for that case um and now what we want to do is basically add all eligible projects to a queue right so um to a priority queues so that we can take the highest profit because we want to maximize The Profit but we also want to maintain that we can't take more than the capital we have and so to do that so while we have project of course and the project in the front which we want to check the capital of it which is at position one so for example here we want to check let's say when we had one zero two one we want to check that this here is smaller equal to the capital before popping it off so we check if it's small or equal then we want to add it to the list of eligible projects so it's actually called this eligible because that would make it more readable and so here we want to add it but because we want to get the highest profit value we want to make it a priority queue and add here just the profit value and so that would be just projects we want to pop the front now and so this will give us the pair and we want to take the profit value which is at position zero here so that's what we'll take let's call this for readability project um and let's just take the profit of it right or we can even say this is profit and capital and then just take the profit here okay so now once we push that what we need to do next is if there is there are eligible project we want to take the highest one as the this projects right we want to do it only K times and each time we take one project okay so here we when we take a project when we do a project we add the profit and the profit is just the hip queue we want to pop the highest profit value so that would be just among eligible ones um and then at the end we want to return the final capital okay um yeah so here just to make sure we don't override this list value here let's call this C and let's call this P now one thing to note here is that since this eligible here in Python is going to be by default A Min queue so by default if we add just the profit value as it is it's going to give us the smallest one so we want to get the maximum one so we just add minus so that the smallest one is actually the highest one and when we want to add it here when we pop it we want to put minus one in front right so that's just for python to get a Max Heap and now if I run this looks good it passes out those cases now let's add the minimum taking them in and this pass is fine right cool so that's pretty much it for this problem um it's a pretty good application of prioritq um yeah please like And subscribe and see you on the next one bye that should be it also on this
IPO
ipo
Suppose LeetCode will start its **IPO** soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the **IPO**. Since it has limited resources, it can only finish at most `k` distinct projects before the **IPO**. Help LeetCode design the best way to maximize its total capital after finishing at most `k` distinct projects. You are given `n` projects where the `ith` project has a pure profit `profits[i]` and a minimum capital of `capital[i]` is needed to start it. Initially, you have `w` capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of **at most** `k` distinct projects from given projects to **maximize your final capital**, and return _the final maximized capital_. The answer is guaranteed to fit in a 32-bit signed integer. **Example 1:** **Input:** k = 2, w = 0, profits = \[1,2,3\], capital = \[0,1,1\] **Output:** 4 **Explanation:** Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. **Example 2:** **Input:** k = 3, w = 0, profits = \[1,2,3\], capital = \[0,1,2\] **Output:** 6 **Constraints:** * `1 <= k <= 105` * `0 <= w <= 109` * `n == profits.length` * `n == capital.length` * `1 <= n <= 105` * `0 <= profits[i] <= 104` * `0 <= capital[i] <= 109`
null
Array,Greedy,Sorting,Heap (Priority Queue)
Hard
null
1,953
all right trying out this problem uh maximum number of Peaks for which you have to work that's our reader so there are amp projects and each project has certain number of milestones and there are two conditions every week we finish exactly one Milestone of one project and you cannot work on two miles from the same project on two consecutive ways so every week we basically complete one Milestone and in consecutive weeks we can't work on the same project and once all Milestones of all projects are finished or if the only Milestones that you can work on will cause you to violate travel rules you will stop working okay so we have to essentially find out the maximum number of Peaks that we can work so let's look at the examples one two and three so uh one two and three is essentially the first project has only just one minus one second because it is two Milestones Third Rate is three milestones so three and then two and then one right so and so this is how I will work I first I'll complete first week I'll do one iPhone three then I'll do one Milestone of two and I'll do one Milestone of one and I'll do one Milestone of three then one minus one or two and one minus one of three and uh so this is how I am going to do so three two one three two three and I'll be able to complete all of them all right moving on to the next example five two and one so five two and one that means the first project let's call it X um I'll be able to order one as five one something like that second project has two and the third project has one milestone now in this case how many weeks I can work for so the remaining uh I could do something like a like so if I follow this uh I am taking this three I can put here like does it matter so one is I can do one two three one two one otherwise I could if I put this three uh let's say here so I could do one two one three one right here so one generation that we are getting is one thing that depends upon is the project that has the maximum number of milestones it's the remaining projects so maximum let's call it m and remaining let's call it r right so now what we'll want is f remaining so if I can fill this is the remaining or less than or equal to um so few minutes okay let's take an example something like 222 we know that nothing will be more than one so three and that's enough for whatever no sorry so four and if there is a five I'll do that five here okay so five and then um some more whatever but the idea is if you're remaining but if in this in a case like this and let's adjust this so if remaining is less than basically I will be able to complete all the work if this remaining is greater than or equal to Max minus one so the meaning is the scenario so that in this case I can do all because one two but if this is the case then I can only do one two one and I will I'll be missing this out this last one so the remaining is for the remaining elements are less than or equal to Max minus 1 then I'll be able to complete everything else I'll be only able to complete depending upon how much remaining is so in this case I'll be able to compute this and an extra this right one two one so else I'll be able to complete so in this case I'll be able to complete all and in this case I'll be able to complete two times r uh plus one right that's the general idea so that's quickly put it up so uh let's have sum as 0 Max as um nuts and strategy this and for each milestone equals to sum plus milestone and Max equals to math.max of Maps so now what will be remaining so remaining is some minus Max and our condition is if remaining is a minus 1 or more then I will to compute all the milestones otherwise I'm only able to complete two times remaining plus one all right let's submit and see if it works all right this is Max and it works
Maximum Number of Weeks for Which You Can Work
finding-mk-average
There are `n` projects numbered from `0` to `n - 1`. You are given an integer array `milestones` where each `milestones[i]` denotes the number of milestones the `ith` project has. You can work on the projects following these two rules: * Every week, you will finish **exactly one** milestone of **one** project. You **must** work every week. * You **cannot** work on two milestones from the same project for two **consecutive** weeks. Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will **stop working**. Note that you may not be able to finish every project's milestones due to these constraints. Return _the **maximum** number of weeks you would be able to work on the projects without violating the rules mentioned above_. **Example 1:** **Input:** milestones = \[1,2,3\] **Output:** 6 **Explanation:** One possible scenario is: ​​​​- During the 1st week, you will work on a milestone of project 0. - During the 2nd week, you will work on a milestone of project 2. - During the 3rd week, you will work on a milestone of project 1. - During the 4th week, you will work on a milestone of project 2. - During the 5th week, you will work on a milestone of project 1. - During the 6th week, you will work on a milestone of project 2. The total number of weeks is 6. **Example 2:** **Input:** milestones = \[5,2,1\] **Output:** 7 **Explanation:** One possible scenario is: - During the 1st week, you will work on a milestone of project 0. - During the 2nd week, you will work on a milestone of project 1. - During the 3rd week, you will work on a milestone of project 0. - During the 4th week, you will work on a milestone of project 1. - During the 5th week, you will work on a milestone of project 0. - During the 6th week, you will work on a milestone of project 2. - During the 7th week, you will work on a milestone of project 0. The total number of weeks is 7. Note that you cannot work on the last milestone of project 0 on 8th week because it would violate the rules. Thus, one milestone in project 0 will remain unfinished. **Constraints:** * `n == milestones.length` * `1 <= n <= 105` * `1 <= milestones[i] <= 109`
At each query, try to save and update the sum of the elements needed to calculate MKAverage. You can use BSTs for fast insertion and deletion of the elements.
Design,Queue,Heap (Priority Queue),Ordered Set
Hard
295,789,2207
927
hey what's up guys uh this is chung here so it's been a few days um yeah i had some back pain after overdoing um on the rowing machine so anyway so uh i think this one is today's daily challenge problem uh number 927 three equal parts um so this time you're given like an array which consists only consists of only zero and once right and now this time we need to divide uh this array into three empty parts such that all of the parts uh represents the same binary value right so basically you and we need to return those two separated separate index right so basically the i and j such that you know so we have array here right and we need to separate uh divide into three parts and we need to return i and j so let's say we have i in here right and j is here so if we have i and j here so we divide this array into three parts the first one is the this part the second one is from i plus one to j minus one right which is this part right and the last one is from j to the end right so that's the uh that's the three parts we want to what we want to return here right if it's not possible return is minus okay and so for example this 1 0 represents 2 8 to 6 right also the leading zeros are also allowed right basically the 0 1 is equal to 2 4 so this is okay so for example we have the 1 0 1 and the output 0 3 right so because uh we divide it into three parts right the first one is zero which is this part right and then the second part is this one here that's why we have zero and three right based on the definition here right so and then this one it's not possible right because you know i think one of the observations that you know the number of ones right has to be divided by three right because in order for us to get like three equal parts you know all three parts should have the same number of ones right so obviously this one is not it's four right that's why i know this is not possible and this one is two this one is possible right obviously so we can divide into this one and uh from here and here right so that's the this is the three part because you know be careful so because here you know we cannot divide it at here because you know otherwise we'll have one two and one right that's why i know we can we have to divide it in this way that's why we have 0 and 2. and so that's the that's all the examples here and the constraints is like this almost 10 to the power of 5 right uh obviously you know given like this big uh this constraints scale we cannot brutal force it which means you know we have basically we try to find all the possible three divisions right that will be like n squared right uh sorry not n square an n cube right that this will definitely tre right so which means you know given this uh string uh constraints here we cannot even do n square we have to e we have to find like a better one either o n or n log n right so for this one it's possible to have o n and y side i think we already uh on that path right so the first one is that you know we have to so each part right so each part let's say we have three parts here each part has to have the same number of ones right so that's the first one and the second part is that is what uh the second observation is that you know the zeros in between them has also has to be the same right because we already know let's say we have this one we have three ones right let's see that in total we have nine ones but and then the second part the observations we need to make is that you know each uh between each one right they have to be there has to be the same number of zeros right for example you have zero here and zero here right so this part has to be the same right zero and zero right here has to be the same zero and zero if any parts have let's say if they're like a more zeros in between this is okay you know because we can always split the uh we can always split the array uh in a way that you know we can include some leading zeros the only exception exceptions that you know the part three right to anything that after part three basically in part three uh if we have more zeros here those zero has to be counted in the last part right third the uh for the part one and part two if we have more zeros here you know it's fine because you know leading zero is a lot that's why we can somehow cut this uh move this uh index around but for the last one you know we have to count everything uh all the zeros in the lot in the last part okay so what we can do is that you know okay so first we know if we count the total number of ones we already know that you know uh we can have like the index uh for each of for the first ones in each part right so which means let's say we have p1 pointing to here right so basically i'm going to have like three pointers the first one is just pointing to the first ones right and then p2 pointing to what p2 pointing to the first one of the second part and p3 pointing it points to this the first one of the third part right so and then what can we do so obviously you know as you guys can see basically we since we already know the p3 that's why you know we already know what's the value for the last part right like i said we have to count everything after this p3 that's why you know what we can simply do is that we can simply move these three pointers all together and then we compare the bit value one by one right so which means that you know so and as long as there's a case that any values right any part of any part any value in each part that's not equal to each other then we can simply return minus one right only when and when everything's are the same until the p3 reaches the end of the rate and then we know okay we have find a split and what would that split be right so let's try to simulate this one okay so in this case we have p1 p2 and p3 right you know for example if we have like if we have another zero here right for example if we have two zeros in between right obviously this one is going to be a false right because it's not equal that's why because when we try to move this p1 p2 and p3 so p1 equals to p2 equal to p3 right so next one is zero and zero that's fine but the third one so right so one but this one is zero right it's it should be one that's why you know for example in this scenario we're gonna return like minus one right so if everything works fine right so we have one and zero one zero right everything works fine and at this moment and we have another two zeros in the end that's why we have to move uh two more zeros right and now the p1 is here right and then the p2 is uh it's pointing to here right and then p3 is pointing to here right so this one still uh is are still the same right and then the next one is that we're going to move p3 so now p1 is pointing to here right and then p2 is pointing to here right and then p3 will be basically pointing to the end of the array right and that's when we can say okay we have find a split right because we have already compared each of the numbers right each of the bit value so at this moment so what will that split be right so now we have it's going to be this one right so that's this is the first part okay how about second part is it's this one right second part is this part right and the third part is what is this one this is the third part right because you know so here you know since we can only we have to split this array into three parts right that's why you know the leading zero the leading zeros are fine right but we but the prefer for the first part we cannot include more zeros than it then it didn't need right which is three uh zeros in the end because you know the last part we only have like what zero one zero right that's when we need to stop okay and so what's going to be the value here so remember so the first part is the p1 from zero to p1 minus one right so this is the first part that's why you know what we need to return is that p one minus one and then p two right because p2 right so the definition of the second index is that from p1 to p2 -1 right that's exactly what we need -1 right that's exactly what we need -1 right that's exactly what we need here and the last part is from is p2 to 2n right that's why you know we just need to return p1 minus 1 and p2 right so i think that's basic that's the basic idea here and cool i think we can start coding then right um so first step is to count the number of ones right count of one right and if ones uh cannot be divided by three right we simply return oh let's define like uh minus one okay it's going to be the default uh re result right so we can simply return the answer right and then we have the target right so the target will be the ones divided by three right so now we have all the targets and let's try to populate the pointers right the three p one p two and p three it's gonna be zero i'm going to maintain like count for now and so for i can enumerate numerator of array right so how can we find those p the starting point of p1 p2 and p3 right so if num is equal to one right if count is equal to zero and then p1 is going to be i right i'll see if count equals the target right and then p2 equals to i uh how's if count equals to 2 times target right and then p3 equals y right and then don't forget to increase the count by one okay then we have length of the array here so now we have the p1 p2 and p3 right so all we need to do is that we just need to simply try to remove the all three pointers together and then compare the values for all three uh pointers right until the p3 reaches the end right so which means that you know well p3 is less than n right but before doing that we also are going to have like the p1 smaller than p2 and the p2 smaller than p3 right uh i think here um since you know we'll be moving p1 p2 and p3 all together i think this part uh we have to you know make a copy right of p2 and p3 right so this part is make sure you know uh the p1 p2 and p3 will not cross over each other because you know for example if we have one zero and let's say one zero right so p1 starts is here p2 is here p3 is here right so p1 should never be should never uh cross over p2 same thing for p2 and p3 right p2 should net should never cross p3 right that's why uh let's um let's do a p two equals to p2 i know the name uh original old p2 how about this one hold p3 okay so basically we should use old p2 here and old p3 here right um so we check if the p p1 does not equal to p2 right this or the p1 does not equal to the p3 right so if any of them are not equal we simply return the answer right which is the uh with this minus 1 and minus one right else what else we do uh we increase p1 p2 and p3 right plus one okay and then in the end uh we simply re check this right we simply we return like i said p one minus one dot uh p2 if p3 is equal to n right else the answer you know this one uh i think the answer seems weird here okay i'll just use this one to represent that so i think this is better right so basically in the end we simply check right simply check if the p3 has reached the end right if it is then we return this uh this split otherwise minus one that's for example this one right even though everything here works fine but you know once this while loop is finished right uh because it will stop before when the p1 reaches p2 where p2 reaches p3 right but at this moment the p3 has not reached the end right that's why you know we cannot find a split because i as you guys can see the path part three is one zero right this is a it's a pretty big number that's why we check this one in the end only when p3 is equal to n then we know okay we have five we have find a split and split is p1 minus one and p2 right and i think that's it right so if i run it okay so this one accept it if i run this one oh sorry there's a corner case which is all zero right um yeah with all zero as you guys can see right uh i'm returning minus one because yeah because p1 equals to p 2 equals to p3 right and okay i think we can simply do this right we can simply check that in at the very beginning right basically if uh here right easy if once equals to zero right so if everything is zero uh what does it mean it means that we can split at any location right uh i think the easiest one is just to split basically i is equal to 0 and j is here right that's the i think we can just return this return like zero and two right because again right so the split is a little bit different so the first part is from i and the second part is from i plus 1 to j minus 1 that's why the second part the me the smallest index for the second part is 2 right that's why has to be 2. right actually no this one can be anything right but since the uh the length of the rate is at could be three right that's why you know we can use this zero two and this should always work and i think that's it right so now if i run it again yeah so now it passed right um yeah as you guys can see right so we have what so this is all often right to count once and here is what it's also like all often right so it's also often to find the pointers right and then the last part is this while loop since they're all the pointers always moving forward right so this part is also often right so in total this is all of n time complexity right and space complexity is of one i believe right so we only use uh limited number of the variables right uh ones p1 p2 and p3 and target right um yeah i think that's it right so for this one um not too difficult the only thing we have to be um insightful is that you know we have to be re we have to realize that you know the last part oh first is that you know each part has to have the same number of ones right so that's not too hard to get right and the second observation is that you know the last part is the most important part because starting from this one starting from the first one of the third of the last part to the end everything has to be considered that's why actually we're kind of using the last part right to check if we have already find the split or not and the last thing is that we just simply compare right all the uh starting from the first one to the end we compared the bit one by one right to make sure they're all equal to each other that's how we make sure all three parts are the same have the same binary value right because you know to be able to have same binary values you know each bit has to be the same right basically if the value is it's six right it means that it has to be one zero right basically we have to have one and zero it cannot be anything like one zero one or one zero right at the as long as the one bit are different then the value the final result will be different right that's why we can compare the beat the values beat by bit right to make sure all three parts are the same uh yeah i think that's it for this problem i'll just stop here then okay thank you for watching this video guys and stay tuned see you guys soon bye
Three Equal Parts
sum-of-subsequence-widths
You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value. If it is possible, return any `[i, j]` with `i + 1 < j`, such that: * `arr[0], arr[1], ..., arr[i]` is the first part, * `arr[i + 1], arr[i + 2], ..., arr[j - 1]` is the second part, and * `arr[j], arr[j + 1], ..., arr[arr.length - 1]` is the third part. * All three parts have equal binary values. If it is not possible, return `[-1, -1]`. Note that the entire part is used when considering what binary value it represents. For example, `[1,1,0]` represents `6` in decimal, not `3`. Also, leading zeros **are allowed**, so `[0,1,1]` and `[1,1]` represent the same value. **Example 1:** **Input:** arr = \[1,0,1,0,1\] **Output:** \[0,3\] **Example 2:** **Input:** arr = \[1,1,0,1,1\] **Output:** \[-1,-1\] **Example 3:** **Input:** arr = \[1,1,0,0,1\] **Output:** \[0,2\] **Constraints:** * `3 <= arr.length <= 3 * 104` * `arr[i]` is `0` or `1`
null
Array,Math,Sorting
Hard
null
252
hey everyone how are you doing today let's check out a nice and easy lead code problem called meeting rooms given an array of meeting time intervals where each interval is basically a pair of start and end times we have to determine if a person could attend all the meetings i also want to mention that if you just started doing problems and aren't sure about how to go forward keep in mind that code forces has a great article about how you can basically guess the time complexity based on the problem constraints it might give you a little advantage and can drive you to the good direction so if we take a look at the input size in this problem the intervals dot length then we can see that it is between 0 and 10 000 10 to the power of 4 which is not a great number and based on the article if you take a look at it you will see that the solution is going to be somewhere between big o of n times log n and n square we're gonna get back to this later so the first example has three intervals from 0 to 30 from 5 to 10 from 15 to 20 and it says that the result is false another important step of getting better at problem solving is to make sketches if you're not sure what you are doing in this case let's try to sketch up the three intervals on a basic timeline so the first interval starts from 0 and goes to 30 the second interval starts at five ends at 10 and the third one starts at 15 ends at 20. we can see that the red interval is overlapping with both of the other intervals which means that this person would not be able to be at two places at the same time so they would be at red's meeting and green meetings at the same time and after that red meeting and the orange meeting at the same time the next example only has two intervals from seven to ten and two to four let's try to sketch these up as well we can see that there is no overlap between these two intervals therefore it is going to be possible so the result is true let's think about a very straightforward brute-force solution we take an interval brute-force solution we take an interval brute-force solution we take an interval compare it with all the other intervals and check for overlaps first examples case we take the first interval and compare it with all the other intervals since there is an overlap we don't have to continue the check but if there wasn't then we would need to go forward and then take the second interval and compare it with all the other intervals the question is do we really have to compare it with all the other intervals because we have already made this check right so in this case we only have to check for the next interval and then we take the last interval and since all the checks were made before we don't have to do anything it is also very important to think about that these are very small examples so if there are multiple hundreds thousands or even millions of intervals it will be very hard to see the overlaps what is the time complexity of checking each pair it will be big o of n square if we refer back to this then we can see that we are kinda getting to the point so for the big o n square solution we are going to need two for loops because we need one for loop for iterating through all of the intervals and then we need another for loop for checking the overlaps if we are in the first interval then we have to check the overlaps for the subsequent intervals if we are on the second interval we have to check the overlaps with subsequent intervals as well so can we do better than this let's try to formulate a logic here if we take two intervals let's say a and b are going to be the start and end time for one interval and then c and d are the start and end time for another interval and we want to decide if there is an overlap what do we need to do we have to check if the end time for the first interval and the start time of the second interval are not overlapping which means b has to be smaller than c if the first interval finished earlier than the second interval started then we know that there is no overlap so we know this do we really need to do this for all of the intervals do we need to check each pair if we know that the start times are in ascending order then we can make sure that we do this check for each pair but we only have to iterate through the list once because you can see that the first example is very straightforward it is already in an ascending order so we can check the start and end times easily but in the second example the start times are not ordered so we can't just check the end time for the first interval and compare it to the start time for the second interval because they are not ordered but if they were like then we could just check the end time for this interval and compare it to the start time of this interval and this would tell us that there is no overlap between these two so what if we want to sort all the intervals by their start time then it will be a piece of cake to look for the overlaps turns out sorting is big o of n times logan time complexity which is better than the original brute force solution and it also refers back to this so let's write the code for this in order to have the logarithmic solution we decided to sort the array based on the start times let's do that and after that we can just iterate through the list and compare the start and the end times we can start from 0 or 1 here it doesn't really matter if you want to check forward or backward i'm going to check backward so what we want to check here is if the current height interval's start time is lower than the previous intervals end time it means that there is an overlap so we can just return false instantly and if there is no overlap we can go forward check the next intervals and if we got to the end then we can return 2 because that means that there were no overlaps the height intervals start time is smaller than the i minus ones end time then we return false otherwise we can return true and that's it thanks for watching i hope this was helpful if you liked the video like and subscribe leave a comment or suggestion it's very welcome thank you bye
Meeting Rooms
meeting-rooms
Given an array of meeting time `intervals` where `intervals[i] = [starti, endi]`, determine if a person could attend all meetings. **Example 1:** **Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\] **Output:** false **Example 2:** **Input:** intervals = \[\[7,10\],\[2,4\]\] **Output:** true **Constraints:** * `0 <= intervals.length <= 104` * `intervals[i].length == 2` * `0 <= starti < endi <= 106`
null
Array,Sorting
Easy
56,253
525
Hello everyone and welcome back to another video of lead code daily challenge so today we are going to solve the problem here ah this is also a problem related to everything which we have already solved so it will be a short video company Talking about tax, it has been asked in facebook's question What is the question saying? Given a binary array numbers return the maximum length of the content sub array with equal number of zeros end once. Okay so you will be given an array with equal number of zeros end once. Once you need to return the maximum length, if you look at this question a little carefully, then look at the question, it is very simple, the question is simply telling you that brother, you must have been given an array, you have to return the maximum length in it, in which there are equal numbers. There are going to be zeros and ones, okay, this is the overall question, okay, if you look here, there is one bar in which there are equal number of zeros and ones, then you will get many such ones, friend, you will get three and three, six, one, this is it. Okay, now if you add these two, then one means it becomes eight in length, but what is our final answer, this biggest one will be visible here. If you start from the beginning and take it till the 11th index, then what is there here? is one 2 3 4 5 6 one how many are six and similarly 1 2 3 4 5 si how many zeros are there six so this length is 12 is your answer ok now what can be the brute force first generate all sub array as many sub array as you Generate as many as you can and check the length of each subbar in which zeros and ones are equal. And among all these lengths, you will have to find the maximum length. What does it mean to say, how will we generate all the subbars? Put the start here, put the end here, okay, so from the start till the end, you will get one sub array which is what is the current one, okay now obviously, in this you make two pointers, make one zero means variable basically. Make one row and one. Okay, so both initialize it to zero. Now what value do you get here? Will go 1 means basically all the Aris are starting from your 's' basically all the Aris are starting from your 's' basically all the Aris are starting from your 's' and keep increasing the 's', this is the and keep increasing the 's', this is the and keep increasing the 's', this is the same logic, we have seen it many times, so now here I got the second one, so I can say how many times I got 's', okay then. If you can say how many times I got 's', okay then. If you can say how many times I got 's', okay then. If you move from and then once you get a row then here 0 + 1 then move forward again g then here 0 + 1 then move forward again g then here 0 + 1 then move forward again g then you get a row again then in row + 1 then you get a row again then in row + 1 then you get a row again then in row + 1 then you can see that the number of zeros and ones is equal this time so as soon as the number Of zeros and ones are equal, take out a length which is upper limit minus lower limit + 1 so 3 - 0 upper limit minus lower limit + 1 so 3 - 0 upper limit minus lower limit + 1 so 3 - 0 + 1 that is 4 Okay where did this formula + 1 that is 4 Okay where did this formula + 1 that is 4 Okay where did this formula come from I have taught this formula in many talks when we go from s to k If we find the length of e in a particular range then there can be three cases in it, okay first case where both s and e are included, both inclusive means that if I said the range is 0 to 10 and 0 and 10 are also included in that range. If included, then how many elements will be there in total? Okay, the formula for this is upper limit minus lower limit + 1. Okay, limit minus lower limit + 1. Okay, limit minus lower limit + 1. Okay, so between 0 to 10, there will be 10 - 0 + 1. 11 so between 0 to 10, there will be 10 - 0 + 1. 11 so between 0 to 10, there will be 10 - 0 + 1. 11 numbers. Count on fingers. Okay, this is done first. Case this is first case when both are exclusive second case what is both are exclusive means you are given s e but the actual range is from s + 1 to k e -1 okay is from s + 1 to k e -1 okay is from s + 1 to k e -1 okay that like I said from ro to 10 If you want to count till but na row or if you want to count 10 then actually I have given you 1 to 9 so what is its formula upper limit minus lower limit -1 correct now what will be the limit minus lower limit -1 correct now what will be the limit minus lower limit -1 correct now what will be the third case then the third case will be yours that Empty a is included i.e. from s to e -1 is ok i.e. from s to e -1 is ok i.e. from s to e -1 is ok i.e. s is included e is i.e. s is included e is i.e. s is included e is not included or what will be the other case s is not included from s + 1 to e but e s is not included from s + 1 to e but e s is not included from s + 1 to e but e is included then What is the formula in these cases and minus start? Okay, so basically I have taught you this many times that if you keep it in mind, it will save you a lot of time while solving questions. So this is a simple trick. Okay, so in this case, as you Can you see that our start and end are both included, which means we are talking about all the air, so I applied the same formula - upper limit minus lower applied the same formula - upper limit minus lower applied the same formula - upper limit minus lower limit + and okay, so we have calculated the length four. limit + and okay, so we have calculated the length four. limit + and okay, so we have calculated the length four. Now similarly, end Keep increasing, you will get new sub array, finally you will get this sub array here, okay, what will you do after that, you will increase s by one step, now all the sub arrays starting from first index and ending, then increasing till the end, similar sub arrays. Starting from the second index and then increasing the end till the end, generate all the sub-arrays till the end, generate all the sub-arrays till the end, generate all the sub-arrays and out of all the lengths, whatever is the maximum length, that will be your answer and how often will you check the length when the number of Zero and once it becomes the same, I understood that the problem with this approach is the time complexity. Now, what is your start, it will run from row to last, and for every start, you are saying that what is your end is that. It will run from the start till the end again, so this will also run n and both are nested loops, so we can say that n is the time complexity space but n is the time complexity space, it will have to be removed, it will have to be reduced, so let us optimize it. A question was asked before this, if you can relate it to that question then it will be solved. What was that question? Find maximum length sub array. Ok, how did we solve this question of off sum? We told him to make a This is the sum of your entire array. Okay, now here at one point I got the sum Whose sum would have been brother, the sum from here to here would be x + k and the x + k and the x + k and the sum from here to here would be I have given you a reference to the same thing, actually I have given it in two videos because it is repeating, this is the third question on the same pattern, okay let's go back to this question now, I just want to know that if I am seeing something similar then it is Has Sum ever happened before in this array of mine and if it has happened then what is its index i.e. if I have to happened then what is its index i.e. if I have to happened then what is its index i.e. if I have to map the sum from the index then which data structure will I use? Hash Map which will be mapped that Sum and Which index did you look at before? Okay, so you can easily keep track of the sum. So whenever you get x + k, you check whether whenever you get x + k, you check whether whenever you get x + k, you check whether x exists in my sub array and if so, then what is the difference between these two. The middle index is my answer Correct now the challenge is how do I fix this k Okay so if you go back to the constraints of this question then you will know that what is there in this array is only zeroes and ones so if an array has only There are zeros and ones so I can bring it to even zero How there are so many zeros Whenever I get a zero What will I do -1 Whenever I get a one What will I do + -1 Whenever I get a one What will I do + -1 Whenever I get a one What will I do + 1 So as soon as I get a sub that has equal number If -1 is n + 1 then that has equal number If -1 is n + 1 then that has equal number If -1 is n + 1 then what will be its sum? Once I understood then we reduced our problem to find the sub array with sum row. Ok then wherever there is row, take -1 in its place. Question is done. is row, take -1 in its place. Question is done. is row, take -1 in its place. Question is done. Solve Now let's see okay so I created a variable named length which has initial value row I created a variable named sum which also has value row and created a map whose key is what is sum and what is the value at which index it is Sum is found, okay let's add one to it, I index, I placed it from here, I will treat it, row th index, what is the value of one, so I said, add one to the sum, okay, does one exist in my map, otherwise? I inserted one and its value became index zero ok let's move ahead so if the value is one then what will happen in the sum will one be added is two present in my map otherwise insert two at an index of and ok If we move further then i will come here as soon as you get row what will you do -1 then 2 - 1 you get row what will you do -1 then 2 - 1 you get row what will you do -1 then 2 - 1 is 1 From here things will become interesting when you will go to the map and see you will see friend I have already seen zero th On the index, on the zero index, you have got even one and on the second index, you are getting the even again, what is one, it means that the even which was in the middle has become a row, okay and why is it zero because obviously you have One is one and one is -1 obviously you have One is one and one is -1 obviously you have One is one and one is -1 because we converted 0 to -1 so if you because we converted 0 to -1 so if you because we converted 0 to -1 so if you sum them then obviously what will be the sum is zero so we can say that we have got the sum. Now here is how to calculate the length. So look i is your included you need its length i is your included you understand this is your end and this is your start is at the zero th index which is not included in your sub so when one is included and one is included If not then what formula will we use end minus start in our case which is end that is i so i minus the value of this map dot get ok whatever you are getting even ok so this is your end and this is your start ok So if you solve it then 2 - 0 what will it come to you solve it then 2 - 0 what will it come to you solve it then 2 - 0 what will it come to i.e. length to which you can also i.e. length to which you can also i.e. length to which you can also verify also this length to is right now is to is bigger than our length yes it was bigger so update it to two ok Let's go ahead, now tell me one thing, have you got even one, will you go here and update one here and update it to index two because earlier you got index row two, this time you got index two, okay then we will not update. Why because we are trying to find the maximum length. Understand one thing here, it is very simple. You found x at a point here, then you found Got it, now when you come here in your map, you will see in the map let's this is index to this is index five and this is index 8. Here you stored this x that x is even index to when you come here, let's From this you again saw that yes, the sum in between is zero, now you updated it to five, then when you come here, you will get this distance, but our main answer is what is this distance, so we will never update x. Because the farther apart the values ​​are, the bigger the length will be apart the values ​​are, the bigger the length will be apart the values ​​are, the bigger the length will be and that is what we need, so whenever we get the first value, we will store it in the map and after that we will never update it correct, so that is why we will not update this index correct so further Let's go, so i has come to this index, now 1 - 1 i has come to this index, now 1 - 1 i has come to this index, now 1 - 1 is 0. Okay, now look here, zero sum is not in our map already but this is the base case which you have to handle because you see from here to here. Which is a sub array, so how will you handle it? One way is that you directly check that if the sum becomes zero and all two things, what do I do instead of that? I say that I consider that here The sum of up to is zero and at which index is it -1? So what will you initially insert in your map? Zero index is it -1? So what will you initially insert in your map? Zero index is it -1? So what will you initially insert in your map? Zero sum at an index of -1 Why is it written as -1 an index of -1 Why is it written as -1 an index of -1 Why is it written as -1 What is the benefit Now see what formula we are using. And minus start right so my end what will be third index ok start what will be -1 so 3 and minus of -1 is + 1 3 p 1 is -1 so 3 and minus of -1 is + 1 3 p 1 is -1 so 3 and minus of -1 is + 1 3 p 1 is 4 so your length is already four which you can see also right this excluded It always happens that I have to exclude it, so -1 will always happens that I have to exclude it, so -1 will always happens that I have to exclude it, so -1 will always be excluded, so I wrote -1, then finally I got a length wrote -1, then finally I got a length wrote -1, then finally I got a length which is bigger than two, so I updated it. Will you update it in the map? Not at all. Okay, let's move ahead, here the value is one, so 0 + 1 is 1, here the value is one, so 0 + 1 is 1, here the value is one, so 0 + 1 is 1, now I have already seen one, which index is on which row, okay, so here I have already seen, here again i.e. In between these, there is i.e. In between these, there is i.e. In between these, there is like a subarray whose sum is zero, so again if we take the length, then the upper limit will be four this minus the excluded index that is zero, so what will it become 4 - 0 is 4 but the length is your already four. 4 - 0 is 4 but the length is your already four. 4 - 0 is 4 but the length is your already four. So no problem, we will not update it and we will not update anything in the map also. Okay let's move ahead so next value is one then it will come here 1 + 1 that is 2 one then it will come here 1 + 1 that is 2 one then it will come here 1 + 1 that is 2 What is two already in my map yes it is on the first index So I can say that from one to five is also a sub-ar, now from one to five is also a sub-ar, now from one to five is also a sub-ar, now its length will also be four, so no need to update, okay let's move ahead, I got the next value one, so I said 2 + 1 is 3 is got the next value one, so I said 2 + 1 is 3 is got the next value one, so I said 2 + 1 is 3 is not present in my map. I would have said, insert three at an index of 6, OK, let's go ahead, if I get x value, I will say 3 - 1 is 2. Now will say 3 - 1 is 2. Now will say 3 - 1 is 2. Now is two already present in my map? Yes, at the first index, here your two has come. This is your current index, so in between you will find a sub array whose sum is zero, so now look here, three times one and three times row, that is, the length will be updated to six. Okay, now obviously I do not insert the sum two. Because it is already present, let's go ahead here i has come and got it -1 do it so the sum is currently 2 -1 is -1 do it so the sum is currently 2 -1 is -1 do it so the sum is currently 2 -1 is one what is one I have already got it yes one has got it at zero index so I can say till now is equal to one, so from here onwards what is going to be the sum of this index again one OK now how many ones are there 1 2 3 4 and how many zeros are there 1 2 3 4 that means how much is the length 8 Now you see the length At is bigger than your six, so I have updated it again, now I understand, should I insert one, no, it is already present in the map, so do not insert it, let's move ahead, now let's move ahead, here again I got row 1 - 1 is 0 here again I got row 1 - 1 is 0 here again I got row 1 - 1 is 0 row index, is the row index present in the map? Yes - on the index with 1, so in the map? Yes - on the index with 1, so in the map? Yes - on the index with 1, so basically this sub array is fine, so now its length will be 10, right? 1 2 3 4 5 6 7 8 9 10 is fine. Its length will be 10. You can also calculate the upper limit minus of -1. What will it become? upper limit minus of -1. What will it become? upper limit minus of -1. What will it become? 10 Okay, so in this way you can calculate. Now will I insert the row? No, if you have already read it, then do not insert it. Let's move ahead. Now move i forward by one, what will be the value 0 then 0 - 0 i -1 -1 has what will be the value 0 then 0 - 0 i -1 -1 has what will be the value 0 then 0 - 0 i -1 -1 has not appeared in your map yet, if it appears for the first time then insert -1. Which index is then insert -1. Which index is then insert -1. Which index is found at 10th index? Okay, let's move ahead again. Now here what is the value got one so -1 + 1 0 again got row now already present one so -1 + 1 0 again got row now already present one so -1 + 1 0 again got row now already present in your map it means again got this big sub array ok what will be its length what will be the upper limit minus of -1 what will be its length what will be the upper limit minus of -1 what will be its length what will be the upper limit minus of -1 so Take this out, it will be 12, then the length will be updated to 12. Okay, now again you will insert your row again. Let's move ahead, so let's move i forward by one. What value did we get in row, so 0 in -1 done -1. What value did we get in row, so 0 in -1 done -1. What value did we get in row, so 0 in -1 done -1. Done - 1 is already present in the map at 10th Done - 1 is already present in the map at 10th Done - 1 is already present in the map at 10th index so we can say that from 10th index till here this length will become two but our maximum length that is 12 so nothing has to be done let's move ahead again i here Pay will come -1 -1 in -1 done -2 -2 is here Pay will come -1 -1 in -1 done -2 -2 is here Pay will come -1 -1 in -1 done -2 -2 is not present on the map, insert it at an index of 13. Okay, now you will go ahead again. If you are finished, your maximum length is 12, then what will be the answer? 12 Okay, so you will return this. Now what will be the time complexity of this approach, so you are obviously traveling linearly, so it is already big of n. Apart from that, you are either checking or inserting in the map. If you are doing then both of these are constant operations then I can say plus constant then what is its overall time complexity Big of n is only and space complexity in verse case we will use a hash map in which all the sums are unique so that means Big of n so it complicates your time and space so first of all we will create a hash map of integer zero comma integer zero ok let's name it map is equal to new hash map ok this hash map is created now next task What is it, first of all insert zero in the map dot put sum done row at n index of -1 sum done row at n index of -1 sum done row at n index of -1 ok now let's create some variables int max length e ect 0 ok and finally this is what I have to return the answer also return max Length ok next is int sum is equal to 0 ok now for int aa = 0 i &lt; a let's take out the equal to 0 ok now for int aa = 0 i &lt; a let's take out the equal to 0 ok now for int aa = 0 i &lt; a let's take out the numbers int n = nums at numbers int n = nums at numbers int n = nums at i &lt; n and then i + + ok so now i &lt; n and then i + + ok so now i &lt; n and then i + + ok so now we have to find the sum then sum How to find sum + equal numbers of i Okay so numbers of sum + equal numbers of i Okay so numbers of sum + equal numbers of i Okay so numbers of i we can't do directly here what to do see if you are getting zero then -1 will be added if you get one then -1 will be added if you get one then -1 will be added if you get one then only one will be added so we can If I get numbers of i is equal to zero, I am okay, so I am applying ternary operator here, basically understand it like this, if there is confusion, sum i is equal to sum plus okay, if I am getting pe zero here, then I say. Return -1 else wise return one ok Return -1 else wise return one ok Return -1 else wise return one ok so what will I get from this ternary operation I will get one value one is -1 and one is based upon one value one is -1 and one is based upon one value one is -1 and one is based upon row or one is now finally when we get this sum then check in your map that if map dot content key if this one exists in my map ok if this one exists in my map then what to do take out the length int l i upper limit which is i - lower limit which is map dot is i - lower limit which is map dot is i - lower limit which is map dot sorry m dot get Whatever is the index of this sum, okay, so this gives you the length. Now we can find the maximum length. Max length is equal to math dot max of max length. Okay, this is the maximum length we have found. In the other case, if the sum is present in your map. If it was not there, then what to do for the first time, just insert it, what happened to map dot put, what happened to your sum and which index I found, the index is fine, so I think this is complete now, there should not be any special problem in this, it was a very small code. let's run it hopefully fully ok because I ca n't use ternary operator in line here so what do I have to write it in brackets ok that's it now it should work done try to submit it end It did, what's the matter brother, okay, so Day 27 is also completed, so this was what came in today's video, I hope you liked today's video and if you did, then like this video, subscribe to the channel, I will meet you. See you very soon in the next video till then bye and take ker h
Contiguous Array
contiguous-array
Given a binary array `nums`, return _the maximum length of a contiguous subarray with an equal number of_ `0` _and_ `1`. **Example 1:** **Input:** nums = \[0,1\] **Output:** 2 **Explanation:** \[0, 1\] is the longest contiguous subarray with an equal number of 0 and 1. **Example 2:** **Input:** nums = \[0,1,0\] **Output:** 2 **Explanation:** \[0, 1\] (or \[1, 0\]) is a longest contiguous subarray with equal number of 0 and 1. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`.
null
Array,Hash Table,Prefix Sum
Medium
325
67
Hi gas welcome and welcome back tu my channel so today our problem is add binary so what have you given us in this problem statement here we have been given two binary A and B and we have to give the sum of this tu my dream Okay, so what we do is, let us understand through the example what we have been given in the problem statement, what we have been given in the input and how we will fine-tune our output. Okay, so how we will fine-tune our output. Okay, so how we will fine-tune our output. Okay, so we have taken both the examples here of this example. Through this we will understand what is the problem, so here we have given two strings A and B and both the strings are yours without resting date mains, in this string you will have only zero and one, so here you will have What has to be done is to add both of them and what will happen after adding should also be your binary string, so here the return type is your string, you have to keep this in mind also, so see here if you are asked to add it. So how will you add, let us see, whenever we have to add our bindastin boundary number, what happens is that when we add one, here we get zero and what is our carry, one. It happens and in this case there is only van, there is something in this number otherwise this van and this carry milk will become zero again and again what will happen to you will be carry van but what will happen here is you have any number otherwise this If carry is to be yours here, then what we do is, we add the binary number, so whenever we add van, what will become of you here, 1 0 and carry, your van is fine, it will have this. When you add 10, what will happen to you? Here, this will become yours. Okay, what will happen after that, here, when you add zero, what will happen to you? So this, which will finally become yours, will become 10 because you You will be there and this is indicating the van. This is indicating the van. These two together will be you. That's why 10 is found here which is yours. If you add 10 here then there should be van and also in the binding. This will be WAN and decimal will also be WAN. If you add zero to WAN, still this will be WAN. Decimal and binary will have both, so there is WAN here, so whenever we have to add, it will be asked, so we will add like this, right, carry it. When will you get your van? When will your van be a van and your maximum will be only a carry van here? Okay, so how will we start adding here? What will we do? We will take an I here because I have given this string to myself. Okay, so I means last. Index, you will start from here, from the last because you know that whatever addition we do, we start from the last, otherwise what will we do here, we will add IK first, we will add Easy first. Look, you will get this in the tractor, how will you add it, first you convert it to wait and a sam variable in which we will add, okay, we have added this and added its van and expanded I here and J. If it is increased then yes, your A is already finished, okay, if there is no question then what is left, then we first add its van, added it, I found you here, but what do I have to do by turning binary? It is okay to give, so in this condition, if you had done it, then you should have got this tu here. Otherwise, how will you get this tu, what will you do, will you get carry in this condition, if you add it to buy c, then it will be 110 and this carry. If there is a van then what will we do, we will see if our Sam is &gt; 1, what if ≥ 1 then we will understand is &gt; 1, what if ≥ 1 then we will understand is &gt; 1, what if ≥ 1 then we will understand what we have to do here is to divide the Sam from Kis Tu Se, whatever we will get here, then you will divide Tu from Tu Se here. But here, what will you get, if you get zero, then there is an answer sting in this string, what we will do in this is we will add zero, okay, now we will get our carry in this condition also because we have and sam, that is ≥ 1, so in this condition. sam, that is ≥ 1, so in this condition. sam, that is ≥ 1, so in this condition. What will be our carry? If it is a van, then what will we do with the scary also? We will take care of it. Okay, right now our SAM is zero and the carry van is done. Now when we move ahead here, it will be over. I have still got what is left, so Whatever will be our SAM, it will not be equal to 0 right now. We will update the SAM. Whose van did it equal to? Why did it become equal to this van? What is this? We have placed it here because this carry has to be added from the next number, so that's why. What will we do here, it is not there, we will take this I and add to it, add to this, again this is you, then we came to know that again what is our 2 &gt; 1, then again what will we do, &gt; 1, then again what will we do, &gt; 1, then again what will we do, this is from you. We will divide, we will get zero and we will add this zero here, we will add this string to the string and carry science, what do we have, if this is our own &gt; 1, then carry is also ours, what will happen here, if there is &gt; 1, then carry is also ours, what will happen here, if there is &gt; 1, then carry is also ours, what will happen here, if there is van here, then what will we keep here. Step 1 is done so now we have carry left with us so what will we do with this carry we will add it to the last one similarly we are doing here we got 110 by adding 0 and what we will do here will be van carry which is This one is your carry, okay, you have taken this van, now you only have it left here, otherwise, add his van to his van, this one is a carry and this is yours, so add both of them. Again you will get zero. Zero is again coming from van. If we add van to this here then we get 001. So what we will do is reverse it because this is a string. You will reverse it 10 0 so your answer will be this, okay. So what do we do, then we also understand through the second example, what is given to us in the second example, the equal number of characters in both of us i.e. zero van is equal to ours, so we i.e. zero van is equal to ours, so we i.e. zero van is equal to ours, so we look at it well, so we will do it here. Will we start adding both the numbers from the last one, so what will we do? So here we have 10 11. Okay, so we will take one sam, then we will divide it by you and we will carry ours, what will we do, we will take van but this is ours. Let's give what is equal to Van? Let's give Van is not equal to Van, so what will we do in this condition, we will add it to Van as one of our string, added it and increased I here and increased J here, both of these What will happen in the condition Van Again we will add Sam Ok this is yours Once again you add Sam then Sam What will happen to you You will add this value here You will add this value Here you will be You came to know that all is your van so if you divide by tu then if you divide 2 by 2 then you will get zero. You people add this zero here and you know that you have got sam here so if you keep carry van then this is Okay, so what will we do in the next number, we will come to this income and increase this i here and carry will remain with itself, this van is carry, so we will add these two, we will get zero in this. If we add van to carry, then this will again give us van, so we will add van here, this is &gt; 1, so we have not got it, if add van here, this is &gt; 1, so we have not got it, if add van here, this is &gt; 1, so we have not got it, if we keep it as carry, then carry will again be apple zero, then now you will start from here, you are Sam, here What will happen on the pay, you will have to divide it with you because you know that the Sam you got is a greater dene van, so what we will do is divide it with you, whatever we get, we will add it here and keep the van carry, okay carry. We will put Van in because what we have right now is &gt; 1, so now our I is over &gt; 1, so now our I is over &gt; 1, so now our I is over and K is also over, so what will we do now, we will add science here, look at this, reverse it here and here, then from It will happen but still you have to reverse because what you are doing is adding here in reverse. You are placing this one here first. If you are placing it here then you will have to reverse the answer. Not in this case but here. So you found it here, see, you found it here, so what do you have to do, if you want to reverse it, what do we do, we show you the code also, so what will we do here, I and K will take the last of your B. Take the index guys, you are okay, carry is zero, we have taken sam, now we will run this loop for how long till our i &gt; we will run this loop for how long till our i &gt; we will run this loop for how long till our i &gt; 0 or equals, you will remain zero or g, our ≥ will be zero then what will we do, we will keep ≥ will be zero then what will we do, we will keep ≥ will be zero then what will we do, we will keep going here, okay this. Loop because even if one gets finished then there will be one number left, so we have to keep adding that too, so here we will take more. Okay, what have we done now, we made Sam equal to Carry, so initially it will remain zero. After you are seeing that your I is greater give equals you are zero then what to do in that condition in Sam you first convert that number in wait, these minuses are doing zero, what will happen with this, you are converting in wait. After adding everything, I have done it, that is, you have done the decrement, then you have seen the jack also, give your greater, equals, you are zero, so what are you doing, add the value that is on the pocket, okay, so here. Then you are incrementing K and then you are seeing whether subman &gt; 1, whether it is Van, whether subman &gt; 1, whether it is Van, whether subman &gt; 1, whether it is Van, then the answer is, first convert it into string, which you will put here, whatever value you get here, you will write it. You will have to do it in posting because you have waiting and you have to return type. What is your sting? So whatever you do in the answer now, you return should be your sting. So here in twisting, you change the science of yours. What is your Sam &gt; 1? science of yours. What is your Sam &gt; 1? science of yours. What is your Sam &gt; 1? So you have to keep carry, it will be carry van, adervise, you have to keep carry zero and answer, whatever twisting sam we are getting, you will keep adding it. Okay, in this way you have this white look, people, in the last you will check if your carry. If there is still van then you have to add van in the last place, after that you have to reverse it and what to do here is you have to return it. Okay so I hope you have understood this. If you liked the video then please like and share. And subscribe thank you
Add Binary
add-binary
Given two binary strings `a` and `b`, return _their sum as a binary string_. **Example 1:** **Input:** a = "11", b = "1" **Output:** "100" **Example 2:** **Input:** a = "1010", b = "1011" **Output:** "10101" **Constraints:** * `1 <= a.length, b.length <= 104` * `a` and `b` consist only of `'0'` or `'1'` characters. * Each string does not contain leading zeros except for the zero itself.
null
Math,String,Bit Manipulation,Simulation
Easy
2,43,66,1031
207
hello welcome to my channel i'm here to do my 100 lego challenge and today we have nico 207 course schedule this is really famous uh legal questions and have been asked by a lot of companies and the question is there are a total of number courses you have to take label from zero to num courses minus one and some courses may have prerequisite for example to take course 0 you have to first take course 1 which expressed in the pair like this example so giving a number of course and the list of prerequisite pairs is it possible for you to finish all courses in here the example um there's total two course and the prerequisite in here is four uh to take number one you need to finish number zero first then it's true then you can just take zero first and then later you can get one in here there's number two course and to take a course one you will need zero but to take zero you will need one so let me draw a diagram it's like to take one you require zero and two take zero you require one then this is a four like a infinity loop so we cannot start because you will always require something so this is false so this is an example let me clear this out first um to understand this question i create one of the example so it's easier to understand so now we have zero point two in this mean i need to take two if i take two i will require to take zero first not only zero but also one so i need two classes one and zero to be taken before i take second like the two so now to take four i require two and in here if i take four i require two and three um first we can see there's a we call something called in degree that means for two we require two input which is zero and one so input two move forward to make it valid after this is valid and then four have two input like two in degree which is two and three so we can make a table called in degree so start with zero or zero we have one zero one two three four so it's five places so here's 0 1 2 3 and 4 course courses name so now we look through every um prerequisite which is in here the condition so now we have we know this connection prerequisite so we lose all the prerequisite and find how many in degree for the node for example in here if two will be quite one degree from here so we add one in here and what two also be quite one degree from one so we have to in degree for this index 2 and for 4 is the same thing after we loop through everything we have 2 in this in degree this is the array that we store in the beginning this is one of the data structure we're going to use why we need to use it because after looking at this in degree we find out oh here zero if you don't have if you have zero in your in degree that mean this number can be taken no matter what so chords zero one and three can be taken first right and we will take this three courses first and later on during this uh loop we need to create a map hashmap so to store in c so we see here 0 to this connection if you take 0 then we can minus 1 in degree for 2. so in this map it will be an integer and a list this will be the map so in here so we have zero in here and another list or array and list i mean this we store two in this list and we see one here we add it to the map in this list we have two and this three here we'll add this list to put four in here and another thing in two and then we'll put two which is um four in this list so now in this map we have this kind of structure data in here so what we can do we store this after we store this one uh we can because now we know that's three zero one and three is a free class you can take it without any restriction so next thing this is one data structure two data structure next data structure we're gonna have a queue saying that first we put the free course in here zero one and three in this queue and now we loop the first element first which is zero we take this out and loop this store a list in here to check oh now we have two since because you take zero you can solve you can sort one of the degree from two so degree will become one in here and then you go to and then this one is gone then you have one you take this one and you see in here we have another list look through everything in the list take out this two minus in this here you see the in degree we become zero because we take zero and one already so no more classes needed for two now two is zero so another condition is when this becomes zero we have to put two to the q now we have one three two because we have complete everything we need for two that mean we can take two now can be taken one is gone and three now we're taking three class three right so class three after we take it and we fulfill one degree from four for four right here so four need two after we take one we become one in degree so 3 is done but 4 still need 1 degree for input so because we have 2 finish it in here we take a look at 2 so two can fulfill one degree for four then cancel this two and four will become zero right after all this q will be empty so kills empty now we check oh this in degree um how does that look so we see everything in degree is zero that means we don't need anything for that class anymore so all zero one two three four classes are fully uh required i mean finish all the requirements and fully uh tickable now after that we can return uh true but only one situation i mean the situation like oh i have one more need for example here 5 2 3 i mean yeah i mean this is best bad example for example in here we need a four we need four before three so in this upper condition here so here would be one degree of three will be one for input so in this case there's no way to cancel out uh this one so oh so if you see one in this array eventually that means false so after this problem should be solved let's clear all this stuff just remember we have three things um we need to use in here let me see how to okay good so we will need in degree and after integrity we need a map and we need a queue for these questions in here we have we just have a condition a pre is equal to no and three dot length equal to zero or this is zero then return uh true should be true now we make an in-degree array now we make an in-degree array now we make an in-degree array call in you in degree courses as a lane and this is finished and the map we have integer and the list of integer type for this map hash map um now we have two of this like we what we said we loop through every prerequisite zero i less than prerequisite dot link i plus and in degree the prerequisite the first number will be increased because you need a degree for this number hold on f map dot contains key the second one then that if it doesn't does not contain that key then we will make a list first integer um current equal to new way less current.add uh pre current.add uh pre current.add uh pre the i zero put the i um current list inside so first we have to add the degree for that number which is here um for this number you need zero so that there's one in degree for this number so we add in the display in degree um table after that we will put zero in the map check if zero in the map is as a key if it doesn't create a list and add number one in here entice that list for zero because that means if you take zero you will uh reduce one degree for one right so that's what it means store so it's storing every number in there if there's um if the zero is already inside that map already we can just add it get pre i should be one yeah it's inside that ready then we add another number of i zero to add one inside that list that is done so after this the map and the in degree is finished so now this two is finished so like what we said we have those free classes let me draw again uh with the example we have is like zero one two three and four we need two classes for two and two classes of four now this is the table in degree table after at this point at 18 now we can take out the three classes and put it to the queue okay oh how can i oh let's see me make a cute first then q will have integer inside and for we check the whole entire in-degree in-degree in-degree array i see integer i okay in degree f i equal to zero then q dot at i we'll put that in there oh no um actually you cannot do this zero just loop through the in degree lesson indeed so look through this one and if check in degree the i equal to zero then we add i in there that means the index okay um this is the this part so now we have let me draw a little bit more the queue right here we'll store it zero one three and okay after this part so we need to check while the queue empty or not so while it's not empties then we put the current number integers equal to q dot pool and a list of integer because we store that integer list inside that map uh we'll see this equal to map dot get current so we get that list we need that list to go back to the in degree to cancel it out so for in x equal to zero x less than this dot size and x plus and here's really dangerous there's one more condition we need to check because this could be zero i mean could be no in that case and we need to check it so we look through everything in that list um we'll first we decrease the degree from that in degree table let's start get um hold on x so this is the index of that number we decrease it by one sorry um after we degree by one and check if in degree let's get x the current number equal to 0 or not like what we said now we check out zero and then zero after taking zero and how many cores get infected so remember i think this has become one because after you take this one if you feel the only two only need one more requirement right only one more requirement so one is another requirement so if zero are finished and class two doesn't have any requirement to take that mean you can take two and hold on let me change it back okay then if that is zero that means that class current class can be taken so we can add that to the queue okay after that we loop through everything so we cancel everything in the in degree so last step we need to do is check in degree all the number in degree so you find anything's not zero not equal to zero then it's false see because you cannot finish that class there's no class can fulfill that requirement otherwise we return true yeah that's it for this question i know it's kind of long probably take some time to digest it so in here we see we use one array one map one queue to finish this question so i think this is really good for on we practicing all the data structure just in one question so i like this question for this reason that's why it's really popular so if you are starting out and this is the question that you should test out for yourself for the knowledge in box free if you pass this one that means congratulation you are halfway to getting the interview so if you have any question please let me know comment below and i will see you in the next video bye
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
392
That a guy welcome back to record in today's problem is sequence pure YouTube channel please do subscribe vishal slot to complete your problems and problems is given testing lab testing labs which TV sequence of strings in used in which is the form from the original sting By Tilting Some of the Characters Without Stopping Relative Positions for the Evening Characters Difficult Costing Is Aisi Peeth Sub Sequence of ABCD Peeth Noida SEC Is Not Withdrawal Cases of Abuse Pair the Same See Difference Forces Not Mention for This Vitamin C Vitamin A True Knowledge Is Understand Examples For Pimple This Where Given String Is Acid ABCD And Physical Abuse Pay Subscribe Button Rule For Examples Eggs Peeth After Submitting And Subscribe Fati Video Course Not Present In The Greatest Subscribe Written 1582 Subscribe 9 154 Singh Binttu Years Way Can Go That I'll Start Getting Water Stream Not Win The Match Of The Character Slashed Pyaar Tasting This One And The Next Character Will Come Clear Again Will Check For The Next Character Singh Vijay Will Cause Some Who Not Give This Time Character Match Will Take Zone From Sydney Test Match Will Move Will Tell Women And Then Only Look 19 Second Time Third Time Will Again Match With The Next Characters Off Side With Jain Naveen The Got Me Soe Thee Time When Moon After To The Next Level So Election Will Reach And Hair Pack Sunveer Will Be Id Porn Ho Jayshiv It's Not Matching Films Liege Ko Again Will Moochhe Naagin A Good Match When Will Move To the precious improved this is for bluetooth turn off do 500 index year such thing subsequent fennel team your show vanity subsequent thirty days means oil in having same land used oil d match for all characters choice going to be always having length wishful Will reach the length of usa is f4 aye is equal to s.no is f4 aye is equal to s.no is f4 aye is equal to s.no length and cabinet to return to true wealth to return for its right code for this ho to like notification to indexes first feature i will start from 0 will start from zero Their lawyer this and this lead out line is that a k and that pure jewelers 140 dot length kind of boat a 8:00 kind of boat a 8:00 kind of boat a 8:00 that idea is equal to 8 don't care airtel se 2000 matching do i plus mails notice at any way you Want to z plus 09 feb also want to return a is equal to add kar lu a return to his return office your knowledge from this is gold submit as an alarm set return set that your intermediate fennel share the time complexity of This problem in this way attracting weight Buddha string in linear website isko* beef and plusam children any website isko* beef and plusam children any website isko* beef and plusam children any number of character in this and tears number character and rich request bluetooth settings video you like it is a different solution behind good comment and such log in all Solution for Different Problem Third Leg Thank You Rise
Is Subsequence
is-subsequence
Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not). **Example 1:** **Input:** s = "abc", t = "ahbgdc" **Output:** true **Example 2:** **Input:** s = "axc", t = "ahbgdc" **Output:** false **Constraints:** * `0 <= s.length <= 100` * `0 <= t.length <= 104` * `s` and `t` consist only of lowercase English letters. **Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code?
null
Two Pointers,String,Dynamic Programming
Easy
808,1051
1,043
I have shown you all the check out statements here, you can simply cross check them, see how much I have taken out, what is my maximum element coming inside all the sub arrays and not how many. From one to three, if a sub-array of mine is being formed, three, if a sub-array of mine is being formed, three, if a sub-array of mine is being formed, then what is my maximum element? The question of partition array for maximum sum lead is first of all, if you understand its problem statement, then you have given yourself an array. Of integer and create our own partitions inside it, so we have to make our own partitions inside the array and they will be of at most length like for example, this is an array and it has some elements, so we can create some partitions and its If the length can be at max k, then at max means one in the middle can be of one length, can also be of two length and if we are saying k is the length then we can make so many partitions and there are There are many ways to make these partitions, but you have to use all the elements while making two partitions. Now you have given them to us. Hey, into continuous sub ares, meaning that this is one subare, second sub are, this is the third sawar hai, trio of three. The server is continuous, this means that it is continuous, now what do you have to do after removing the partition, like for example, this is a partition which has three elements inside it, so you can take any of your elements inside it and the whole is complete. If we can convert it into that element, then basically we have to do it in such a way that the value of each one becomes maximum, then what we will do is that out of these three, we will pick whichever one has the maximum value and convert all three into it. We will give it to you and you will understand it better through examples, but what do you have to do, you have to find out the sum by doing all the partitions like this, you have to take care of this thing that it should be even, maximum and yours. We have to return that total sum like for example, we have given three arrays to us, we have given three examples, here the value of k is three, so now we have to divide our array into partitions, then the solution is that here we have to return this total sum. These three will be made one partition. If these three will be made one partition, then as you can see below in the explanation that what is happening due to this is that the maximum inside these three is 15, then all three will be converted into 15. Here all three All three of these got converted into 15. Three of these three got converted into 10. Because of this, whatever maximum possible sum this could have had, you will get it through this technique or this particular partition. If you take some more partitions then you may not get the maximum sum or you will not be able to exceed 84 so that's why this is the proper way of making this partition. Now the thing is that there is a lot of confusion inside it. There is a lot of confusion right now. Let me tell you, let us take another example, like what have you done just now, forget these elements for now, even if you forget these elements, from now on, I will clear some doubts that if you are approaching this solution then What are the things that you will have to take care of, like for example, if you want to extract partitions out of four, then out of four, you can basically see that two or two partitions will come, one partition will be for this and one partition will be for that, now these two Why are two coming from partition A because either we have this possible partition, but if we let's say, the value of one would be 10, meaning that ours would be 10, 15, and no, if this were So, sorry, if you take this partition, then it means there is a lot of confusion. Include this line that include this one, that is, include this element in your partition that if nine is big, then include this line. So, see, you have included nine, sorry, nine is big, so you did not include Nan because it will give more answers individually, here 10 was big, so if you did not include your 10, then by doing this, you can get different answers in the same size. All of them will have to take care of themselves, so these are some observations, some examples, now it comes to how we can unsolve this, see, the first thing that should come to our mind is that now how can DP be applied in this if Think for a minute with your DP, if your friend has said that let's go till now, if you know the answer till now, then what am I saying, you have the answer here. If the length of my key was three, what would be my answer here? If the length of my key was three, what would be my answer in this particular index? If I have that, then what would be in it, I would go to the fourth index. Let's go to the fourth index. So now what I am going to do is I am going to find out that if I include the fourth index then how many sequences can I create in my Hey. Okay if you don't understand then let's understand it okay first of all The thing has been kept by giving k3 or not, it has been kept by giving k3, it means that this 15, its influence can be ka, its influence can be at both these places, either at these two places or at these three places similarly if If there is any element in between, then where can be the influence of nine? The influence of the line can be two elements behind and two elements ahead. This is a way of thinking. Now let's consider the question. You can think through your multiple ways, what am I currently thinking about, where is the influence of nine, that is, which elements have the influence of the number, one way of thinking can also be that this Any particular element on this particular element, whose influence is it, that if I am standing here, then what am I doing now, what am I doing here? But I am standing, what am I saying, till now I have found the maximum possible answer that I could get, now what to do, Nine has come to me, a new element has come to me, Nine is so complete till now, Hey, this is my new Hey, it has become like, for example, earlier this was our Hey and its answer has been found, now Nine has come to us, so the size of our Hey has become so much, so now Nine can influence these three elements behind it and make itself just like this. The one on the left and the one just to the left because Apna is k3 so it can influence a total of three elements, so what will Apna do, we will go from nine and see that if I include the nine from Let's, I include the nine in myself one. Should I take one size or should I take nine of two sizes or if I make nine of three sizes, if I give all the possible sizes to this nine which is all about nine, from here till the back, then what possible answer can I get? Will that possible answer be my maximum or not? Similarly, if I get the answer from here that what is my possible maximum answer till now, then I will go to Pay Two and from Pay Two, I decide that I have to stop only here. Meaning, I have to stop only from 2 to 2. Forget these two also, I have to stop from 2 to 2 because this nine is big behind it. So what will I say that 2 plus my answer came from here. My answer came from here. This means that if we look at it in terms of DP, then we can always say that if our nine is up to this point, then it means that this plus dp of this index is such dp of Okay, if you are not able to understand then let us understand this example by solving it with DP and it will be a little bit tough to understand, but look, now when we do a dry run with our example, it will seem very easy. Now see what I am saying, first of all, we do towers from front to back, so we have our layers with this particular index, now how many elements can one influence on this particular index, we will keep storing DP on top of that, okay One can only influence itself. So far my maximum possible answer is one. One is my maximum possible answer so far. One is now 15 can influence whom. 15 can influence itself if 15 If he is influencing himself, then what is my answer? 15 If I take 15 back, then 15 is influencing whom, 15 is influencing one too and I have seen that 15 is the maximum, till now 15 is the maximum. So instead of one, I would like to take 15. Instead of one, I would like to take 15 and I will say that my current answer is 30, because what I said, make it 15 also, so my current answer is even the possible maximum. Maybe 30 is fine and why are they storing theirs, you will also know after some time, now after that I came on seventh, so if I am with myself on seventh, then I will get the answer, it is seven, is n't it? Just looking at myself or if I am taking size one of my k right now then my answer is seven. As soon as I thought of taking size two of my k and see, I got 30 got it means I got 30. Meaning that if this is one, this is two, this is three, these three are a saber of length, then the maximum element that will come in it is 15, the maximum element that will come to you is 13, sorry, 15, then 15. By influencing these three, if the maximum in these three is 15, then these The answer of all three will be 15. So when Sen traversed these three elements, Sen finds out that the largest element is 15. So what will he do with it? Simply, 15 means that all three have 15, so you can simply write here. 15 ta 3 Either you know how much is 15 ta 3 45 So till now you have come to your possible answer 45 Okay, now I have come to nine from late, so what will I say when I am with myself? I am the biggest till now, I am the biggest so now if I am considering myself the biggest then what will be my possible answer I am considering myself the biggest then see how my hey will become 15 &amp; 9 This is how my hey will become 15 &amp; 9 This is how my hey will become 15 &amp; 9 This is how my hey will become Now I am saying that if I am the eldest then it is nine, no plus, the sum of the back is the same, now how will we get the back sum from the deep, is it 15 30 45, we have stored it here, so our one is possible. The answer can be 45 P9 which is 54. A possible answer can be this. Now if Na comes to this then Nan comes to know that I am bigger than Sen. If Nan comes to know that I am bigger than Sen then I also include Sen in my size, which means that if I am all of length to loo, ending at ninth, then my maximum element is still inside it, which means everyone is at nine. I can convert all of them into naan, meaning how much is this, 9 toss 2, how much is this, 9 toss is 2, and what am I saying, now look, one is 15, sorry, both of these have been converted. I have already converted, 15 is 15, now I told it that if you become a nine, then this is 9, if it is like this, then this is 9 ta 2 + 30, isn't it 9 ta 2 + 30, so 9 this is 9 ta 2 + 30, isn't it 9 ta 2 + 30, so 9 this is 9 ta 2 + 30, isn't it 9 ta 2 + 30, so 9 ta 2 and I will add what was written in the DP behind this, then it will be 18 + 30, that is 18 + 30, this 18 + 30, that is 18 + 30, this 18 + 30, that is 18 + 30, this is 48, so we can see that 48 is not greater than 54, so 48 will not be our answer, now I simply went to the back and went one more size. I thought that if I take these three, then out of these three, if I take the size of all three, ending at this element nine, then the size of all these becomes three and at max. I can't take more than three. A. I can't take more than three in 2x. So I came here. I saw that the size of the saber is three. Now which is the maximum element among these three? The maximum element is 15. If the maximum element is 15 and I am taking all the Have to make something such that think something like 1 15 Now how did this one come in the starting because look it has one st in its DP 1 15 Out of these three I have seen that 15 is maximum so 15 So now I know that if I take this then my answer will be 15 ta 3 + 1 which is stored in this dp, 15 ta 3 + 1 which is stored in this dp, 15 ta 3 + 1 which is stored in this dp, I will not look at this, I will see what is stored in the dp because behind this The sum of the elements also comes in DP, so this is Apna 46, so you see, out of 46 and 54 is still bigger, so Apna see, you have seen all the cases, that is, see this one case. I had also seen this case that when it was 15 and 9 and I had seen another case in between that was 15 7 and 9. I had seen all the possible cases and The common thing in all of them is that this particular index is being added to this particular index. Are there any sub ending at a particular index? How many sub are ending at a particular index? So my answer will always be more than three sub. There cannot be more than three sub endings at a particular index. There can be only three sub endings at a particular index because Your k value is three and in other words a very good observation that I can say at any sub are if I write it let me just write it ends very good observation at any let me change this text to white neither at any index I index just increase is ok at any index i total sub are ending r k total subs ending r k can shift it somewhere shift it so at any index i total server is ending r k this thing you must have understood i guess Whatever sequence can be created, what I am saying is that how is ending at particular index, I with my solution could also go at any index, high how many serves are starting at index, so the sequence was starting there but Now we are going in reverse order how many series are ending at index i in this case we are going from front to back if we think how many series are starting and index i then we are coming from back to front in that case like The whole reverse order would have happened but for now this is the thing we did this much dry run now let's do further dry run ok look now you can do it please you should make noise that man there are more possible subre Which will be the end of nine, you will see that there can be only three sabers in total, one of own length, one of length two and one of length three because if its length is 3, then its end is With our help, we are finding out the answers to all the possible cases and whatever length we are taking, like this length, one length, two length, whatever length we are taking, we are always making sure that whatever is within us, we are always achieving the maximum. They are considering only that which has value, they are also sharing their own make For now, I have come here with late, so for now, I will consider all of them, or I will get lost in one. So inside one this is this and inside one this is when I do this then I will know that inside that if I'm ending at here let's say I'm here or first of all let's say I'm here myself so in that case What will happen in that case, a case of our own will be that 2 p 54 is not 2 p 54 means I am taking myself this and plus 54 is okay i.e. two and the elements behind is okay i.e. two and the elements behind is okay i.e. two and the elements behind if I can write it in another way. This will become our 1550 15 means 15 and na and ru so one sub will become this. After that if I consider only two of length then I will see na is bigger so here na low right sub are ending at two of length ru. If there is no maximum element in it then please consider this as no a well so in that case what will I do if I am taking that then in that case apni sub is it will become something like 15 na and na it will become apni sub Look, you are still figuring out the answer till here because you don't know further that even two will consume 10. You don't know this, but right now you are figuring out the answer till this point. If you had given so much to yours, then it would have been yours. Possible answer would be ok, this is what happened, now how do I find its solution would be something like this, from Let's it was 2+ 54, its solution would be something like this, 9 2+ 54, its solution would be something like this, 9 2+ 54, its solution would be something like this, 9 times 2 ps d p of this plus d p of this, is n't it because The earlier solution would have come out like this: 9+ 2 plus d p of this particular come out like this: 9+ 2 plus d p of this particular come out like this: 9+ 2 plus d p of this particular index. This is done 9 times to my plus d p of this particular index because 45 are already stored here. Okay, I understand this. And all the cases of 'S' you find out, you will come to all the cases of 'S' you find out, you will come to all the cases of 'S' you find out, you will come to know that the best possible answer is 2 P 54 that is 56 like you can try it out if you can find out different cases then the answer would be 56 now ending at index From ending five to ending at index five, here our maximum possible answer would have been 10 + 54 10 + 54, our answer would have been 10 + 54 10 + 54, our answer would have been 10 + 54 10 + 54, our answer would have been 64 Right, till here our answer would have been 64, we will also do dry run, how can we not let's go Come here, it is yours, let's cross check what I am saying, what am I saying, if the ending at index is five, then your answer should be 64, isn't it what your DP is saying from Let's If it was just like this, then what would you have done for now, return one, zero, anything, return a dummy value and let's just run it, want to see the expected outcome, what is the expected output, what is coming, so in this case the expected output is aha. Is it 72? Are you able to match? Are you not able to do? Obviously, you must have made a mistake. Let's see. If I take it as two instead of five, let's first cross check two. Definitely, you have made a mistake in some calculations. The is and that could be 10 p 50 64 ok let's see if I'm taking two [ if I'm taking two [ if I'm taking two then the then the then the expected outcome should be 63 to yahan pe bhi apna 63 hi aa aah that minute we've done something rang larat we haven't definitely I did something wrong, this would not have happened, it would not have been common, sorry, my fault, this would have happened, if this would have happened, then I would have done it. I have made a mistake in writing the answer 15 9 and 9 so in this case what becomes 9 ta 2 what is 18 plus this 45 18 p 45 and this is I guess 50 18 p 45 this is 5063 Right 63 So here our answer would be 63 and if we are cross checking here then it is also coming to be 63. Okay after this, if I had considered these three lengths then my answer would have been 9 ta 3 + 45 So this would have become 72 This would have become 9 ta 3 + 45 So this would have become 72 This would have become 9 ta 3 + 45 So this would have become 72 This would have become 72 Like you can cross check 9 Ta 3 + 72 Like you can cross check 9 Ta 3 + 72 Like you can cross check 9 Ta 3 + 45 72 would have been in that case Apni Hey kya banti 15 9 So ending and this Apni This is a possible one Hey banti which would have been your answer And if you cross check it right here, whether your bus or your dryer is right or not, very good way to check it, due to this, your athlete comes to know that your concept is right, so now I am I will write the code, it cannot be wrong, I just have to convert my concept into code, it is okay, what I said, I have included one more thing inside my hey, that is file, it is okay, that is file right. Wait second, first of all remove the terminal, it is coming again and again in the middle or okay let's just run it I am apan kya bolrahe answer aana chahiye 72 let's see the answer kya aata hai apan aaye yahaan pe apan ne expected dekha 72 is coming very good Then we come to this particular index and this particular index says that friend, I am the eldest among these three, so I will take 10 times 33 and plus I will make it deep, that is, take whatever possible answer was there till now, plus the next three elements. I will remain myself 10 So this would have become our possible answer 10 and 10 This would have become ours, but if I had included this also then and in that case what would have been our answer 30 toss 54 which could be It goes 84 so if you go here and add one more 10 at the end then see what was your answer ok your answer comes 84 and you have also guessed 84 right then you see how much DP is there in it The useful thing is that if you store the previous answers, then you are giving benefit to yourself. Whenever you are taking all the answers, you are giving benefit to yourself. Now we understand why. We are using DP and how we can use DP. First of all now let's see how we can do it in the code. Look, first of all we have to create a DP and what are we always doing in DP, right? An index. Looking back, now the length of my saw is touching the particular index. If it is touching the particular index, then our answer will be the maximum of whatever is inside these three. That maximum plus this index minus the index, so what happens in this case, like if this index would have been from Let's x, this index would have been k so apan kya hai maximum in times k na see this maximum value times k plus apan plus kya do I want to explain, a simple reason to explain is that if I am writing x - 1, simple reason to explain is that if I am writing x - 1, simple reason to explain is that if I am writing x - 1, it means that if the value of x is by chance and if I had written 0 -1 chance and if I had written 0 -1 chance and if I had written 0 -1 then dp0 - 1 would be dp0 - 1 would be dp0 - 1 would be -1 which is not possible. -1 which is not possible. -1 which is not possible. To avoid this case, either I should put an if else condition that if I am writing -1 by chance, put an if else condition that if I am writing -1 by chance, put an if else condition that if I am writing -1 by chance, then do not consider it, but better than that, let's make a map of our own. Now let's see what happens in the map. We have created a map of comma int and we name it deep. Now the good thing inside the map is that inside our DP we can now separate -1 from row, which means that can now separate -1 from row, which means that can now separate -1 from row, which means that inside it we have -1. Index can also be considered, inside it we have -1. Index can also be considered, inside it we have -1. Index can also be considered, okay, so there is no need to worry about it, Apn-1, whatever no need to worry about it, Apn-1, whatever no need to worry about it, Apn-1, whatever element is usually adopted by default in all DPs and is treated with minus only, now the good thing in this is that - Be it 1, be it 2, be it now the good thing in this is that - Be it 1, be it 2, be it now the good thing in this is that - Be it 1, be it 2, be it -3, be it anything, be it the index behind, we -3, be it anything, be it the index behind, we -3, be it anything, be it the index behind, we will consider it as zero by default and it will not generate any error for itself, okay, you have understood this thing too, now let us run a loop int. E 0 aa should be len a aa r plus ps aa aapn ne puri ki puri arep ek chala di ru so basically what aa specify here what we want to find is that total sub ares basically apn kya niklaan hai total sub ares ending at Look at the index, if you have reached a good level in DSA and at that time only you click on this particular line, then this is more than enough. A good person can guess from this particular line only that yes, I am the answer. If I know that total subs are at index i, how much will it be? Well, we know for a fact that total index at ending at will always be k and less than k, so it can be less than equal to k. It may be okay, whatever it is, now let's take out all the sub-arrays, so for now look, all the sub-arrays, so for now look, all the sub-arrays, so for now look, now let's talk about the length, so int length should be equal to 1 and length should be less than equal to k means length one can be two. It is possible that if the value of k is , then it can be the if the value of k is , then it can be the if the value of k is , then it can be the entire length between n and k. Your sub's t ending at the index. Okay, so you have done this, then you have done plus length so that now the length is We will increase the length, we will increase our length. What is in general so that I can write my code, if I have come to this particular index, then what I am going to do is, first of all I will consider a length, then look at what I have, the maximum answer for a DP should be I have found out the possible answers of the three sub-arrays and if I have found out the possible answers of the three sub-arrays and if I have found out the possible answers of the three sub-arrays and if I have to find a maximum from them, then I have to save that difference. One more thing is that what is my maximum value coming within all the three sub-arrays, what is my maximum value coming within all the three sub-arrays, what is my maximum value coming within all the three sub-arrays, I should save that also. If you want to keep it, then these are some things which you have to save, okay, first of all, let's focus on our maximum value, let's do our work one by one, so what am I saying here, let's take mx0, maximum is 0, okay. Now what will we do mx2 comma Which particular index am I on now? Look, if my length was two, then let's not forget everything. 0 1 2 3 4 If my length was t then now I would have to remove this element like first of all my length would be one I came here my length is one so what I would do is let's i e 4a so 4 - 1 do is let's i e 4a so 4 - 1 do is let's i e 4a so 4 - 1 p 1 I would call this index I add it in itself, isn't it 4-1 P1? I add this index, isn't it 4-1 P1? I add this index, isn't it 4-1 P1? I add this index, how did I get this, then this one in itself is length and I have to add this one because look, 4-1 is 3 P. because look, 4-1 is 3 P. because look, 4-1 is 3 P. 4 meaning current index, this formula becomes, basically aa minus le pv, this formula becomes that we have to add this index to ourselves, how to cross check. See, if I talk about this particular index p and I talk about length one, then add me also. It will take t i = 4 minus what t i = 4 minus what t i = 4 minus what is the length 1 p This is 4 That means you have to look at your fourth index, add it to your Comparator to see whether it is maximum or not, add this to the answer, this is that, now let's get my length. My length has become two. What do I do when my length has become two? 4 - 2 P1 What do I do when my length has become two? 4 - 2 P1 What do I do when my length has become two? 4 - 2 P1 How much is this happening, this is what it means, now I will add the third index, this is like this in myself, if you want to see this thing then This is the particular element to be added, let's give it its own name, inter element to be added, okay, element to be added, let's give it its own name or element to be compared or just element, let's say first element, I call it Why am I saying first element because look, we want to see in every particular array that if there is ending at index then where is the first element of whatever apni array is formed. Now what is the first element? The first element can also come on the seventh or second index. This can also happen in I, so let's name it as first element index. Now what was the formula of first element index? You get the first element of your sabre. If you have any doubt, let's clear your doubts. First of all, okay, now you have indexed the first element. What will you do? If you have any doubt, then check it out. By doing this, we will clear in each particular step. Now we are going to clear our C. It is okay, there is some time in the solution. If we continue to clear our C. So this plus arr of first element index is just this will clear our maximum. Now we simply write out ' out ' out ' Hey starting at index' Hey starting at 'index', Hey starting at index' Hey starting at 'index', Hey starting at index' Hey starting at 'index', now we write 'if' is the now we write 'if' is the now we write 'if' is the first element index 'Is', now if the first element 'ix' ever index 'Is', now if the first element 'ix' ever index 'Is', now if the first element 'ix' ever comes negative then we write ' comes negative then we write ' comes negative then we write ' if' first element index 'e' here. let lesson if' first element index 'e' here. let lesson if' first element index 'e' here. let lesson zero then what to do here break this loop break your understanding ok so what do you want to write right now your see out statement want to write are starting at index first limit index ok starting from here Are we trying to remove the maximum element? Is the maximum element in the are starting in index first index and ending at ab and which index is there and is happening at aa and ending at a and this is it right here. Let's put end and just print it once and see what we have done so far. Return is zero. It's okay, small mistakes keep happening, it is not a big deal, there is no error here or we should write 'A'. So int a id size or we should write 'A'. So int a id size or we should write 'A'. So int a id size this i it and isko apan kar do hain a one more time do apan run ok return zero is misspelled RT you are n lrat so you should have some particular statements a dos will be very interesting so see Maximum element in the Are we starting at Apna forgot to print the maximum element here, Apna has to put one more thing here, is n't it? Now here we remove Apna by doing one bus and one more b, you will understand which. You will understand what you are doing only after reading that, see, if there was a particular index from zero to zero, then the maximum element inside it is my one starting and index. If I was from one to one, let's If there is so much inside it, then the maximum element inside it is 15, from zero to one. If my one is all, from zero to one, it is all from zero to one, then my maximum element inside it is 15. The maximum element is 15 like this. Keep checking, keep checking, and one by one, each one is being formed, from row to 01, 2, my maximum element is 15. So for now, I have shown you all the sing out statements here, you can simply cross check them. You can do that, friend, see how much effort you have made that what is my maximum element coming inside all the sub-ares, no, maximum element coming inside all the sub-ares, no, maximum element coming inside all the sub-ares, no, if one of my sub-ares is being formed from one to three, then my element is coming inside it. one of my sub-ares is being formed from one to three, then my element is coming inside it. one of my sub-ares is being formed from one to three, then my element is coming inside it. What is the maximum element coming? I am making a sub from four to six. So inside that my maximum element is 10. What is coming is 15. Now with the help of this you can calculate the remaining amount. Things are fine, okay, now let's move ahead, now Apna has got this thing, it means a big work has been done Apna, I will do it for now. Comment Alright, I also have the link to the solution, whatever is my particular. There is a solution, I will put its link in the description if you want to see it. So I have done this. Now after this, what do you have to do? You have to find out the DP that what will be the DP in the current index or you have to find the answer that whatever. Possible sub-arrays are being formed. As many possible sub- whatever. Possible sub-arrays are being formed. As many possible sub- whatever. Possible sub-arrays are being formed. As many possible sub- arrays are being formed. If you include the maximum element in all those arrays, then what will be my answer? I am not able to understand. Let us understand what we are trying to do. Now let us first understand it. What I am saying is that if I consider subs of one length now then what will be my answer then this will be my answer one, if I consider subs of two lengths then this will be my answer two if I consider subs of three lengths If I do, then my answer is three, so here I am if this is what I am saying is one length sub is ending at this index two length sub is ending and dis index three length sub is ending and dis index like this or like this Understand this, if I consider all this then I can get these three possible answers. How do those answers come? Sub of one length is plus d p of this. Sub of two lengths is plus deep of this. Sub of three lengths is plus deep of this. By doing this like this, I would get all the answers and compare them, what is my maximum coming out of the three, that would be my d, inside P of this, it would be DP of this current index, like this, now let's come to my code. On the other hand, here we create a variable by taking our int answer with our m one which is zero also I just want to make one thing sure our answer long is not coming no anyway no long is not coming okay On return we are releasing our int. All right anyway, this is our answer. Now what do we have to check our answer? How to get our answer? Int answer is equal to sorry not answer. You have stored the answer variable. Answer is equal to maximum of answer comma answer. Eq maximum of answer comma Let's give you the length of your length, how many maximum elements do I have within that length, that's length times maximum elements right so what does A mean maximum element in my sub in the current sub in The current sub array is my maximum element inside the current sub array, I do the times length, then what do I do along with it, add the deep DP, which valley do I add the DP, the first element is just before the index, isn't it DP? I add the first element just before the index, so this is the answer. Along with this, my answer has also come. I have to do it at the end of this loop. Look inside this loop, what will happen. I have found out the answer for all the variations that will be made and I have taken its maximum at the end, what would I do, whatever my maximum answer comes inside DP of a, I would store it and at the end, my DP of n-1 and at the end, my DP of n-1 and at the end, my DP of n-1 would lock my answer if I run it. So you can see that this is getting accepted If I submit this then again this is getting accepted So this was the solution I hope that you have liked it I hope that you have enjoyed my explanation Any comments You need to bring any improvement Explanation Please feel free to ask them and give your suggestion in the comment. If you have watched the video till now then do n't forget to leave like and also subscribe. If not then subscribe also. Thank you everyone. Bye bye.
Partition Array for Maximum Sum
grid-illumination
Given an integer array `arr`, partition the array into (contiguous) subarrays of length **at most** `k`. After partitioning, each subarray has their values changed to become the maximum value of that subarray. Return _the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a **32-bit** integer._ **Example 1:** **Input:** arr = \[1,15,7,9,2,5,10\], k = 3 **Output:** 84 **Explanation:** arr becomes \[15,15,15,9,10,10,10\] **Example 2:** **Input:** arr = \[1,4,1,5,7,3,6,1,9,9,3\], k = 4 **Output:** 83 **Example 3:** **Input:** arr = \[1\], k = 1 **Output:** 1 **Constraints:** * `1 <= arr.length <= 500` * `0 <= arr[i] <= 109` * `1 <= k <= arr.length`
null
Array,Hash Table
Hard
51
975
welcome back today we are going to start new uh video of this Google interview Series right so this and this time we are going to use uh problem we have selected odd even jumps right and uh this is very good questions and have been asked in the Google interview multiple times so I will recommend you to please watch the full video and uh let's go to understand okay so uh I'll start one code from uh ourself right so if you don't you if you cannot do great things right so you can do small things in the great ways this is a state by APG Abdul Kalam right so I ideally want to say that you have to start little questions right small questions so that you will uh work on your goal right and you will achieve one day with your goal right so I will recommend please watch this series that I'm going to I have started actually and I'm going to do multiple questions based on the Google interview questions right I will collect all the questions from different uh hotels right and I'll put those here okay so if you have any suggestions please pick me in the comment box right and I we will discuss there thank you guys let's continue so uh in the statement we have given two we have given like uh two things right the first about the odd number and even number jumps right so it is saying that statement is saying that we have given uh you have given an integer array that is array and from starting Index right you can make a series of jumps okay from starting index okay and uh if there is a first third and fifth jumps in the series are that is called odd number jumps okay if the jumps are first third and fifth odd number jumps right this is called uh odd number jumps okay and second fourth and sixth and so on these jumps in the series are called even number jumps okay means we have given an array right an array in an integer array you can say elements are in integer where we have given some a series of jumps right if these jumps are in the odd number this is called odd number jumps and if this is given this even number least this is even number jumps right make sure that jumps are numbered not the indices these indices is are actually this is not actually an indices actually okay these are jumps okay it is saying these jumps are actually numbered not the indices make sure that we will discuss okay and you may jump forward from uh I to J uh index where I should be less than J means I should be less than J in the following way the first way is uh during odd number jump means jumps one two one three and five and so on you jump from I to uh you jump to the index J right you are somewhere let's suppose I and you are jumping to the I index okay it means the array at I should be less than equal to array at J right where array at J is the smallest possible value in the array right where we want where the range is there right if there are multiple such indices right if there is multiple such indices you can jump only one time with the smallest right we have in the possible values right and such indices is J again it is saying during even number jumps 2 4 and 6 you jump to the J and such uh a of r i is greater than equal to this means this element a of J is largest possible values right and if there are multiple such indices J you can only jump to the smallest right so you have to take care of these nodes it is also saying it may be a case that for some indices right there no legal jumps are there okay so this is the things we have the rules like this one and we have to follow this one but a concept is saying that a starting index is a good if starting from that index you can reach the end of the array means array dot length minus 1 indexed right if you reach there by jumping some number of times right possibly zero or more than once right it means this is your good index and that number of good index we have to return that we will see here okay so this example we have 10 13 12 14 and 15 right let's suppose we are talking about this one okay so this is the array we have given here I'll start the index 0 1 2 3 and 4 okay so here the if I want to jump from these two this or any of these right okay so I have possible possibility range right possible range what we have is I can move to any of the directions right from here to here these are my range right indices from 1 to Force right we can jump okay either one jump or multiple jumps I can do okay so what is the criteria we have to check the elements this range right if it is and another is a smallest possible values so this is one three and five like so this is uh this is the indices right this is one right so what I will do I'll check the element which is uh smallest right so in this range 12 is the smallest element okay so I will select not to go here but I will jump to here okay and I am at this position so from here this is the indices 2 right now we have to check the uh next jump right so this is the second jump right so this is the indices two right and uh if you'll talk about the indices right this is one two and three right so if take any other jump right where we will reach right but we have made already one jump now one element is left here 13 so what I will do I'll check the next element right so there is a possibility here and here right where we should jump Okay so this possibility can we come to either here or we can go to here right okay so if let's suppose we are going to this one so we reach here okay and if we want to jump from now here to here right or here to any other place right let's suppose so we are reaching at the end here okay so either will come to here and here so only one possibility is coming here like we are reaching at the end right from here to here or from 12 to reach to any other position right so maximum two approach two way we are getting here okay we will discuss here let's suppose so what we are talking about here we have given 10 13 12 14 and 15 right this indices given so if indices are 0 1 2 3 and 4 right so if we'll start with the in this starting index is 0 we can make the first jump to 2 here because the smallest element is at 2. since C array at 2 is the smallest among these elements right all these elements these are the range we have given so from here to here this is the smallest element right so a smallest element is 12 and that's why we jump we can jump there so that is greater or equal to the error zero now we cannot jump any more right because we are at here from a static index 1 Let's suppose we are going to here and I again we can say here or from here we can make our first jump to 3 either we will come to here right or either this jump can be come to here okay so we cannot jump anymore from here to any other places right both jump can be come here next what is saying but we are not reaching to the last one okay next we are coming to index I equal to 3 right so we can make our first jump to I equal to 4 okay so from here we can make a one jump to here and we have reached the end so we can count one output okay next from the starting index that is at here if you make any jump so we are at already at the end right so we do not require any more jumps right and that's why these two count is there one and one this is the starting index three and four where we have to reach at the end okay so in total there are two different indices I three and I4 as you can see here and we can reach at the end of the number of jumps and that's why we are getting output 2. similarly let's suppose we have given this one okay so we are starting at index I equal to 0 1 2 3 and 4 right so we can jump where a smallest element either I can jump to where I equal to 1 right because this is the odd one right and we can jump to I equal to 2 or I equal to 3. either greater or either smaller right so during our first jump that is the odd number right so first jump is odd number we first jump to I equal to 1 because this is the odd number and array at 1 right is the smallest value in this range right these this and this okay and that is greater than equal to F 0 it is greater than or equal to zero right so smallest number is now updated to which number they see this is the largest among the three one but according to the question this is the smallest number right because it is saying that it should be greater than or equal to this number now during our second jump what will happen we will get even number from where I equal to 1 to I equal to 2 so if you go to from here to here right because array at 2 this element right is the largest value in 2 3 and 4 these three element side and Which is less than equal to array at 1 right at this element so it is also largest value but 2 is the smallest Index right and so we can jump to I equal to 2 and not to the I equal to 3 okay so next jump we will make odd number jump and we can start from I equal to 2 and I equal to 3 right so array at 3 is the smallest value and array at 2 as you can see here and array at 4 is the greater than all this element right so we can make I equal to ah from I equal to 2 to I equal to 3 right this is the smallest element now we can't jump I equal to 3 to here because this is the odd number first of all sorry this is not the odd number right and I equal to 3 to I equal to 4 so a starting index I is not good 0 this one is not good right and in the similar manner what we can do if the starting index is I equal to 1 we can jump to 4 right and so we can reach the end because this is small and this is a greater right so one jump will be there okay when we are starting at index 2 right we can jump to I equal to 3 because this is the smallest right so we can take but we can't jump anymore so we can leave that starting index I equal to 3 is 1 and we can jump to four that is another count and we have reached already now at index 4 right what we have starting index and we are already at that and so three jumps we will make right and we can say in the total jump we had three different diseases we have so don't we take a little load on yourself and we can just assume that the possibilities right and you will understand these questions coming back to this except this okay let's understand uh the third output third example so here we have given ah one two three four five but indices are 0 1 2 3 4 okay so we can start from index one that is this one okay so from here we have to find the smallest one right we can go to here right so this is the first starting index from three we'll find the smallest one so we can reach to here we will get another one from 4 this is the event right so we can reach to here and this is the third right means total we can reach from the starting index to the end is 3 right so the output is coming 3 okay I think you got me so let's understand the constant we have given so constant we have given the length of the you can say array greater than equal to 1 and 2 into 10 to the power 4 and arrow length is this one okay so this function we have given we have to implement this one okay so before that before going to the jump let's understand the odd number jump and the even number jump right so how will how we are understanding first of all what we have to do you have to understand first third and fifth are the odd number second fourth and sixth are the even number so we have to jump the index J in such a way we can have this logic right so array at I should be less than equal to J means these elements should be small than this one okay if this is odd number so that is called smallest element right in other case in the even number if we add is the even number get up it should be greater than equal to J means array at I is the largest possible value not to be the smallest one okay not what you have to do if multiple indices are coming means we have to make the smallest one jump a smallest jump multiple elements are coming right so we have to check the smallest one right there may be a case for some index that are not legal jump so you can skip that now starting index you know if the starting from the index you can reach to the end of the your array right that is called array dot length minus one you will reach that is called a good number okay so uh we have to return number of good number that is starting from the indices right so let's suppose uh again we have this example we have given 10 13 12 14 15 right 0 1 2 3 4 we have given start index 0 we have and for the first jump so if we are at here from here right so this element we have all these elements the smallest element is what 12 we have so we can reach there so this is your first one what we but we have not reached here okay next time what we will do from 13 we'll check a 12 14 this one so which one is smallest this one is the smallest right so still we are not reaching there right now we'll from 14 this is a uh one two three four and fifth now we are at four right we will check the max largest one which is largest 15 is the largest so we have got one because we each at the end now 15 is here the element right so 15 is already at that there so we'll do one more uh jump so total jump is two that is the good number we have okay I think got me okay now we have to find time complexity and space complexity after this uh understanding like so we'll uh you can note this is the time complexity we will find uh n log n and O of n right so how we will implement this one first of all we have given array dot length right so how will calculate n is we can find our length and we will take one result okay so we'll take a Boolean and we'll mark as a by default this all elements are false and will take lower is Boolean at N is a load Bond we'll take and we'll say higher n minus 1 equal to lower n minus 1 we will Mark as true every higher n minus 1 and lower n minus 1 both are true right we'll take a tree map and we'll store all this element here how we will put n minus 1 and N minus 1 like this right we'll start from the N minus 1 and then n minus 1 and will iterate over this element right because we have to uh get the we have to reach at the last Index right that's why now what we will do for n minus 2 from the last 2 element we'll move to the 0 and do I minus so that from the last element of the array let's suppose this is your array okay so this element length is n so n minus 1 is the index and this is zero index so from here we will go to here and that's why we are making the loop like this okay so from this L we have already stored this index on this element right at where at the uh you can say map okay here as you can see we have already stored now from here to here right from here to here what we will do this is your n minus 2 index and there will be some element okay so this element from here to here will come and will store onto the map how we'll do we'll take a selling entry right array at I will take and there is uh that is will call high and uh the floor value will take on the look right we have all high and low and what we will do we'll check if High not equal to null will store at a high right if high is not null then we will store lower value right of the high and similarly if low is not null then we'll take a higher value of this one actually we are getting uh you can say higher value and lower values at the element and we'll check the index right we'll pass the index and we'll check its uh we have reach or not right for that we'll store higher at higher and lower we'll check the element high at higher will take High Dot get value and lower it will get lowered this value well but will check on the cross will check at lower at higher will check lower and at lower will check at higher right whatever will come we'll store it here okay and then we'll do higher at I will do I plus and we'll do map dot put and we'll do array dot i and comma I okay and finally we'll return we will have all the elements high low elements we have and we'll come to here means its index value will be there and element will be there and finally we'll return this result so this result contains uh you can say we are adding this value so each time if we get the higher value right this value will get incremented right and finally that element we are storing at this indexes right so this will give you your result and for that the time complexity is O of N and because we are using T map Auto sorting and here we will take off n Azure time complexity sorry space complexity okay thank you guys thank you for watching this video If you like this video please hit subscribe this channel so you will get more videos like this thank you guys
Odd Even Jump
range-sum-of-bst
You are given an integer array `arr`. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called **odd-numbered jumps**, and the (2nd, 4th, 6th, ...) jumps in the series are called **even-numbered jumps**. Note that the **jumps** are numbered, not the indices. You may jump forward from index `i` to index `j` (with `i < j`) in the following way: * During **odd-numbered jumps** (i.e., jumps 1, 3, 5, ...), you jump to the index `j` such that `arr[i] <= arr[j]` and `arr[j]` is the smallest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`. * During **even-numbered jumps** (i.e., jumps 2, 4, 6, ...), you jump to the index `j` such that `arr[i] >= arr[j]` and `arr[j]` is the largest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`. * It may be the case that for some index `i`, there are no legal jumps. A starting index is **good** if, starting from that index, you can reach the end of the array (index `arr.length - 1`) by jumping some number of times (possibly 0 or more than once). Return _the number of **good** starting indices_. **Example 1:** **Input:** arr = \[10,13,12,14,15\] **Output:** 2 **Explanation:** From starting index i = 0, we can make our 1st jump to i = 2 (since arr\[2\] is the smallest among arr\[1\], arr\[2\], arr\[3\], arr\[4\] that is greater or equal to arr\[0\]), then we cannot jump any more. From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more. From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end. From starting index i = 4, we have reached the end already. In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of jumps. **Example 2:** **Input:** arr = \[2,3,1,1,4\] **Output:** 3 **Explanation:** From starting index i = 0, we make jumps to i = 1, i = 2, i = 3: During our 1st jump (odd-numbered), we first jump to i = 1 because arr\[1\] is the smallest value in \[arr\[1\], arr\[2\], arr\[3\], arr\[4\]\] that is greater than or equal to arr\[0\]. During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr\[2\] is the largest value in \[arr\[2\], arr\[3\], arr\[4\]\] that is less than or equal to arr\[1\]. arr\[3\] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3 During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr\[3\] is the smallest value in \[arr\[3\], arr\[4\]\] that is greater than or equal to arr\[2\]. We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good. In a similar manner, we can deduce that: From starting index i = 1, we jump to i = 4, so we reach the end. From starting index i = 2, we jump to i = 3, and then we can't jump anymore. From starting index i = 3, we jump to i = 4, so we reach the end. From starting index i = 4, we are already at the end. In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some number of jumps. **Example 3:** **Input:** arr = \[5,1,3,4,2\] **Output:** 3 **Explanation:** We can reach the end from starting indices 1, 2, and 4. **Constraints:** * `1 <= arr.length <= 2 * 104` * `0 <= arr[i] < 105`
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
null