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
879
um hello So today we're going to do this problem which is part of Fleet code daily challenge uh profitable schemes so basically um in this problem we have a group of n members okay and we have a list of crimes they sh they could commit okay um and then the ice crime generates profit I so um but I'll say crime zero generates profits at position zero so it generates profit of two and it needs a group of I to be able to participate to commit that crime okay and so again for Crime zero we need profit zero so two and we need to group zero members so we need two members out of this n to be able to commit that crime um and get the profit and the member can't participate in another crime which basically means once you commit crime at position zero then you should subtract this two from this five and you would have only three members remaining because they can't commit another crime if they did then you could keep five and keep reusing them but they can't so you'd have to subtract it and we have this concept of profitable scheme where basically it's any subset of the crimes that we have um that can generate at least the minimum profit that we have here so the profit of a set of crimes is just the sum of their profit um and so to have a profitable scheme it's basically a subset of the crimes where the sum of the profit is small or equal is bigger or equal than the minimum profit but also the total number of um of members participating in that subset of crimes is at most end which is what I said earlier about like a member can't commit to crimes so you'd have to subtract it completely and so the goal of the problem is to return the number of schemes that we can have and then we could use this modulo okay so that's the idea here now let's take a look at the first example and see what this is about so for the first example well we want to get profit of three at least and so we could decide either to do only this one right climate position one that will give us profits of three it will give us we will need to use two members which is within the number of members we have available so that's a valid solution so we count it so we have one um and then the other possibility is to do both right you can't do just two because then the profit is smaller than the minimum but you could do both and then the profit will be five which would be uh bigger than the minimum profit so it's good and then also in terms of the number of members we would need two plus two so four which is still within the limit that we have here so that's another possible solution and just zero alone is not possible then we have only these two so it's two okay so that's the idea now it did happen that this problem here has two and two that are within the limit now what if this here was let's say four if this was four then we would want to return just one because you can't take both because if you take both then you need six members but we have only five okay so you can think of this as we have two constraints we have the constraint of the sum of the profit needs to be bigger or equal to the minimum profit but we also have the concern that the groups then the total number of members in groups we take has to be smaller equal to This n okay um and that's the problem here now let's see how we can solve it um okay so how do we tackle this well the first thing to think about is there some sort of heuristic you could use um to solve this intelligently and or at least without trying all possibilities but and if you think about it there isn't really anything um and so in that case we just should just try all possible choices as usual if we can't find an optimal way let's just try all of them and then calculate um and so here we want to calculate the number of um schemes that we can choose right the number of profitable schemes and so then we need to just think about our choices well for every crime remember these are the crimes and we get the profit array for the crimes and then the groups that we need where the that contains the number of members we need for each crime okay and so for each crime we have two choices only two choices possible Right you could either commit the crime right or not commit the crime those are the only two choices and so let's just try all both and see what we need now what are the questions that we that the problem says we need for a profitable scheme well the first one is that the sum of the profits for the subset right for subset of the crimes we are taking needs to be bigger or equal to the mid profit okay so that's the first one the second one is that the number of the members in the group so the sum of let's call it group I write for the i in the subset of crimes we are taking right it needs to be within the number of members we have available which is n so this needs to be small or equal to okay and so if you think about this now sort of the state of our recursive function that will need to either commit a crime or not commit has two things well it has first The Profit the total profit of this subset so it has the profit let's call them the profit so far and it should also have the members that we used so far so that we make sure that we don't exceed n and so I'll say mem plus all this member is used okay and what else do we need well when we are looking at crimes each time we look at the ice crime and decide either to take it or not take it which is committed or not committed if we committed we get the profit for it and we need to add the members we needed for it but if we don't commit it then we just move to the next one and also decide and so each time we need to pause at the ith crime and decide whether to commit it or not and then go to the I plus one and so we also need the position so now we know the state of our function which will need to be basically the index right the profit so far so that we can make sure we don't exceed here and then the um the uh the members that we used okay and now the only thing left to do is to determine our use our um our base cases and then the recursion that we want to do now let's first do the recursion well for the recursion we can either take or not take so basically commit or not commit so if we want to commit then what happens so the function calculates the number total number of ways right okay and so let's call it ways then on with this state and so if we want to commit then we commit this crime at I and then we want to go to the next index all right index plus one now if we commit the crime we gain the profit from that crime so we want to add the profit from that crime which is going to be just profit at that index okay and if we commit a crime we use the members in that group right so for example in the first example we have two if we commit crime zero then we use two members okay and so here is going to be the members used so far plus the numbers we use from group at index I at Index this index here right because that's we to commit that crime and get the profit we need to use those members okay now what about don't commit well don't commit is easy uh or don't commit because in that case we can just go to the next index but still keep the same profit so far right and the same um members uses right because we use the same um because we didn't take anything so this is of course going to be I plus 1 because we go to the next state and what do we get from these well we want to get for each state all the way to the end we want to get if it was valid scheme or not if it was a valid scheme We'll add it to the number of ways if it's not we want to add it and so let's call this result and then we'll add the number of ways from each call and that's what we are going to return at the end okay so now what are our base cases um basically the base cases need to determine if when we reach them if it's a valid way or a valid profitable scheme so that we can count it what does counted mean well if we want to count it then we just need to return one so that it propagates to a year and gets added as a one of the ways okay and so the first thing we know that if we reach the end of the number of crimes right and the profit so far is bigger or equal to the minimum profit and the members used is more equal to n then that's a valid way okay and so instead of checking all of these first let's just actually just check the invalid um the invalid base cases and then what's what remains would be just the valve cases so what's one of the invalid cases well if we ever exceed n then that's not valid and so if ever the members used is bigger than n then that means we violated this condition and so we can immediately return this is not a valid way so we'll return zero okay now what if now if that's if it's within members use it but we reached the end of the group so we there is no more crimes to commit or not which basically means index is equal to the length of the group now in that case okay in that case what should happen well it depends on here if the profit is smaller than the minimum profit then that's not a then that's um so if prob fits so far is smaller than the um the minimum profit okay what does that mean well that means it's not valid because we didn't reach the condition of at least minimum profit so in that case what does not valid mean we can just return zero okay now the other case is what if the profit the other main case means basically here that the profit so far was bigger or equal to minor profit and so and the members use it is small or equal to n so that means both conditions are valid which means we have a profitable scheme so we should count it now counting it just means returning one because then it will propagate um to the result colors and then we will add it up and we'll return it as this here and that's pretty much it um so just try two choices try the two possibilities commit or not commit and add the way add home however ways we get from those to our result and then in our base case we'll check if it's a valid scheme profitable scheme will return one if it's not in this case will return zero okay of course there are a couple of things we need to do one is we need to add the mud here and the other thing is we need to also cache because if we don't cache we will call the function multiple times with the same input and that will recalculate everything and so we want to Cache or memorize um in this case but that's this is the main logic so let's just write it make sure it passes um okay so I type it here just what we saw in the overview so we have our function here um and then what we want to do is um we have our base cases here sorry about this um we have our base cases here so if we exceed n that's not valid we'll return zero if it's equal then depends on the profit if the profit is so far is smaller than the minimum required then it's not valid profitable scheme so returns zero but if it's bigger or equal to minimum profit it's valid so we'll return one it's a valid way so we return it and then here we have two choices either take it and so actually let me just show you here so we either take it or not take it okay so if we take it then we add the profit if we don't take it we don't add it and then Returns the result and now we need to call it so we call it with the first index Zero The Profit so far is zero and then they use the zero and return this the other thing we need is of course to use the mud here so let's just Define the mod that we need so 10 to the power of nine plus seven um and then we will need to just modulo it here um sorry about that and then match the load here as well and that should be it now if we run this it does pass on these couple of test cases but it will first exceed time limit exceeded because we are our first calling multiple cases this function here we may call it multiple time with the same input and then it's already calculated so of course we need to memorize that's the first step so if we memorize let's see if that's enough so memorization we can use the same state of the function and so here if this is in our minimization table then we could just return it otherwise we need to store it instead of storing it can be just like this it's going to be the result mod the mod value and then we return it okay let's see if this works um okay it will probably time limit exceeded now why well because this profit so far plus profit index every time it will increase every profit you add but the thing is we don't care about the profit value itself all we care about is whether it exceeds it's whether it's at least minimum profit that's ever all we care about and so because here we have three states and so the number of value variations with these states increases because if it's two it's you have less combinations but with three you have more combinations so can we eliminate one of these combinations well we could eliminate that we could make this one have less possible values because we only care about whether it reaches the minimum profit or not and so what we can do is actually take only up to the minimum profit here because that's all we need if it's bigger then we can just pass the mean profit and this check here will pass and we will get one and so if we have an admin profit then all the bigger values will have the same value for this state and that's basically reduces the number of combinations by a lot and so if you use this will reduce the combinations by a lot let's run it let's see if it will pass and that passes right so this is memorization alone is not always enough so before switching to DP normal DP try to see if there is a way if you have multiple state to reduce the number of values that are one of them can take and that will reduce the combinations I think that's the lesson from this problem um yeah so that's pretty much it for this problem uh please like And subscribe and see you on the next one bye
Profitable Schemes
maximize-distance-to-closest-person
There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a **profitable scheme** any subset of these crimes that generates at least `minProfit` profit, and the total number of members participating in that subset of crimes is at most `n`. Return the number of schemes that can be chosen. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 5, minProfit = 3, group = \[2,2\], profit = \[2,3\] **Output:** 2 **Explanation:** To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1. In total, there are 2 schemes. **Example 2:** **Input:** n = 10, minProfit = 5, group = \[2,3,5\], profit = \[6,7,8\] **Output:** 7 **Explanation:** To make a profit of at least 5, the group could commit any crimes, as long as they commit one. There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2). **Constraints:** * `1 <= n <= 100` * `0 <= minProfit <= 100` * `1 <= group.length <= 100` * `1 <= group[i] <= 100` * `profit.length == group.length` * `0 <= profit[i] <= 100`
null
Array
Medium
885
84
hello friends today less of largest rectangle in histogram as first thing about the proof of solution we just iterate all the bars from left to right and we come by the current bar with preceding bars to get new rectangles for example if the current bar is 5 we know the 5 times 1 is a rectangle and we try to come by this one and 5 get a new rectangle which is 2 times 1 and then we can buy this 2 1 5 to get a new rectangle which is 3 times 1 if we solve this problem use this algorithm we will get the time complexity of Big O and squared but we can solve this problem in linear time which we will use us stack let's see how to use a stack actually we will maintain a strictly increasing stack this is how it works but first thing first what are they mean by increasing stack do we save the height in the stack actually save the index in the stack the reasons are true the first reason is that the height may have duplicate like these three we have two three Heights the region two is if we just saw save the height we will never know the new width the width of the new rectangles so we need to save the index and by subtractors or index we can get the width of the new rectangles that's a reason so by means of the increasing actually we based on the heights we maintain an increasing stack this is simple histogram as we iterate from left to right so the final you know the final increasing stack to the bitter want you because the last parachuter contender in the stack so that's a reason and we may notice that there are two bars between this index 0 industry are greater than the height of heights 3 because I think assume these two bars are lower than the heights 3 but larger than the height 0 we should contain these two bars in the stack so it impossible so if we assume this troopers are lower than the height of zero then we will not contain this zero in our stack so it'll also impossible sewing or if we have these two index in our stack that means all the elements between these true index should have larger tighter than the following height okay so as you may know at first there are stacks the Peter darrall want you because the height 1 3 4 are increasing in there then when we try to append this index 3 chooser stack it doesn't emit 10 or increasing stack so in the to pop some elements from the stack so we can it is 4 and we need to calculate its calculator its area we know that we should use 4 times 1 but how do we get this one actually this is a new rectangle we need to know it's right border and the left border it should appear sweets we already have its height which is a height stagger peak but how about its width we should use 3 minus 1 and the minus 1 because both of this cube on the bounders are exclusive so how to get this one actually it's proceeding index in the stack right so in order to get to the proceeding index in the stack when we try to get a height we do now use peak wheels pop so then we can get the preceding index which is a current peak okay so we get it is 4 times 1 how about then we compare these three and the true we find this reads still greater than 2 so we needed to calculate to the area again then currently we need that you know this is real time is true how to get is to the same idea the right border is two or three but the left border is 0 and we also needed to minus one so the width should be 3 minus 0 minus 1 so we care this which and we do SM see the highs stack pop times the height the you know this 3 - the stack pick - 1 so that's the idea - the stack pick - 1 so that's the idea - the stack pick - 1 so that's the idea and you should know the very cool idea is that all the bars between Q index in a stack should a big greater or equal than the larger index height okay so let us see this example to understand this idea again well first a we will have this there 1 which is 1 3 2 our stack and then we find this is 2 it is less than the 3 so we need a poverty's 3 from the stack so currently the stack should be index 0 2 and height it will be 1 2 then we found this one and is less than the peak of the stack which is true so we need a pop it from the stack and as it is straightly increased deck so we also need a pop this one from the stack so we push this 3 to their stack and we push these three through the we should fall to the stack so that's it okay so the nose you should know that we save the index in the stack notes the height and the importancy I will say again which is the all the parts between I and J should be greater or equal than the heights J and the ones we get is a final increasing stack see this example we catch the increases Decker is 0 3 5 and their height is 1 2 3 how do we get all the rectangles basically the same idea at this place as you may notice that the last part should always contain in the stack so we have the right border is just the end of this array which is you know because the length of this array is an so the right border should also be an and how about its left about is less Boulder should appease 3 right so we do the same thing the height is the heights stack pop and we get its preceding index which is currently the heights peak and there were minus 1 because both of these two boulders are exclusive so we get a new rectangle which is 3 times 6 minus remains 1 then we'll do the same thing the highly is true right then we times still use the right border 6 minus the left of 0 minus 1 actually we calculated this rectangle right 2 times 5 how about this place we should calculate 1 times 6 but how do we get this 6 we still need another left border but it's nothing else in the stack how about we just push a negative 1 in the stack when everything starts so in their case we will get 1 times 6 minus negative 1 minus 1 so to make things simple we can first push a negative 1 to the stack okay so the whole idea is to calculate the widths of the new rectangles and our solution is to use the right border - left border and minus 1 and though it - left border and minus 1 and though it - left border and minus 1 and though it makes things simple we you first push the negative 1 through the stack ok I hope you already understand it let's first let's see these two examples again to help you understand if all the paths have the same height what we have the stack be like we first to push the negative one and then we push the zero and the height is 3 well this is straightly increasing stack so we'll meet the second is 3 we will pop this first 3 and push the new one to the stack so on so forth and finally we cancel this 4 negative 1 and now we do a sync right border is 5 right and left border is negative 1 and we minus 1 again so we now get the area which is 15 this is a whole area what about we have 0 height in the histograms we first push the negative one and we push the zero and the height is three and then we'll meet a zero is less than three so we pop these three from the stack and we push one and we push to the hi days three so on so forth and in the end we use the current height is three times the right border is five left border is one right is one and the we- we minus one so again the width of 3 we- we minus one so again the width of 3 we- we minus one so again the width of 3 so 3 times 3 we get to 9 and we left her 0 the height is 0 and a right border fight left the border negative 1 we - fight left the border negative 1 we - fight left the border negative 1 we - swamp so yes 0 so I hope you understand this idea we just maintain a straight 'le increasing stack and once it can 'le increasing stack and once it can 'le increasing stack and once it can augment I'm straightly increasing we calculated the new areas a new rectangles area and the way we finally get a increasing stack we do the same thing to get to the area of the new rectangles so the time complexity actually is Pico and if you look carefully every element we only calculate once how about the space complexity in the worst case we will save all the same old index cuter stack so it's also Big O so if you understand the idea the code is quite simple we first get the length of this height and we needed we're down a stick array and then we first push there let you punch through the stack and then we need a global variable max and then we just iterate Heights and the wire it violates the straightly increasing manner we pop something and calculates the area so only when there's that could pick now you go to one and the heights of the current pick is greater or equal than the heights Oh current height we need to calculate the area which will be the Heights stack pop times or about the weeds right Boulder is I sorry left border is the current the peak back sorry we do not need to guess the height stack pig minus 1 and every time you push the I because this is our straight idli increases deck ending here so every deck should contain current I now once we get straightly increasing stack we do the same thing the max will be nice the height of the stack of times the right bodies and let the border is stack pick -1 finally return border is stack pick -1 finally return border is stack pick -1 finally return max okay thank you for watching see you next time
Largest Rectangle in Histogram
largest-rectangle-in-histogram
Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_. **Example 1:** **Input:** heights = \[2,1,5,6,2,3\] **Output:** 10 **Explanation:** The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area, which has an area = 10 units. **Example 2:** **Input:** heights = \[2,4\] **Output:** 4 **Constraints:** * `1 <= heights.length <= 105` * `0 <= heights[i] <= 104`
null
Array,Stack,Monotonic Stack
Hard
85,1918
35
welcome back to algo jest today's question is leak code 35 search insert position so given a sorted array of distinct integers and a Target value return the index if the target is found if not return the index where it would be if it were inserted in order you must write an algorithm with o log n runtime complexity so in the first example we have this nums array we have a Target which is equal to 5 and the output is 2 because we've returned the index of 5 here which is 2. in the second example we have this nums array we have a Target equal to two is not found within this num's array but we need to return its position if it was added into this num's array in its sorted position so it would be inserted at this position so as soon as the question is asking for login time complexity for the solution we will be using binary search that way we can actually get a solution which has login time complexity so with binary search we have a left and a right we get the middle which is usually mapped up floor so we'll grab this value here as the mid we check if the middle is equal to Target it's not so we have to do an additional check to see whether this value here is less than or greater than Target and whichever one will determine what condition we apply to that so three is less than five so we know for a fact that the answer will not be stored on this side of the array so we need to increment our left pointer to Mid plus one now we have to recalculate the mid which is going to be this value here we check if the middle is equal to the Target it is so we can just return the index of 5. let's quickly try another example let's say the target is equal to two if we carry out binary search we get the left and right pointer we get the middle value which is going to be equal to three we check if it's equal to the Target it's not so we check whether it's greater than or less than the target the middle value is greater than the target so we know that the value is not going to be stored within this side of the array so we can get rid of this and in order to do that we need to update this right pointer to Mid minus one So Right Moves here now here we need to calculate the middle which is just going to be at the same point we look if this is equal to Target it's not it's less than so anything to the left this won't be considered and we need to consider everything to the right of this and in order to do that we increment the left pointer so here as you can see left is greater than right so the while loop for this question is going to be left is less than or equal to right and as soon as we increment past so as soon as left doesn't conform to this we return the index of left because in the sorted position two would go where 3 currently is so at index one and as stated in the question the time complexity of all this one is going to be o log n and the space complexity is o1 so let's write this out so the left is equal to zero write is equal to non-store length minus write is equal to non-store length minus write is equal to non-store length minus one well left is less than or equal to right grab the mid which is left Plus laptop floor right minus left divide by two we check if nums are mid is equal to Target if it is we can just return mid however if nums at Mid is greater than Target we can reassign right to equal mid minus one else or sign left equal mid plus one and finally we can return left let's give that a run submit it and there you go
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
211
Hello guys welcome oil hot media live today episode 235 problem on August late coding challenge data structure design please like this video fuel forget to subscribe our Channel morning renewal mission update designer data center approach fall into operation from Edward and search and show Su Little Board and Regular Expression String Continuously Letters A to Z and Dot Net Country Present Any One Network Sagittarius States Problem Clarify the All Matters Will Only Work as A in This Question in Existence Into Another Privacy Explain Problem in Army During a Recording Dance Remix Print walking the prime detail in this video and cool and service will also recommend you 250 protesting for the effect clear water is telling the video of the top and also in description moving forward s be clear with the basic idea of ​​traveling data structure with idea of ​​traveling data structure with idea of ​​traveling data structure with examples sony Six And Wool Invariable Indicating And The World In To Dip Look Like These Flash Lights Focus Attention To More Easy Method In Case Of Getting What Will Stop Taking A True Talk Opinion Entertain Pimple Distance From Every Time With A New World Will Start With The Root Of Every Character in the World Which Gives the Character English Not Visible Checking the Character Indexes No Affidavit Simply Create a New Object Woolwich Update Temple One to the Child After All the Characters Who Travels Attempted Suicide Note Swimming These End Eggs and Two Not Bays Updating Leg Piece Complications Of them into dowry question latest discourse implementation more but admitted to all characters 9th cat-Ranbir water effective characters 9th cat-Ranbir water effective characters 9th cat-Ranbir water effective this phone logic and lentils white and the return of the day Neeraj Gaur note drop union parameters in case of witch exists without mintu part set a parameter in Second Me To Know The Character To Search And Quantum Dots Sunidhi Indexes Parameter Listen And Helper Method Absolutely This Let's Notification Logic Medal Contenders Character Recent Me How Dot Benefit Can Be Enabled Services For All The Nominal Child Not And All This Function Record Fifth Child And the next question is this result comes true spirit and rule now even after seeing all the child not speak for advance diminishing returns full movie to the spot mintu rider logic in that is not done in this case which given the child not enter character is not Effective notification on to the child in spirit and false discover all cases for the method search results for one day when will search for more words in the simplicity of child is later enter last related to child fruit will be the world cancer day observed quarter right One should observe and give vote no support will need to find what he did as discussed with sleeping daughter to meet from zinc and methodical shivling in this case which column in third phone dubai additional remote site services for in the body as well for all The letters in rich the world vision for this award flag and asks it's true with simply return true time complexities of temple well defined and after mintu in father scam in all characters hair's length in all characters hair's length in all characters hair's length number 21 space complexities of when we fight when the question Exam Question Paper Maths Class 12 Thanks for Watching the Video Flag Video Please Like Share and Subscribe Our Channel Latin American Fashion Model Think About the Video
Design Add and Search Words Data Structure
design-add-and-search-words-data-structure
Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the `WordDictionary` class: * `WordDictionary()` Initializes the object. * `void addWord(word)` Adds `word` to the data structure, it can be matched later. * `bool search(word)` Returns `true` if there is any string in the data structure that matches `word` or `false` otherwise. `word` may contain dots `'.'` where dots can be matched with any letter. **Example:** **Input** \[ "WordDictionary ", "addWord ", "addWord ", "addWord ", "search ", "search ", "search ", "search "\] \[\[\],\[ "bad "\],\[ "dad "\],\[ "mad "\],\[ "pad "\],\[ "bad "\],\[ ".ad "\],\[ "b.. "\]\] **Output** \[null,null,null,null,false,true,true,true\] **Explanation** WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord( "bad "); wordDictionary.addWord( "dad "); wordDictionary.addWord( "mad "); wordDictionary.search( "pad "); // return False wordDictionary.search( "bad "); // return True wordDictionary.search( ".ad "); // return True wordDictionary.search( "b.. "); // return True **Constraints:** * `1 <= word.length <= 25` * `word` in `addWord` consists of lowercase English letters. * `word` in `search` consist of `'.'` or lowercase English letters. * There will be at most `2` dots in `word` for `search` queries. * At most `104` calls will be made to `addWord` and `search`.
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
String,Depth-First Search,Design,Trie
Medium
208,746
146
hey everyone welcome back and let's write some more neat code today let's take a look at a really popular interview question lru cash it's even asked by twitch tv it's one of their most popular interview questions and also don't forget to like the video it supports the channel a lot so this is definitely more of a design problem than an actual algorithms problem so we have some kind of cache that's going to store values it has a capacity so it's fixed size and we want to be able to get values from this cache based on a key value if that key value exists then we'll return the value that it corresponds to if it doesn't exist the default value we want to return is negative one and if we're getting values we also need to be able to put values into the cache we're putting them in based on key value pairs and there's a lot of edge cases and they explain a bit of them to us if the key already exists in the cache then we just want to update the value if it doesn't already exist then we're inserting it for the first time so we can put that key value pair into the cache and remember this does have a fixed size capacity so if we ever exceed the capacity then we have to evict the least recently used so that's why this is called the lru cash problem and it also makes sense right if there's a key that we're not really using then that's the one that we're going to take out of the cache and this is actually pretty similar to how browsers work so for example if you're using chrome and you know web browsers have caches if there are values that we're not really using in those in that cache then of course we can remove them let's also try to solve this the most efficient way which is each of these operations get and put are going to be constant time operations and it's going to be kind of tricky but it's definitely possible so let's just look at the first example so the input is two so that's something that we need to kind of remember right the capacity is two in this case and the next operation is put so we're putting a pair of one key one value one and we're going to keep these kind of in order right because we want to remove the least recently used so we got to kind of remember in what order are we adding these values in the next one is another put operation and we're putting 2. of course for these first three operations we're not really returning anything so the output is going to be null so next we're actually doing a get operation and we want to get the value that has a key of one and remember we're trying to do this as fast as possible we're trying to do each operation in constant time so how can we know instantly what the value is when the key is one well the easiest way to do that would be with a hashmap right so we're going to use a hashmap to instantly look up the value of every key we can of course do this in constant time and we know that we the size of this hash map doesn't need to exceed our capacity so we can have only two values here right so for the key value we can use the same value that we use for each of our nodes and we could and for the value we could also do the same thing we could use the same value that we use in our nodes but i'm going to show you why it's going to be a little bit better for us instead to have the value be a pointer to the node itself and we can do the same thing with the second node that we inserted as well so for key value 2 we're going to point at this node so now finally when we call this get and we ask for the key 1 we're going to return the value 1 that's over here which is exactly what the output tells us is correct so since we just used the get operation to get this one we went to our key then we found this value and then we returned that value that makes this the most recently used value and this is the least recently used value now so i'm going to keep track of the most recent and least recent by having a left and right pointers right so this left side is going to be the least recently used and the right over here is going to be the most recent so therefore we're basically going to be swapping these two nodes right and so this part this portion of the problem is starting to keep the ordering of these it looks like we're going to need a linked list and not only a linked list but a double linked list because remember we can easily look up where these values are but if we want to also reorder them quickly by for example every time we use a get operation we want to take this value and then move it over here because it was the most recent and so now we're going to reorder the two nodes so now this is the least recently used and this is the most recently used and since this is a doubly linked list we need the pointers to be connected of course the hashmap won't really need to be updated because these are pointers they're already going to be pointing to the correct ones and i'm not going to show that and now we can get to the most interesting operation the third put so we're putting a third value key value 3 and since 3 is greater than our capacity of 2 then we're going to have to remove the least recently used value and convenient for us we know exactly what that value is so first we're going to end up updating these pointers to make the least recently used 1 and get rid of this and of course we want to replace that too since we know it's the least recently used we want to replace it with the new key 3 and now we also want to update that pointer we want it to point at the new node and since the new node 3 is the most recent we're going to put it over here 3 and the pointer is going to point here this pointer is going to point here and there's going to be a double link between them so this is basically the main idea we're going to keep track of a capacity we're going to have a double linked list we're going to have a hash map where the key of the hashmap is going to be the same key that we get from the input and the value is going to be a pointer to the nodes and each node is going to look something like this and it's going to have two pointers remember so it's going to have a previous pointer and a next pointer and don't forget about this right and this left these are also going to be nodes because we want to have pointers we want to be able to instantly know what's the least recently used and what's the most recently used so these are going to be dummy nodes pretty much so getting into the code remember we're going to need a node so before we even write this lru cache class let's make another class for that node that we're going to use and remember each node is going to have a key value pair so we're going to get those we're going to initialize those and we're also going to have two pointers one for the previous node and one for the next node and they're both going to initially be set to null now when we actually get into the lru class we know that the capacity needs to be stored because we want to know if we ever go over that capacity we also need a hashmap and i'm going to call that our cache and remember this is going to map the key to nodes and before we even have any values in our cache we want to have a couple dummy pointers a couple dummy nodes which tell us what are the most recent and least recent uh values that we added so we can just initialize these to zero for the default values so zero and initially we want these nodes to be connected to each other because if we're inserting a if we're putting a new node we want to put it in the middle between left and right and we can do that with some pointer stuff so left dot next is going to be right and right dot previous is going to be left and remember left is going to help us find the least recently used and right is going to be most recent so now let's start with our get function because it's mostly straightforward if the key exists so if the key is in our cache then we can return that value right so we can return self dot cash of key now this tells us the node remember because each key is mapped to a node so to get the value we can just do dot val and of course if it doesn't exist they wanted us to just return negative one now the only thing we're forgetting with this get is that every time we get a value we want to update it to the most recent so to help us with this part i'm actually going to write a couple helper functions so i'm going to write a remove and insert helper function and these helper functions are going to be applied to our linked list so we're going to pass in the node that we want to remove from our doubly linked list and i'm also going to write a function to insert into our linked list and when we insert we're going to insert at right and the remove is just going to remove from the list so these are basically going to be pointer functions we're going to be manipulating some pointers from our left from our right and doing some stuff so i'm not even going to worry about that i'd all i know is that we have a helper function that can remove any node from our list and a helper function that can insert any node at the rightmost position of our linked list so since we're getting what we want to do to our list is take this node self dot cache of key and remove it from our list and after we remove it then we want to reinsert it at the right most position so we can just do self and looking at this get isn't so bad as long as we fill out these two helper functions for us so now when we actually look at our put function let's remember that if we have a key that's already in our cache that means that a node already exists in our list with that same key value so before we can insert this new key value pair we want to remove from our list so we can get that node by getting our cache and using the key value so these helper functions are definitely coming in handy for us so now we can create a new node with this key value pair so node key value and we can put that in our hashmap so now our hashmap has a pointer to this node but remember that's not enough we also have a doubly linked list so we need to take this node and insert it into our list so insert and just pass in the node which is cache of the key value so the node is stored here and we pass that node into our insert function okay so we just inserted a new value but remember we have a capacity to worry about so every time we insert a value we gotta check did does the length of our cache now exceed the capacity if it does this is the part where we're gonna remove and delete or evict the mo the least recently used so we're going to remove it from the list the linked list and delete the lru from the cache or the hashmap so how do we actually find the node for the lru well this is why we have our left and right pointers remember the left pointer is all the way at the left and it's going to tell us what the least recently used was so left dot next is always going to be the least recently used and so first we're going to remove it from our linked list by just passing in the node and we're also going to delete it from our hashmap so self.cache our hashmap so self.cache our hashmap so self.cache and we want the key of this node which is actually stored in the node itself this is why we didn't only store the value we also store the key in our node class so we don't have to return anything input but we do now have to fill out these two helper functions remove and insert so if you have three nodes and you want to remove the middle node what do you do well you take this pointer and move it over here and you take this pointer and move it over here so this stuff is no longer relevant and we have removed the middle node this is going to be referred to as our previous node this is referred to as our next node so when we're writing this function node is going to be the middle node so we want to get the previous and next nodes of node so we can just get the pointer so node.previous get the pointer so node.previous get the pointer so node.previous node.next node.next node.next all we want to do is say that previous dot next should be updated and next dot previous should be updated these are the two pointers of the next and previous nodes so previous.next previous.next previous.next should be next stop previous should be previous so now node is no longer in between previous and next the last thing we need to do is fill out our insert function which what we want it to do is insert a node at the rightmost position right before our right pointer so let's say this is our right pointer we want to insert right here and this is going to be our previous pointer so when we have our new node that we're trying to insert what we want to do is take this pointer and reassign it to that this pointer and reassign it over here and we also want this node to be connected to its neighbors so we're going to have the next pointer over here and the previous pointer to be here so in this case our previous and next pointers we can get by using our rightmost pointer so self.write.previous so self.write.previous so self.write.previous and self.write now we want both and self.write now we want both and self.write now we want both previous and next to point to node so we can do that like this previous dot next is going to be equal to next dot previous which is going to be equal to node they're both pointing at node has been inserted in the middle of them and node.next and node.next and node.next and node.previous also need to be and node.previous also need to be and node.previous also need to be assigned to next and previous so this is quite a lot of code about 44 lines with some space and comments in between but this is how you get the most optimal solution for this problem and of course i had a bug so i misspelled something i'm really hoping that's the only bug here because i do not want to search for a bug in these lines of code okay so we got it to pass so i hope this was helpful if you enjoyed please like and subscribe and i'll hopefully see you pretty soon
LRU Cache
lru-cache
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`. * `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key. The functions `get` and `put` must each run in `O(1)` average time complexity. **Example 1:** **Input** \[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\] \[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\] **Output** \[null, null, null, 1, null, -1, null, -1, 3, 4\] **Explanation** LRUCache lRUCache = new LRUCache(2); lRUCache.put(1, 1); // cache is {1=1} lRUCache.put(2, 2); // cache is {1=1, 2=2} lRUCache.get(1); // return 1 lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} lRUCache.get(2); // returns -1 (not found) lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} lRUCache.get(1); // return -1 (not found) lRUCache.get(3); // return 3 lRUCache.get(4); // return 4 **Constraints:** * `1 <= capacity <= 3000` * `0 <= key <= 104` * `0 <= value <= 105` * At most `2 * 105` calls will be made to `get` and `put`.
null
Hash Table,Linked List,Design,Doubly-Linked List
Medium
460,588,604,1903
653
welcome to august leco challenge today's problem is two sum four input is a bst given the root of a binary search tree any target number k return true if there exists two elements in the bst such that their sum is equal to the given target so it's a typical two-sum problem we so it's a typical two-sum problem we so it's a typical two-sum problem we want to find out if there's two node values that sum up to our given target so there's really no reason to complicate this we're going to use the typical approach to carry a hash map we're going to use a hash map and using the equation x plus y equals k we're going to keep track of everything that we've seen while we traverse our binary search tree and see if we ever can find the value k minus x inside of our set or hash we'll use a set here so basically what we do is uh first check to see if this value y which is going to be k minus x is inside the set and if it is that means we've seen the value that we need to pair this value with to get our target number k so what we'll do is create a lookup here this will be a default dict and we'll have integers and we're just going to do a typical depth first search passing the node so if not node we just return but what do we want to return here we want to return true or false whether the pair exists or not right so let's make sure turn or false here uh now what we'll do is say uh well it's calculated the y that we're trying to look for so this would be y equals k minus no dot value right so if y is in our l that means we could find the pair for this so we can return it true otherwise we should add our value not the y though the node.value into our not the y though the node.value into our not the y though the node.value into our set so we'll add that value and then we'll keep traversing the dfs no dot left and we'll say or dfs no dot right so as long as one of these is true that means we could find a pair right so all we have to do then is return the for search with the root and this should work this should be it oops if y is that's not in y in that's my fault again we don't need a default dick we just need to use a set okay so it looks like it's working so let's go and submit it and accept it so time complexity wise we're going to worst case be of n because we'll traverse through every single node and we'll have the same amount of space of n because of our set so it's really not any different than how we would solve a typical twosome problem it's just that we're traversing a binary search tree this way okay everything else remains the same thanks for watching my channel and remember do not trust me i know nothing
Two Sum IV - Input is a BST
two-sum-iv-input-is-a-bst
Given the `root` of a binary search tree and an integer `k`, return `true` _if there exist two elements in the BST such that their sum is equal to_ `k`, _or_ `false` _otherwise_. **Example 1:** **Input:** root = \[5,3,6,2,4,null,7\], k = 9 **Output:** true **Example 2:** **Input:** root = \[5,3,6,2,4,null,7\], k = 28 **Output:** false **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-104 <= Node.val <= 104` * `root` is guaranteed to be a **valid** binary search tree. * `-105 <= k <= 105`
null
Hash Table,Two Pointers,Tree,Depth-First Search,Breadth-First Search,Binary Search Tree,Binary Tree
Easy
1,167,170,1150
373
Adam is back again with his daily news challenge and today's question is a medium level problem, this question is already sorted and what we have to do is to create an element which will give us number one. We have to take from and one elements and that leg should be such that the one which is equal to it is the minimum and in this way how many legs do we have to create, so if we see then what we have to do is we have a story or a story, whatever is there in it is the minimum thing. Every time if we see, like 11 can be made with 17, 11 can be made with four, 11 can be made with six, then story na kahani, this is what we have, is this one of ours, so it is complete, do we have to do this, do we have to keep something? Brother, I am already happy with this index, so what will we make for it? We have also asked the question of what is behind, yesterday also, so what do we make negative in such a question, why do we make it negative so that our time complexity does not increase much, okay? So, let's start first of all, we have made the saree Sapna, the size of both can be different, hence I have given the answer, now we have made the answer of vector, we have made a set and we have made a set of pairs, brother, these two are what we have. We have already gone through the index, so for that we will have to make pairs. We have to make a set whose name we have taken as waste and 1 minute. Our priority is fine, we will keep it less and now after making the priority, what have we done? Not the first but the first, if seen in the ascending order then the one who is the first to index is the smallest of the two. Now English Pride should be like this, there is no sending. The one who started among the two has some smallest and the smallest if we pace them both. If we do, then it will also be the smallest, so that will be our possible answer. Okay, so what did we do with that? We pushed it, so in PK we said that if you pushed then we added zero plus zero before the name, so first of all we By asking this, we have pushed what we have here as well as in our inspector on various other things. To make such trees, we said, brother, isn't our mean empty? It does n't become negative. These two conditions do not become negative unless our Till the time we are not satisfied, what will we do? We put our auto and we put a top in the auto and what did we make of the top, what have we made, brother, we got PK's top stored in the top and whatever it is, what is there to fear from PK? Now after getting the pop done, what did we do, brother, we did this index, this induction, okay, we have done this much, but along with this, what do we have to do in the answer, brother, which name is that and along with this- Also, if it is not even widgetized, and along with this- Also, if it is not even widgetized, and along with this- Also, if it is not even widgetized, if it is if widgetized, if it is not being found, then which of our phones is not fine in I Plus One and K Ka Te, then what will we do? Update I Plus One and also whatever is widgetized. And insert whatever is there in the widget Here it will be K plus one, it is a small mistake and this is ours by permitting.
Find K Pairs with Smallest Sums
find-k-pairs-with-smallest-sums
You are given two integer arrays `nums1` and `nums2` sorted in **ascending order** and an integer `k`. Define a pair `(u, v)` which consists of one element from the first array and one element from the second array. Return _the_ `k` _pairs_ `(u1, v1), (u2, v2), ..., (uk, vk)` _with the smallest sums_. **Example 1:** **Input:** nums1 = \[1,7,11\], nums2 = \[2,4,6\], k = 3 **Output:** \[\[1,2\],\[1,4\],\[1,6\]\] **Explanation:** The first 3 pairs are returned from the sequence: \[1,2\],\[1,4\],\[1,6\],\[7,2\],\[7,4\],\[11,2\],\[7,6\],\[11,4\],\[11,6\] **Example 2:** **Input:** nums1 = \[1,1,2\], nums2 = \[1,2,3\], k = 2 **Output:** \[\[1,1\],\[1,1\]\] **Explanation:** The first 2 pairs are returned from the sequence: \[1,1\],\[1,1\],\[1,2\],\[2,1\],\[1,2\],\[2,2\],\[1,3\],\[1,3\],\[2,3\] **Example 3:** **Input:** nums1 = \[1,2\], nums2 = \[3\], k = 3 **Output:** \[\[1,3\],\[2,3\]\] **Explanation:** All possible pairs are returned from the sequence: \[1,3\],\[2,3\] **Constraints:** * `1 <= nums1.length, nums2.length <= 105` * `-109 <= nums1[i], nums2[i] <= 109` * `nums1` and `nums2` both are sorted in **ascending order**. * `1 <= k <= 104`
null
Array,Heap (Priority Queue)
Medium
378,719,2150
298
because it is called banares chilangas cannes and tips and queens it is a super simple thing they ask us is that they are going to give us a tree with the node of a tree and we have to find what is the most realistic list of consecutive numbers and a high amount of consecutive numbers that we can join with the new ones in this tree, no, so for example in example 1 the most serious thing is 3, 4 and 5 stress in these two classes 2 and 3 cannot be done in reverse, it would be good if they could be done in Inversely, it would give it a complexity to extrapolate, since it doesn't have it, then it is very easy to do. Let's go for a max variable that will be global. So if root is different from null, we will call a helper function to which we will pass the node and one what does it mean that we have a constructive value that would be the same end we return max which is going to be our helper function this is going to be this to put current or by law counts is going to finish the maximum of max and camps then well you're going to see if rutte is null or root modes both are null then do nothing if not then let's see if root lifter is null if not null then let's call this function helper on cancer is let's send ruth point left but we are going to do the consecutive one like this if ruth point plus one is equal to point the point ok means that the next one is not consecutive from this one so we are going to send a with camps plus one if not we are going to give it a 1 just because Well, it resists counting, that is, we don't have more constructive numbers and do the same with the right wright node and this must be it again. I made a mistake with my raids, wright elected the time. I'm confusing them, the order that goes, the h and the and you don't know how desperate I am that this would impose this is the solution and this is all I know
Binary Tree Longest Consecutive Sequence
binary-tree-longest-consecutive-sequence
Given the `root` of a binary tree, return _the length of the longest **consecutive sequence path**_. A **consecutive sequence path** is a path where the values **increase by one** along the path. Note that the path can start **at any node** in the tree, and you cannot go from a node to its parent in the path. **Example 1:** **Input:** root = \[1,null,3,2,4,null,null,null,5\] **Output:** 3 **Explanation:** Longest consecutive sequence path is 3-4-5, so return 3. **Example 2:** **Input:** root = \[2,null,3,2,null,1\] **Output:** 2 **Explanation:** Longest consecutive sequence path is 2-3, not 3-2-1, so return 2. **Constraints:** * The number of nodes in the tree is in the range `[1, 3 * 104]`. * `-3 * 104 <= Node.val <= 3 * 104`
null
Tree,Depth-First Search,Binary Tree
Medium
128,549,1416
219
contains duplicate part two so given an integer elements and integer K written through if there are two distinct indices I and J in the array such that number is equal to num sub J and the absolute difference between the I and J is lesser than or equal to K so what do they mean by the question um let's say the array current is 1 comma two comma three comma 1 which they have given and the K value was 3. so we have to find the two distinct integers but the indices must be different and we you could say in the array one and one are equal and I is not equal to J that means the positions are different right so If You observe the index this is 1 0 1 2 and 3 so 3 minus 0 will be 3 which is less than or equal to K is nothing but three so what if we have that a one two 1 3 then K is equal to 3 in this case the difference between 2 and this is 1 which is equal numbers example zero one two zero one and two so two minus 0 is 2. it is not lesser than or equal to Q let's continue it's not satisfied hence the return false in this case so this is the problem they have given so what is the approach to solve this problem usually what we can do if let's say the integer is given right so one two three one so you take the first integer and you give a nested Loop i n one and the J one more variable so I will start from 0 because J will start from I plus 1 to variable that means you couple each element with all other elements in Array one with two one with three one with one and when you are comparing you check whether the elements are equal terms of I is equal to one of J and also you have to check whether the absolute difference of uh so absolute difference of I minus 0 is lesser than equal to K so once you first do the first one next two then single elephant but uh this won't be some since this is having a complexity of pick of n Square uh this won't be suitable for the larger RX so what do we have other approach better optimal approach to solve the problem so if you say we can use the hash table right so once you have this now you have the array elements one two three and one and K is equal to 3 as We Know right so at first you run the fall look right so you'll run the follow the volatile the first step now check whether map dot contains of we have the inbuilt function in uh that is contains key to check which particular Keys present in the hash map or not so this hashmap s the data type will be integer command integer because the key is also integer and the value will also be integer value is nothing but the position the K is the element here of the array value is the position of that element this key and this is value so both are integers so integer common integer you have data type map is a hash map which you are using me so map dot contains K of what we have to look for now I'm Supply as I said it's an element we have to look for the element since element is a key we have to check whether this particular element is present or not if this is not present if this returns false then what do we need to do we have to add that particular uh element and the corresponding position to the hash marker so map Dot put off I element and the value is positioned that is I so this you do if the hashbook present contains the particular element key in the particular element in the hash bar so what if it contains a particular method as well let's say you start with one which is where the mapler contains of numbers of pi one is present in hash map one or no it's not present and still you do map dot put off terms of I comma I so nums of I is 1. and this position is 0 I is zero so this is added to the hash mark okay now you move to the next position again you check Lambda contains K of number five is two is present in Hashem one value is that's why you should add that also so map dot put up numbers and that's position is one fine next you go to the next element similarly map.23 go to the next element similarly map.23 go to the next element similarly map.23 is not present then you have three so yeah its position is two so you write to here fine so next again you move further notice that map dot contains K of number five whether one is present in hash map yes it is present in hashma this is a key value rate one now once you get the particular key value that comes magnified you have to check and condition also that is you have to check the difference what all difference we have to do whatever the position we have got so mad Dot as I said math dot absolute difference of the previous position is nothing but since we have got that particular key is present in hashman that means this particular element is appeared somewhere before in the array so that is this position so map that absolute off you have to find the difference between this and this position so how do you get the dispersion the position is nothing but the value of the this value so value is zero like how do we get the value not DOT oh sorry map dot get off I so by this you get the value that is zero minus whatever position you have that is I right so in any case anywhere indirect you will find that this particular case present in the hashma of already then along with the this condition if this becomes true we have to check out this connection that is the absolute difference between the value of this key minus the particular position where you got the matching key please nothing but the value of the element in that so if both of these conditions become true okay now you find the difference I know to check whether that is less than or equal to that is very important if both of these conditions become true then you add that particular uh then you would just return to if all operations are done and you get still false then uh you don't find any matching elements you may not find the matching limit I mean if K is equal to 3 so about it so a very basic simple thing if it is pressing along with that check the absolute difference between the maximum value and the position at which you got the matching element then you the difference should be you check whether the difference is less than or equal to K if both is conscient satisfied then you're written through otherwise you will false it by the end of the Earth so quickly we'll code this so map integer yes okay and let the name be map equal to U h okay so after this yeah directly run the file for end I equal to 0 I lesser than startling and I plus it first let us check if map dot contains these gaps K is of what terms of I along with that what you have to check the difference so my DOT dot absolute difference of m dot get off numbers of I so you get the value minus I if that is less than or equal to a if both is completely satisfied then you written true so if in case map dot contains K becomes false then you have to add that particular after all this condition if none of these cases happen and this reason becomes true then you return false yeah could see this cases has been passed yeah it's been successfully submitted if you have any notes please drop it in the comment section will come up with another video next session and until then please subscribe to the channel and keep learning thank you
Contains Duplicate II
contains-duplicate-ii
Given an integer array `nums` and an integer `k`, return `true` _if there are two **distinct indices**_ `i` _and_ `j` _in the array such that_ `nums[i] == nums[j]` _and_ `abs(i - j) <= k`. **Example 1:** **Input:** nums = \[1,2,3,1\], k = 3 **Output:** true **Example 2:** **Input:** nums = \[1,0,1,1\], k = 1 **Output:** true **Example 3:** **Input:** nums = \[1,2,3,1,2,3\], k = 2 **Output:** false **Constraints:** * `1 <= nums.length <= 105` * `-109 <= nums[i] <= 109` * `0 <= k <= 105`
null
Array,Hash Table,Sliding Window
Easy
217,220
299
In the second question of 13, let's see it in this, as if here we have got the input, then what do we have to do in this [ then what do we have to do in this [ then what do we have to do in this This is an example, give this example, so as if this is our secret string, this is our gas string. In this, we have to tell how many Kos are there in Gulshan, then what are our Bulls, like which is the secret string and gas is the string, if any digital is read from the index, then it is like 1 digital here is 8 and come here. If it is from both then it means but this index is 7% here so van but this index is 7% here so van but this index is 7% here so van here at this place we have it ok now as we have 7 it is not present in the index but it is definitely present somewhere else so it means If we have a house of three, then what will be formed finally, let's see from the beginning, like we have a secret string, a gas string, if there is a digit lying in the index, then it means that it has become one of the balls, if there was another SIM lying there. So it says two, if someone else had read it in the index then I say three, so here there is only one digital, from the index, one is spoken, then after that, now let's see, but if there is a need somewhere else, then it means I am and then zero, now we will see this here, as if we have van here and van se is lying in the index, then it means that if we say van, we have it, and now we will see how many couches, like we have van here, so this se The index is lying somewhere else, it is lying here, so it has been read twice, it does not matter to us, the van here is ours, is it present in it, and somewhere else the index is present, it is ours, it means van. It is okay now like if you have not read Tu Kya Spring Mein Present Hai, then we will not count it, so we have to tell only how many tools are there, if any present is lying in a different index, we do not have to give it, like we have to give 'A' instead of 'Bulls'. we do not have to give it, like we have to give 'A' instead of 'Bulls'. we do not have to give it, like we have to give 'A' instead of 'Bulls'. In place of b we have to give 1a 3b, we have to do it like this, so we will do it like this is our secret string, this is our gas string, so the secret is a hashmat, we will make two hash maps in it, we will make one for s, so this is my s. This is my wish, so like now we will calculate its frequency that how many times it is present in S, like here it is present once, so it is present once in it, then how many times it is present in zero, here also zero van. Once it is present then now like if it is equal then it will be zero so if when we get equal then we will just enrich the bulls one Now what will we do for Kos, for couch we will see in our Hass map then which is our This is the fate of our secret, so for the first time, first of all, we will look at the van in front, is the van present in this, if the han is present here, then we will stop the course, okay, we will increment, then after that we will see the zero, this is the zero. Is mine present in it? Han zero is also present in it, so now if we increment it by one, then this increment is done, ours will become you, it will become 3. If you do n't understand, now let us see from this second example here, like, how will the mistake be resolved. So the bulls will be zero in the book starting, so if we get the digital from the index in the starting, then we will just increment the bulls by one, so here there is only one meaning, there is only one country which is cement, so the bulls have become our van, okay. Now let's look at the couch. Now to get out the couch, we will have to make two Hashmat. One is of S. One is of gas. This is our secret. our gas. This is our secret. So now what will we do in it. How many times will we present in it? Ours is present only once. 2 How many times is ours present once? Now if we see in G then it is zero, ours is zero, so in the return of our van, first of all we will see the van from here. Okay, van, is it present in this? Han van. If it is present in this, then those who will increment each one, we will increment to see how much value is lying here, the van is lying here and how much has grown here, you are lying here, then we will find the minimum of both of these. For example, there is a van lying here, then the minimum of these two is found out, then their minimum comes out to be zero, there is zero lying here, there is a van lying here, then the minimum of these two comes out, its value is its van, so the van comes out to be seven here. If you have read 'Seven is lying here' then only 'Van' and ' here. If you have read 'Seven is lying here' then only 'Van' and ' here. If you have read 'Seven is lying here' then only 'Van' and ' Van' of 'Van' comes. Now as the van is Van' of 'Van' comes. Now as the van is Van' of 'Van' comes. Now as the van is lying here and the van is also in G, then whatever is its value, the van is here, it is okay and you are here, then which of these two The minimum will be that it will be added to the couch. What is the minimum of both of you and Van? And here there is Van only once, so this is our secret string. Seeing this, how will ours be formed if Van is present anywhere in it? Gas Ring. So our that how will it be incremented in how like van will be the first has map, first of all we will wake up the van then it will see in the gas whether it is present in it, in hastmaith if han is present in it then we will see its other values like the values ​​here There is a van there like the values ​​here There is a van there like the values ​​here There is a van there and you are here, so whatever is the minimum of these two, we will increment it in the course. Okay, so if we ask this question, then first of all, what should we do in this? How much will it be, it will be zero in the starting and how much will be our bulls in the starting, that will also be our zero. Okay, for the secret, if it is for a gas, then what are you storing inside the hashmat, like if it is a string, then first of all, van nickel. So this van is a kind of character here because it is a complete string so the frequency of the character and beyond that means how many times it is present, once it was present then it is waiting for us, so we will take the character and waiting for it. Character character and wait, so this is my new hash map, so we have to make two hashmats, so now we have done the next step, our two hashmats are made, so now we have to get the first character out of it. If we have to get the first character out of it, then first of all we will get its length. We will traverse that much, then we will extract it, follow up, first of all we will extract the character in it, if both these characters are to be incremented and if it is not done by both, then we will store it. It is okay. If the character comes out first, then this is the character. So if we take pickle then we take another character then both of our characters are gone then we will check ok then we will check if it is not from both then what we had to do like if it is not from both like starting sir plus van So what does this mean, what will he do, like which character had come in the starting, if our van character had come, then in the starting, our hand would be completely empty, then if he checks the gate, then it would be empty here in the gate, then this Zero will tell him that there is nothing in it right now, then he will do plus van and put # in it and if like here we # in it and if like here we # in it and if like here we take van man that van is bigger than before like second time is present then what is this? If it does a gate then if it will not get it then it will get zero then it will make a plus van and put it inside it and if it is already present then what it will do is just increment its value by one plus, now we will get less than this in P. If we want to do the same then we have to put it in P. Now both are different, so we have to put its value in P. This is our Gmail photo to the G character. Now after this, with less than this is ours, it will be complete. And we will know our number of bulls, so now what do we have to do, now we have to know that whatever we have made, first of all we will come out once, you will come out once, three will come out once, like in this, vans will come out of 20 nickels, then most of them will come out. First we do this step, then we go, our van will come out, so now we have to see whether it is present in the G. If it is present, then we have to find out its value and the smaller one is the one. If you want to add it in Gmail, then okay, so first of all we will check whether it is present in Gmail or not, what does it contain, if it contains Gmail, if it does, then both its values ​​will be extracted and the both its values ​​will be extracted and the both its values ​​will be extracted and the minimum one will be added. So, first of all we will find the minimum, then to get the minimum, we do Mac dot min. Now we will find the minimum of both, from that we add S dot get the value of this character that will come out of it, then the minimum of these two will be Ours will be added to 'K', so what will happen to us now that Ours will be added to 'K', so what will happen to us now that Ours will be added to 'K', so what will happen to us now that as 'Jitni' will be 'ours', as 'Jitni' will be 'ours', as 'Jitni' will be 'ours', we have got it but we have to return the final answer like ' I' so what to return, what to do, we have to return, I' so what to return, what to do, we have to return, I' so what to return, what to do, we have to return, first of all our 'B' will be added, so this will give us Have to return, our 'B' will be added, so this will give us Have to return, our 'B' will be added, so this will give us Have to return, our final answer will be this, okay, so let's run it once and see if there is any mistake, then we will know, then let's see if the mistake happens, okay and this secret of ours will be copied everywhere Yes, copied everywhere Yes, copied everywhere Yes, even gas. Let's do it while speaking, I take it to everyone Instead of this, I take the secret and where else did I run the setting here and if I run it, then it is still our fault, so what is the fault now brother, so is he my husband or not? This is happening including us
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
328
hey how's it going so today we are going over leeco's 328 question not even link list given a single linked list group all odd nodes together followed by the evenness please note that there are we are talking about the nodes number and not the value in the nodes we should try to do it in place uh the program should run a one space complexity and oh notes time complexity um so if our input is like this uh you can see that um the output is like this is because um it start so you can see the first note is considered odd the second note is considered even and so on and so forth so you can try to imagine this is the first note second no third note fourth note fifth note sixth note seventh node so basically we put one three five seven and all the r nodes uh place odd places nodes into uh the first few nodes um followed by all the even uh place uh notes right so uh basically you can imagine that it's like index one base instead of index zero base so one three five seven all at the front followed by the all even places numbers right uh yeah so um our solution is also based on the idea basically we can create a uh even linked list putting all the even nodes even uh notes inside of the linked list and we can create an odd link list and put all the odd place odd index place nodes in that list and at the end we just have to add our even linked list behind our um odd link list right so yeah that idea is like that um so yeah this is our um this is our like example and uh later we'll use that but first let's um just uh write the corner case where uh our given link class is the empty one so by the way if hat is none is the same as if hat is not but in python you can write it both ways so if hat is none return none um and if hat is not none then we can create a our odd list and uh it's at the hat so yeah let me just write here um our odd is right here right this is our first odd and our hat is given it's also here so our even is at this place right so our even is actually hat dot next yeah our hat is here so our even is head.next so our even is head.next so our even is head.next and we also have to create a pointer pointing to uh to this one that's because remember at the end we have to add our even link list behind the all linked lists so we have to know the head of the even linked list to in order to add it right so the even head is always here um even hat is equal to even um so it will never be changed it's uh it's always here so and we write our while loop to traverse our uh list so well ethan is gone and even dot next is not none um and uh so our odd is right here right so uh you can see that in our note uh each note has a next pointer so our um odds next um this pointer is actually pointing to this number right so this number is actually even dot next right so it's actually even.next is the right so it's actually even.next is the right so it's actually even.next is the number right so and uh in order for our um odds really going from here to here we have to add odd equals odd.next odd equals odd.next odd equals odd.next because this statement only says that our odds pointing to this one but in order to really have our uh traversing to go into the uh this position we have to say odd equal not next after we handle our odds uh then let's handle our even so even.nx even dot next is our odd.nets so even.nx even dot next is our odd.nets so even.nx even dot next is our odd.nets right now right our even x is our odd next right yeah so and uh in order again in order for us to come from two to four we have to say even equal even dot next okay
Odd Even Linked List
odd-even-linked-list
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,3,5,2,4\] **Example 2:** **Input:** head = \[2,1,3,5,6,4,7\] **Output:** \[2,3,6,7,1,5,4\] **Constraints:** * The number of nodes in the linked list is in the range `[0, 104]`. * `-106 <= Node.val <= 106`
null
Linked List
Medium
725
34
hello welcome to my channel today we have leeco 34 find first and last position of element in sorted array so given an array of integer nums sorted in ascending order find the starting and ending position of the given target value so if the target is not found in an array so we turn negative one and negative one so um the follow-up is uh we have to use it the follow-up is uh we have to use it the follow-up is uh we have to use it in time capacity of log of n so yes we will just start with longer than this solution so you can see the example one here input a sorted array in here and we're finding target eight so the output will be two digit which is the first is which is the lab first position and right first position so um you see eight is the first position in the left side switches three and here and the right i mean another eight is four so output three and four is a position so in the another case uh example two we're looking for six but we don't have six in here so there's not nothing no position that we can find so negative one and negative one same as the example three um yeah if in this case it's only have one eight is left two a in this position so the output will be 3 and 3 because you're looking for the left side as the first appear as this position then with output 3 on the right side you first appear in this position which is 3 also so this is the question itself so basically we can make this uh question become a two binary source uh example so we can first have the first element search through the first element by cutting in half if is the middle one is not is bigger or smaller i mean bigger or equal to the target then we swing this right swing it to the left side yeah and then if it's bigger than target then we put find it from the right side that's how we found the left one white one we can see in the later part first we can have the basic output first will be started with negative one so i just write down everything the template first so now we have output 0 which is the left search we taking nums and target and output one is right search nums target right here and okay then we start making the let's see we make the first left search first i take in nums and the target so we started with index uses negative one as a default now we have n star equal to zero in n equal to num star playing minus one we have start even beginning and start the end and while this is really important start less or equal to n events equal we seem to find it then we have a mid this template of the binary search star plus n minus star divided by two so we have the mid pointer right now so the condition is if nums mid bigger or equal than target then n equal to mid plus i mean mid minus one that's what we mentioned about else f um mid smaller than target yes then star is equal to mid plus one and so after we move this pointer like um after we move this pointer and then we now we check if num mid equal to target or not if that's the case and then return actually let me see give me a second yeah things we keep track of we have this condition start less or equal to n then we always keep that uh integer updated to the midpoint at the end the midpoint should be um keep track while the last time that number equal to target then we'll return the index as the result if this condition never met the default value will be negative one okay and this is the left search now we finish the left search and then we have to finish the right search integer it's really similar every similar things write down every similar thing first won't explain again so until now mid is equal to start plus n minus star divided by two if um now is the tricky part with nums mid we're looking at if mid is bigger than target um then and it's equal to remove n right away else if it's not mid less than or equal to target right and at that time we can keep searching because it could have the right side might still have the duplicate target i will keep track on the target location and push that range to the right side and after that the same in here keep track of every midpoint which is target location if this is case index equal to midpoint at the end updated the index already then we turn the index value now we have a write search left search and right search done and we return eventually we turn the output first element second element output to output let me return the output and that's it sounds good okay and then let's see you submit it and it beats 100 uh basically this is the idea of solving this problem it's really essential to try out this solution and get to know the edge cases in every position you see how wise equal here wise like this writing and how you push the left boundary and right boundary right here and it's really essential and then if you know this solution and then you can solve a lot of cases in the future so if you have any questions please comment below and i will see you in the next video thank you so much 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
986
Hello hello guys welcome back to years in this video you will see how to find the interview list interactions with this from list co 23rd the match 2016 personal problem statement problems that were given to list playlist of interviews were pulled in water no need to the INTERSECTION OF INTERNAL subscribe to the Page if you liked The Video then subscribe to the setting interrupters from 40000 avoid 102 I have included doctor intersection from zamin paun inch subscribe and subscribe the btmono true pair 12812 2nd one is equal to the The Present In Ascending Order Descending Order To Give You Problems Clearly No Subscribe To More Post Interval Is From 12811 2016 In The Second List They Have Only One In Trouble From 10 In This Page You Can Directly Reserve Overlapping But Only At One Point Services Overlapping Delhi 1.1 Services Overlapping Delhi 1.1 Services Overlapping Delhi 1.1 Starting End Even Point Will Be Same Soul Will Have To Introduced Name 8 Oct 10 One Special K Swar This Problem Don't Look At The Different Possible How Do Subscribe My List 2 And At Least Two two sometime intersection no latest two in this case to will follow the same method of one is great think what does 2 and does great think what does one strong contrast interaction between avatars and condition here you can see The Evening Organic Waste to Okay This is Correct Events Se Zinc and Sudhir and Interaction Between Two The Thing Will Also Request You to Give One to Two If Out of Bones and Interaction in This Is Not Fair Look at this place for years with similar Ashok Chavan initiated a request to do and one should listen equal to you can see but you should be greater than equal to one but this is not true or not to give one to do you find what is the subscribe The setting on two to the maximum off karo chanak 2nd minimum of even ko my two pure maximum office match 2020 Thursday two day inter subscribe Video then subscribe to the Page if you liked The Video then subscribe to The Amazing Newspaper Quote of Bounds and Beatty Argad That Forms of Sweet Starting at This Point in the Cases of Civil Supply the Same Condition Will Want to See The question is the value of bunny calls to the value of The Daily Beast Quest For Truth In Winter Session And Test Your Knowledge With Maximum Of Which Is The Meaning Of The Word Values ​​Which To Two Will Have Of The Word Values ​​Which To Two Will Have Of The Word Values ​​Which To Two Will Have To Push 124 Setting Show Will Enter This Point And There Are Five And Very Sogdu Increment No You Will Have To Send Increment The Value Of This Is Value 22512 subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Page Will Give The Name Of The First Values Post Admin 1514 Kill Enemy Minimum Of The Second Value Certain 52555 Not a Single Point Will Get 2019 Directly subscribe and subscribe the Channel Will Keep Repeating 12558 12512 Distance Between This is the 123 Approximately 1200 10 days 300 This is Winter Session No Veer 11223 Subscribe Intersection 15231 More Maximum 12345 000000 000 blind interactions and you Can Clearly See That The Intersection More Minutes Ago Ajay You Can See The 2016 More Research Edison Intersection And Winter Fashion Point Will Be Maximum Those Chapters Subscribe to the Page if you liked The Video then subscribe to the Page Play List in Order to Process List Na Dhan Se Zoom Interval Se Don't Push Forcefully This is the Processing in the subscribe our YouTube Channel and subscirbe Interview Maximum of the Meaning of the Word Values Into This Temple Run Will Return Subscribe Point To The Point Will Check The Values ​​Of Point To The Point Will Check The Values ​​Of Point To The Point Will Check The Values ​​Of Phantom And Villain Parde Hai Haldi Operations Simply Will Have To Return The Results Final Year Result So Very Simple Process And I Hope You Enjoy The Problem Tarf And Solution In Different Languages ​​In This Post With Everyone Can Languages ​​In This Post With Everyone Can Languages ​​In This Post With Everyone Can Benefit From Like share and subscribe
Interval List Intersections
largest-time-for-given-digits
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`. The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`. **Example 1:** **Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\] **Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\] **Example 2:** **Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\] **Output:** \[\] **Constraints:** * `0 <= firstList.length, secondList.length <= 1000` * `firstList.length + secondList.length >= 1` * `0 <= starti < endi <= 109` * `endi < starti+1` * `0 <= startj < endj <= 109` * `endj < startj+1`
null
String,Enumeration
Medium
null
461
Hello Everyone Welcome To My Channel Today Solved 5MB Problem Having Stand All Mintu In Tears Is The Number Of Position Which Corresponds With Different Activities Hey Wow Calculate Distance Between 02351 Then Subscribe The Channel Different More Than 1000 Dravid And Virat For Example 0 Ki And 400 Support Him And Distances A Different Souvenir 2.1 Android 4.2 Different Souvenir 2.1 Android 4.2 Different Souvenir 2.1 Android 4.2 Midnight Se Subscribe Number To Subscribe To That And Demerits Of Different When Will Give Divine Souls Will Help To Solve Will Take Care Of The Number Six Speed ​​Come 108 Care Of The Number Six Speed ​​Come 108 Care Of The Number Six Speed ​​Come 108 Number Of Account Number Off 200 Om Vipal Use Flats Implement First Basic Implementation So What We Can Do Will Just Simply Returns And From This Very Simple Liner Solution Written In Tears Will Regret Being From The Guide Subscribe To That If Chords Compiling Embedding Correct Answer So Let's Submit This That Antiseptic Is This What They are doing everything library method is loot related high fuc oo can not be used in village side third subscribe The Channel Please subscribe And subscribe The Amazing will check the a pan mode on to busy cursor for this is not where taking no In writing significant best office number what is this effective will count plus other wise vivid and will return account is members of what bihar writing and custom hate you can any number of side in isro it is compiling and zinc and marketing correct answer subscribe implementation the city has Accepted A Souvenir That Medium To Find The Number Of Side Effects And Number Of Bones In Number Using Back Sexual Addict Subscribe Decimal Number Valve Co Subscribe Side Of Over Subscribe Basically All Subscribe 100 Model With That And Minus One In This Will Give Us And Will Us This Ladder 1004 NSS Plus This Content From News Channel Will Increase In The 100 Ko Hardcore Videos1 Subscribe 0 Subscribe To Of Account It Is Equal To One Hair And Will Take 17020 Active Voice And Subscribe Channel Subscribe Now To Receive Video0 Twitter-Twitter Tweet -Tweet Subscribe to Twitter-Twitter Tweet -Tweet Subscribe to Twitter-Twitter Tweet -Tweet Subscribe to E-mail - E-mail - E-mail - Hai Amount Plus Sudheesh Pass 22nd Number of Birth Number 35 Companies Have to WhatsApp Se Plate Se Interview Want You to Not Used Any Evidence Operators How Will Song So Let's Try to Understand That They Should Behave Number Net Se Example1 It Also Effective Work In This Will 100 Total 32bit That We Are Similar Bride For Cardamom 080 Fennel How Will Check Bedardi Last Details What Are The Last Week In Stadiums Halls Without You To Check What Is The Best Wishes 2008 Subscribed 158 Representations After bittu I will be the first one was with both are not equal to increase it is not divide subscribe hai main ahmedabad represents a replacement for only for best right now morning thing 04 210 is point soft 400 fit model bittu will give me one Effective Model Bittu Before I Will Give Me Yaar Very Hard Different From Having Distance Will Be Increment By One So Lets I Will Increment 5219 Youth Shiv Will Divide Very The Number Send Message Vikram 0 4 Vikram 25000 December 10 2012 Unified Inquiry Tenth 105 Model Login Bittu Very Will Give Zero Phone Software Will Be Notified In Binary How Many Distances Till Now Again Divide 800 Model Login From Here From You Log In This Website Different 100 Jewels Got Intimate Scenes Vikram Very Vikram 1030 E Will Stop So Let's Implement This will give them where not hazy mid day miles away for solving equations where used oil 1000 what will you do of account and preventive medicine effect motu is model with notification motu danveer Video then subscribe to The Amazing Indian Villages Return Online Without U a Fetish Accepted Sudhir Why Should Always Gives You Can Choose What Wrong Turn On The Interviewer Wants Sorry For The Time Complexity Sodium The Bell Icon to get early notifications
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
1,544
welcome political JavaScript a channel where we solve every single little question using JavaScript today we have 1544 make the string grade this is an easy question so given a string pass of lower and uppercase letters a good string is defined as one that does not have two adjacent characters as I and a sub plus 1 were the following conditions hold it should be a most related to characters that means I is greater than zero or equal to zero or is greater or equal to as I like negative minus two and s i is a lowercase letter and Si plus one is the same letter but in uppercase or vice versa meaning you have something like this would be valid because we have e as lowercase and E is uppercase and we want to not have to letters that would be the same if you change the case to them all right so to make string good you can just do adjacent characters to make the string bad and remove them you can keep doing this until this one becomes good and you gotta return the string after making it good the answer is guaranteed to be unique under the concerns that we're given and notice that an M2 string is a valid answer all right so the way to solve this is actually using a stack and we're going to do it we're gonna start with stack and two stack in JavaScript you can simply use an array kind of the constant stack there then we're going to use a forge before the string as um I'm going to call it C for character of s now we Monica when I keep track of the last element of the stack and to do that we do there's a couple ways to do it but just to prevent any errors from happening I want to do that is using the stack that at negative one that's simply going to give me the last value that we're looking at and we're going to check for the last is not no and C is not equal to last because remember e is valid e is not valid we gotta check this first and then we've got to check where the two things are the same in but in different cases and there's two ways to do that you could check the character code and see that the reference might be 32 an interviewer may ask you to do that otherwise there's a short time we can use in JavaScript and simple I'm going to do it here it's going to be C2 lower lowercase and that's equal to plus that lowercase all right and if that's the case we're gonna pop this tag I'm gonna do is tag.pop I mean this tag I'm gonna do is tag.pop I mean this tag I'm gonna do is tag.pop I mean I'm removing the top element it always we're gonna push the current character so we're going to attack that push see and finally we end up with a stack that has all the characters in order of the great string and we're going to return the stack join in the empty string so we can just return everything let's run this code as you can see stuck electron actually allows us to return a string because the stack in this case still an array now let's just represent what we did once again to make sure everything's clear we start from the stack and then we do a forged loop at the regular folder works just as well and we always push the current character and accept whenever the current character is both not the same as the last character and a different case format and if that's the case we're gonna pop the stack so we do not have both the previous character and the current character so we essentially eliminate for example in this case when we see e and e we end a return and the deleting both of them and we get with lead code at the end and finally we do use stack.join to and finally we do use stack.join to and finally we do use stack.join to return trained although you could use a for Loop instead even in the interviewer asked you to do so now the time complexity is o event because we have a single for Loop that goes to rest where n is like less and the space complexity is also all of n because we are using a stack and in the worst case we're going to be storing every single character of s and that's going to be it let's try submitting this and there you go the runtime is extremely fast faster than 91 percent of JavaScript online submissions thank you so much for watching don't forget to like And subscribe
Make The String Great
count-good-nodes-in-binary-tree
Given a string `s` of lower and upper case English letters. A good string is a string which doesn't have **two adjacent characters** `s[i]` and `s[i + 1]` where: * `0 <= i <= s.length - 2` * `s[i]` is a lower-case letter and `s[i + 1]` is the same letter but in upper-case or **vice-versa**. To make the string good, you can choose **two adjacent** characters that make the string bad and remove them. You can keep doing this until the string becomes good. Return _the string_ after making it good. The answer is guaranteed to be unique under the given constraints. **Notice** that an empty string is also good. **Example 1:** **Input:** s = "leEeetcode " **Output:** "leetcode " **Explanation:** In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode " to be reduced to "leetcode ". **Example 2:** **Input:** s = "abBAcC " **Output:** " " **Explanation:** We have many possible scenarios, and all lead to the same answer. For example: "abBAcC " --> "aAcC " --> "cC " --> " " "abBAcC " --> "abBA " --> "aA " --> " " **Example 3:** **Input:** s = "s " **Output:** "s " **Constraints:** * `1 <= s.length <= 100` * `s` contains only lower and upper case English letters.
Use DFS (Depth First Search) to traverse the tree, and constantly keep track of the current path maximum.
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
1,750
It is very much that Seervi Sagar will solve the question today. Medium length of thing after removing the similarity. Okay, first of all Govinda, let me explain the meaning. Ask the question. If you understand, it will be a lot of fun. It is true and never even by mistake, there will be ginger in the enter. They are thick. That's why you understand and you do n't even have to do the measurement. This is the front option. The first thing you have to do is enter the import here and it will become ice. Okay, so in that case, I have tracked back the speed test of the back and now tell them. What to say that you have to remove both the end similar friend of your spin like the answer is definitely guaranteed left and right side that is so displaying so much dance with its mental so if I remove this channel part then I get swing at That's the song, I have this train's growth, after removing my friends in the 19th, she benefits me with this gift and a bag of cement is different, so a little inside this, you will get more information about this quick memory of cricket. I give spring, Eid seeds page, Modi, 1000 years, paper can start, hello viewers, left opposition loop, inter college, the character which is equal to a tomato by taking it on a light point, then it means part of the district, through this, I will man the point, those people. Of reached here still you meet free end and this agreement sub character so see so much part office friends If symptoms are found, this is 31 and this is 3121. Harmony of current account will be done. Okay, so it came here, these two also came here and this single also, this chapter's account will be created on Twitter next time when you reach over clear me. How long have you been experiencing Samjhauta Express? See you tomorrow Yasmin. Keep maximum A part of this sentence on our heads and we will have jobs etc. If I have to print its length then how much is the lens so that it can be washed in this manner. If the position of left and right show the photo is kept on the nice then what we will do is you can say remove the boys if You have removed this team from one and these will become double, these two end specifications minute item was received by Abhinay from both the adventures, did we get tractors from us, is tablet mode on, so what is from Enfield, various acts, so what is on this The central characters then take the remote and juice friend to us that the tiles will save by straightening a little bit, she will be only of two lanes, then one and only this loot means now it does not matter which one will be bought, another check return burst we This survey means which team is the speed of which lens that I meant from that vehicle was e-challan in this case I meant from that vehicle was e-challan in this case I meant from that vehicle was e-challan in this case two is ok whose answer is example such sample is ABCD not on left side not on right time no conference item So no one will be removed and use of quotes for notice which was of my and national interest let's look at it a little interesting that we have I Josh that is I have added the character on the left side of the page I have added on the left hand side What is tax? Sim toe has been removed. If there is left side and hybrid SIM, then these are also removed but if I talk about it, then while removing both the center and state characters, I will have a character later if any such case happens. Neither should it have a big boot in it. Okay, now let's talk for once about how we will approach this question. Simple and after this minute, now this question arises. General Improvement National Roshan thinks that Jhal Agreement is on option in this. I speak more in this. It doesn't seem logical but your implementation skin will matter more, so let's talk for once, so that I can talk about these issues once, will they do it? Is it better than removing the table? No, you, I will account for the simple end characters, okay, or I will tell you 2.8 as a saver, how will you tell you 2.8 as a saver, how will you tell you 2.8 as a saver, how will you choose, stop removing, why for us we are full, if you remember, if I climb Korea and give my career, then this is the feeling inside the string. Removal bench is not added, Chawal Gandharva is present in these are dubitable and if you add any level in it, then it is not a simple test, for that first a separate office will be generated, okay, all of them. If it was then you will get Singh Panesar but still now we focus on solving the portion ok look carefully I will not do this zero index for standard were contestants 45678910 wealth shoulder inch character for Shyam Ek Lokayukta please subscribe Indian left kept I put more light here, I meditate on sixteen here, I get the certificate made, where is the left, where is the light, then initially hang Weapons &amp; Express Your then initially hang Weapons &amp; Express Your then initially hang Weapons &amp; Express Your Index Prescribed Norms &amp; Index Prescribed Norms &amp; Index Prescribed Norms &amp; Express Se Top 10 Intex Collector Shri Nandishwar Gets equal to liter So, what will happen to our boys, I have asked twice that the interest is equal, so the characters of similar group like them should be given an account, they should be given an account and on the left, turn off Aishwarya's page so that IG of that range can be added to us. Hello friends. If we do our next different character again, then after this set, clip news will go on this, produce paper on roadways or it is very accurate for dividend, saw the topic, what is the character of the one to which the left index is pointing? B hydration also points character. So I said, who are similar directors and yours and they will turn on, skip them, how will you prevent that, I am going to submit it on different tasks, it will reach on the laptop, right on the shift index, where will it go, basically for Independence Day, if I showed the saffron display character and saw the right play character. Again they call me similar. I said, on both your ends, whoever finds the character of this side, if I find their interest, then just collect them, group them and go over it, their relationship will go. After this system of specific artist, left will be possible, right overtake was again electronic playlist get from me then tractors of SDM Group means Samsung monitor gets interested, take left of him, I will be able to come to his house, I will keep the light near him, okay now By doing this and this, we said, we have tried till Ko, which cream tips for attack and back, Milan and Ko kept on tipping like Ko more on both the sides, then I said, as many as you have on your left and a right hand, right? If you skip them and send it to the next character, then see that Mehula is found from the center, make a group of them, they are worthy, cigarette characters are found together, go back to the next one and will add it. Installed that this is a similar type of characters to me, what is it actually? Should be should happen means should burst if I remove these by any process then delete me Akshar send me I have to remove something like told that this water sample top entry will require rough drops my and more time okay so laptop in it What is left is the leg up, back left right, Fateh Muslims had to block those character scratches which are part of the string and whose similar end does not meet and what I had to do was to make it a similar type of spring, then only after finding out the length, then left and right. If here is a very simple fact like this then how many characters belong from left to right, this team will come out with right - left plus word it - 7 will come out with right - left plus word it - 7 will come out with right - left plus word it - 7 a plus one and - 7 plus one that is too a plus one and - 7 plus one that is too a plus one and - 7 plus one that is too late for work number is that I want to withdraw 12345, how many numbers are selected among 501, then pipeline is more, obscene operation will have to be done in it, five correct answers will be produced, when five numbers are selected on time and these are the display of Intex service center, how much return is given from next point The sacred characters of the system are right at the time of that prince's juice, from decades to the left to the right, they also have their own indexes, the fuel filter also gives the character to the account public private minus plus, but now in this thing, let's remind like this, my father's 10th Question for Implementation Not for Profit We did not put much special effort in this, just accounted for the time of left and right end for our PC, in this way, means we will send the displayed left to you, where is it, give the right to sirope Set where is the electronic cigarette after all, now look, we have to do it till the time the loot is the right head and sir, the important resistance is that A, what is the printed jhal torch light electronic bulb in that point collect character is equal to be. Now we will do it, did I say that the shopkeeper who wrote means that this is the previous class that accepts tractors as friends and that the character on your left end and white end is SIM, what are we doing, I will take out that character. Now what they get tractor from MS Word character add is a letter whole winner will account from left side I was left front landslide and see this I hope to see the account if I get evening character on left side whenever I get the character What will Polytechnic do? Will we keep increasing the left? Since then, from the left side, whoever gets his voice mail and express like this character, he accounts to them. By increasing the left, he got the hair done, either I will do which actors who travels. If this is if you are not equal to the letter and correct if it is equal to s.no torch light - - second in this, torch light - - second in this, torch light - - second in this, we will discuss this news on average, in the last, the distance of exit from the villagers should be less. Maybe this is all your interest process and or the character on the left side is not equal to the point director, then I can say Gomez, how many characters are planted on a thing, then it is more fine, let's see once. And I will also tell you about the piece in this, it doesn't do much in this, it has already been done, so we will talk about this relationship that the chicken is electronic, so let's make the friends paper difficult, which exam page for study, I am in Saudi, which erotic fiction and forgive me. Cements Presidents and Exports and Specifications Z2 Now according to its own logic, NET has made the left side zero instead of ride poetic works and if you travel from here to here, how did it happen that my checked left side is still smaller than the side, which means it is all my Characters are not minuted Is the character with left hand equal to Writer-Director? Is the character with left hand equal to Writer-Director? Is the character with left hand equal to the character with right end? Gyan will remain for updates. Now Africa period. It happens that I came to know that my left end is equal to right end. ₹ Which character is being talked about in the future also, ₹ Which character is being talked about in the future also, ₹ Which character is being talked about in the future also, what kind of character is being talked about right now, after his test, in place of Mohan, now look, we are the chapter cream, this relationship is clear, till lunch till Chhota Right, we will work to this extent and at the same time we will keep setting this. Character left side effect contact delete when do you get it like me on the left of the track now winters what traveler character is big prince which one here will increase the light what bus stand tips I have this oil to plug printer increase response goes we So we will move forward to the left. If I find the student character on the beats, then for the movie, I will move forward to the left. Physically, because I have made the landscape, my hands have moved forward so that all three of them are speaking to the same traffic character. Okay, this is why they are coming out. About the next one, stitch them, which is my character, this is my front one, it is equal to the interpolator, we go to the response and go to the point - - point - - point - - A right, the index which is pointing is also a character, if I want to find it, then you can decrease the right. Now, if this character is confused, it is not equal, then I, this brother, got out of the group, look carefully, we told you inches and did this, in this film, Miller type characters should be made together, now while on the top side, at least 10 minutes. What will be similar and this has been removed or has come now let's come in the royal look next time Is the character on the left side equal to the character in the ad Is this character on the front equal to P Is the shopkeepers going to take advertisements on the character points Now the message character What am I talking about? Mall p.m. What am I talking about? Mall p.m. What am I talking about? Mall p.m. If the response is on the electronics on the boil director tiles, then what character reference is moving forward to the left? If the response is coming, then the nature of the victimized electronics is gone. Now see what character this is, the response is on the Titanic ship. You can increase the production by increasing the production. If the character is not on the tax during the time, then look at the previous ones, these are the assembler and the tax actors, Hina, I have done them like this and now we are standing here, there is a place to do the texturing to check this trick of ours, you had met us. Elements which travels, if you forgive them then they will be removed. The character on the left side of the next screen, is this zodiac sign the difficult big HT line character? c47 again 6, which collector are we talking about? Big details on electronics in pen form. Look, I have left, response goes from right, we are the character, loop intake is equal to the first character, so moving the lips forward, the character click is not equal to liter, one age is basically a choice, no, which protection is there to block the loot. If the torch light is working, connect if it is equal to the center by pointing to the right, then we have to inch what we are looking for, that right is equal to the first character, then decrease the light, what we are looking for and the hydraulic filter. If it is equal to then decrement it, then basically this is the scene, this means both of these had similar ends on both sides, then this send is fine, so see here, now again the character on the left side is related, dear writer and director BT. I will request in this manner whether my left and right are equal or not, whether I have removed the printer, which doctor are you talking about, one ghee, yes brother, my length is shorter than the right, one more thing is that this correction system. There is no appetite, this interest belongs to the left, if the response goes, then decrease the next one, I am frying yours in English properly, will it become tight, points on the index, the response goes, you will also dish to the right Index real fighting is try it on next character will top the light from triangle point people of that village used to decrease from internet that in short Ismail Khedi in front of insurance and mathematics all the corresponding left end and white end don't group we encountered What actually should have happened is that the symbol should have been removed and now we are pointing the left to right side, we are pointing the penis with the length of which means sacrificing the balance, we add water from this range. Let's turn the size of Tax rate minus one plus one comes out to t&amp;c one plus one comes out to t&amp;c one plus one comes out to t&amp;c How many colored lion colonies do I have near you? No, you did not have to suffer sugar hunger for two days. Okay, and if I talk about global complexity, then address time. Complexity of which will be off and skimming on Tuesday, the character had to eat only once and which is the girl 's end specific city gas 's end specific city gas 's end specific city gas that if there is one case in this which I want to tell the target committee and it is this one third fourth this In this regard, the main door has been opened, in this all seasons, inspirational, this point is definitely written, so much lesson is given, where it is used to understand, the satellite does the same, the intestine determines whether you will get full marks in your report or not. Amma beat me a little, now let me explain, if we don't do it then set a reminder, this is my last point, this will be my light point, who was this one, I am the notification of the code, the shopkeeper will go, the opposition is equal to left and right. After taking out our character, whose character are we talking about, the desired character is on the left, the response comes, we will move forward to it, is this character on the left side or the response goes, now if we move the net forward then it is okay, better sleep light than this. See this character is vibes, the response goes, we increase it in this, remember this, we have gone to the city and take out a little indexing phlegm to understand that Abdul will be ready again, opposition, the character on the left side is equal to the character on the ad and who else? We are talking about the character. Okay, this is the character. Because of this look at the character which is the left index for taking equal to the inter. So increase the electronics volume. This is the character which is equal to liter by taking equal points to the diet nerves requested. If so, the side effect is scientific, people come in, there is no problem till now, Ajay Devgan cover will become more clear, who is Redmi on the left, who is Redmi on the right side, who is CC, after this it will remain for one minute and this servi will remain for that part of this time. I face any problem in playing cricket. This mark is one and a half left, it is still small. The rifle response goes. You set your character. Is that left end equal to the character of research electronics that we are looking for? The response goes to the left. If we take it further, people have now lagged behind in the race by having so much leftover, instead of fourth, it is equivalent to left-right, so now instead of fourth, it is equivalent to left-right, so now instead of fourth, it is equivalent to left-right, so now I will not be able to enter again in this group, I will make the entire World Cup champion. That A is equal to Check Left Right. To do the last few things, now the problem arises. Now let me tell you what we have assumed. Our answer has not been earned. There is a big one on the right and the minus plus one should have been closed well and This sequence is pure sequence in looting, this noose has straight thread on its side, smooth white part and if this thing is intelligence then right, my poetry becomes more left short on it, then in that case, Varanasi is there and if it is good then it should have come. How to control this, we will handle this case if I glue the right part and divide it equally because this will be the table that will be done in it when the verification is done that now in this case the strike will go back and our difference will come because the dough wanted so that Sool Sam Tyag instead of speed, the explanation is easy, the whole flower is additional, there is no logic, there is no personal explanation, okay, a little, who will do it for you, how to remove an assistant director, okay, aunt doctor has made Bigg Boss videos modern and can do it, okay so this If you have understood the question then please do platform chicken, you will get it on that side of the portal, run it once and see, only then you will get Justice Chowki, if you did not do it on time, then add question number and let's see, then Khurram said. Correct, Akbar is a bad cigarette, try it on the portal from the serial, then we will be attracted towards you and will meet in the next video. If you like the full container, then please like, share and subscribe. Well, the more people know, the more our number will increase. Okay, it will benefit all of you more. 21 Please find my sources. In this you will be able to ask questions about food, how are you facing any problem, what complaint, audio, next video were cigarette and king up.
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
363
The Whole World is Incomplete Channel Tweet Sunny And You Will Be Talking About Very Interesting Problem Maximum Sum of Practical Knowledge Bank Ki OK Flexible Like Share and Subscribe Button Subscribe Thank You Can Easily See Problem Mind Manch subscribe and subscribe this Video Equal Samiti Ki Report Subscribe Thank You Can See In The Interview You Can Easily Like To Explain The Apps Explain The Procedure Explain The Time Complexity Explain The Best Solution Of This Problem Fix Without Wasting Time On Which Let's Move VAT Registration 721 Matric-Matric 0589 Maximum Time Matric-Matric 0589 Maximum Time Matric-Matric 0589 Maximum Time Rectangle In The Matrix True Davidson Midlife Happiness Prosperity Unit Certificate Unit The Video then subscribe to the Page if you liked The Video then subscribe to the Page Triangle Forex Involved in the Use of Earned Money Explain These Inputs and Outputs Also With Help Capability Central Provident Visualization and Nominates Look Vardhak Have This Point To Help Site You Can CDMA Samay Tricks Length And Width Matrix Of Violence Can See A Men Is Like 102 Subscribe Scan Hai Vo Like Subscribe Now To Time Limit Exceeded Nuvve Festival Subscribe To This Platform Up To Understand This Problem with the help of example OK so you can see it in the distance subscribe and subscribe the notification subscribe like share subscribe problem statement subscribe and subscribe the key effect if then which prosperous triangle white this condition and now considered this triangle certificates will Be Discarded Ok Gyan Unse Subscribe Like Subscribe And Different Types Of What Is The Meaning Of This Is Like This What Is This Channel Subscribe Must Subscribe Channel It's Present And Systematic Chhat Sami Don't Go Into A Straight Leaf's Fans Year Greeting Diwali And Stuart Broad this time a leg apply sea values ​​lines a leg apply sea values ​​lines a leg apply sea values ​​lines rectangle also much more close to discover with me to front search volume how to front secretary Rajesh OK so before finding sarchu a plate just first understand its daily system rectangle viscera beach immersed in sea Close To's Value To Do You Can See This Is The Value System 90 subscribe And subscribe The Amazing Like Very Love You Queen Of Searching For That Is The Value Key It Is Like Very Close To Developed Between Scroll Soth Disawar And Subscribe Our Channel Like This Is The Mind Green The Return Of Rebel To Do Subscribe To The Quantity Of Water Into Another Problem Like Kar Number Of Maths Recent Topics Add Sachiv Pradeep Sen Like You Can See One Of The Video Is About Your Effective Work Capabilities Talking Deposit And This Key The In This Problem When To Find The Number Of Medicine Dasharu Video Actually Vinit You Find This Woman President Of Messages Actually West Bengal Ok Sweet Secretary Rectangle Ok 100 Harold Problem Rectangle Subscribe Want To Talk You Can Be Thank You Will Feel Much Easier to solve this problem subscribe my video and you can just look at life super modern stop this problem you can see what time does not want to build and subscribe start the first how to just make some rectangle ok do subscribe The Channel subscribe this Video Please subscribe and subscribe can see and we can reduce and tree to two as well as the maximum number of columns and like this page question equal to so great daily 121 edits exactly equal to 8 rights issue focused upon this condition you can easily see that I'm Just Build Up Some Special Type Solution Okay So Ifine Type Solution For Feet Rich Triangle Angry Birds On The Number Of A Question Is The Volume Maximum Know How To Draw A That Your So Ifine Cry To Take These Elements And Can Very From One To This Capital And Liquid 1 This S8 Video Gems Festival * Very From Greater Than Equal To Festival * Very From Greater Than Equal To Festival * Very From Greater Than Equal To One Rank One To M And Is Also Going To Worry About This Rich And Remove From Blacklist And K Soft Particular Step Vibration We Can Easily Say Diet K So Let Me Down Lifted Yashwant Sonth A Particular Hydration Vacancy Value Enriched In This Cream And Artists Avengers Patient Data Am Just Fixing Me Left And Right Like No One Can See The Thing That Is Going To Deposit About The Best Lines Ok Temple To Build Up Understanding Rectangle You Can Also Have A Rectangle Like This You Can That Are Trying To Make This Most Puck Novel Price Two Lines And So They Can Easily Find Out The Suitable Rectangle Wedding Between Two Lines How To That Okay Services Directly Share Matrix Data Video This Is Actually The Prefix Sum Of The Samprati Samudra Russian Video Must Subscribe What Is The Meaning Of This Is This What Is Subscribe Like And Subscribe How I Can Easily Find Out The Possible Values ​​Like And Lines But This Train Channel Values ​​Like And Lines But This Train Channel Values ​​Like And Lines But This Train Channel Whole Inch And Dentist - 9 - Stree - Whole Inch And Dentist - 9 - Stree - Whole Inch And Dentist - 9 - Stree - Support for this one and minus point panch dushman and one five - quickly ok he will find panch dushman and one five - quickly ok he will find panch dushman and one five - quickly ok he will find the volume source file point of this will give you can easily see the balance like plus one so let's salute to find the value of this Land Of Electronics Subscribe - - - Friends Welcome To Do It I Subscribe - - - Friends Welcome To Do It I Subscribe - - - Friends Welcome To Do It I Think And This - 7 - 953 Think And This - 7 - 953 Think And This - 7 - 953 Spider-Man And Details About To Work On Vo Spider-Man And Details About To Work On Vo Spider-Man And Details About To Work On Vo Palat Mitra Tangen Etawah To Is Point This One Minus 5.2 Villages Of Love Between To My Channel Thanks U that in this case tong listen you can easily see the value is Samudra Values ​​- Mr. value is Samudra Values ​​- Mr. value is Samudra Values ​​- Mr. Mallik Okay so this is you consider rectangle about this What is this - is this What is this - is this What is this - Okay Google What is the value of the validity Subscribe 21 Subscribe Ali Hey that side And Where Is The Number Of Truth And They Are Not Going To Worry About This Time For Every Particular And There In This World Subscribe To The Channel So Hey - Reel 512 You Need To Find Some So Hey - Reel 512 You Need To Find Some So Hey - Reel 512 You Need To Find Some Rectangle Okay So Let's Acid To Prevent This Rectangle Liquid Denoting This point to that is rectangle stop this security system that your shahabir want to find out the name of particular rectangle where we want some also close stupid idiot's illegal Tubelight consider and Chinese are like this thank you will find the problem Modified 3 years ago And Water In Delhi Are Living In Maximum Effort Have A Statement Back Itni See Left Right To Find The Traffic Jam Of This One The Pichmix Coming About - Free Not Attempt Pichmix Coming About - Free Not Attempt Pichmix Coming About - Free Not Attempt To Key Notification Office Near Ok So - Reel 2nd Can See What Is The Function So - Reel 2nd Can See What Is The Function So - Reel 2nd Can See What Is The Function Naav Ko Ok I Will Give Me To Find The Amazing Starting From Come Babuji Sach Debit The Tips Subscribe Now Till Subscribe That End Exit Ci Ok Me To Point Particular Illicit Relationship Element subscribe to The Amazing Widow End Subscribe Not Understanding What Will Explain The Wedding Gift Boxes In The Same Thing You Need To Find Out The Subscribe And Subscribe The Welcome To PNB Current Elementary Mid Hai - Key And Absolute Bonding Vision My Hai - Key And Absolute Bonding Vision My Hai - Key And Absolute Bonding Vision My Set Se Topic Time Led Salim Debit The Value Monk Stupid Too Chinese - Loot Value Monk Stupid Too Chinese - Loot Value Monk Stupid Too Chinese - Loot Operator The Valley Between Under 0.5 Inch From Point Operator The Valley Between Under 0.5 Inch From Point Operator The Valley Between Under 0.5 Inch From Point System Elements Who Will Find The Difference Between China And Attainment Of Cases Right From Unwanted Ambulance 108 Another Thing Andhe Maximum Subscribe To That She Said Dash Love Not Understanding Flight Mode Turn Hotspot On This Occasion In English No Record To Give A Little subscribe And subscribe The Amazing How to find the total - Welcome to do the person the total - Welcome to do the person the total - Welcome to do the person subscribe like subscribe and subscribe - 1 hai subscribe - 1 hai subscribe - 1 hai but this pallu and border this wonderful - but this pallu and border this wonderful - but this pallu and border this wonderful - 24 - 1898 put amount of - one in this 24 - 1898 put amount of - one in this 24 - 1898 put amount of - one in this state of - Stree * U Can see this state of - Stree * U Can see this state of - Stree * U Can see this point in fifth element to ok so it means status clothes starting from this to ending up this code will have something which to take care of you can see some differences coming about what is the amazing and 122 others in this coming to Countries have the element subscribe and subscribe this Video subscribe On flight mode I show you the latest want to the newly accepted salary submissions Okay so this problem actually demand in typing disturb me to find the thing but it's okay so maximum sum of rectangles in more columns OK and subscribe the Channel subscribe and subscribe Person Start from the Best All the Best Channel Please subscribe and subscribe the Channel subscribe The Channel Quentin Girl On Wed 29 May Preferred Shikshamitron Advocate AIIMS Unskilled Default Value Research Times Bhi Suppose They Have To Find Out Conference It's ok so late may also changed r parents first think benefits of elements and subscribe about like sheron to and 4th and subscribe tips - key ok subscribe and like this subscribe tips - key ok subscribe and like this that I think they should have not about jaswant so speak investigation report submitted derrick system lower Back side to for - key system lower Back side to for - key system lower Back side to for - key skimming about ends significant role in adherent mr rectangle subscribe this channel definitely subscribe and subscribe the channel it is starting from the like this point subscribe our channel ko subscribe and subscribe hai naveen can see but you need to find out the Term Deposit Their IF Pandav Till Current Sametime Minute Till Lipsum Poster For The Current Saminder Inch Width Shift No Need To Find The Value Of Log in members side complexity subscribe and dont during winter comment section 2 videos last love you all like this video share and subscribe our YouTube channel latest updates thank you for watching this video Jhaal
Max Sum of Rectangle No Larger Than K
max-sum-of-rectangle-no-larger-than-k
Given an `m x n` matrix `matrix` and an integer `k`, return _the max sum of a rectangle in the matrix such that its sum is no larger than_ `k`. It is **guaranteed** that there will be a rectangle with a sum no larger than `k`. **Example 1:** **Input:** matrix = \[\[1,0,1\],\[0,-2,3\]\], k = 2 **Output:** 2 **Explanation:** Because the sum of the blue rectangle \[\[0, 1\], \[-2, 3\]\] is 2, and 2 is the max number no larger than k (k = 2). **Example 2:** **Input:** matrix = \[\[2,2,-1\]\], k = 3 **Output:** 3 **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 100` * `-100 <= matrix[i][j] <= 100` * `-105 <= k <= 105` **Follow up:** What if the number of rows is much larger than the number of columns?
null
Array,Binary Search,Dynamic Programming,Matrix,Ordered Set
Hard
null
1,335
hey everyone welcome back and let's write some more neat code today so today let's solve the problem minimum difficulty of a job schedule kind of a confusing problem so I'm really going to focus on the example that we have here so the idea is that we have a bunch of jobs and we're given the difficulty of each job in this input array we're also given a number of days so what that means is we want to split up this list into two parts for this example cuz D is two so we want to do some of these jobs on day one and the rest of the jobs on day two of course if D was equal to three then we do it like split them up into three different ways and we can choose how we want to split them up but on every single day each one of these has to be non-empty so we have to do at has to be non-empty so we have to do at has to be non-empty so we have to do at least one job on every single day we can't just say Okay do this on day one day two and on day three do nothing and we have to make sure that we include all of the jobs in total we can't miss any of these jobs in addition we have to do the jobs sequentially so it's not like I can say okay this job and this job are going to be on day one these jobs are going to be on day two and these jobs are going to be on day three we can't do that we have to do them continuously the problem description tells you the same thing just in more confusing wording now once we have done that let's say we split it up like this and this we want to calculate the total difficulty of doing that and it's not by just taking the summation of all the difficulties what we actually do is we take the maximum difficulty on day one basically the max of this subarray it's six and we take the max of this subay on day two it's three so we take those up and add them together that's the total difficulty of splitting it up this way now obviously that's not the result so what do we want to do for the result well we want to find a way to split these up such that the result is minimized so the solution to that would be to do five of these tasks on day one because then the maximum is still six from there and then on day two do one and then we add those together and then we get seven which is the correct output okay so the first idea that you might have and the first idea I had was let's just try every possibility right let's try to break it up every possible way how can we even do that is that even feasible and if it is can we then add a little bit of caching to that solution let's try to find out so we don't have that traditional choice of whether we want to include this or Not Included the choice that we do have though is on six do we want to consider this the end of day one or do we want to have six and it's not the end of day one and then we have another choice we get to five do we want to consider this the end of day one or do we want to have five and not consider it the end of day one and here we'd continue as well if this is the end of day one then we'll get to five and say maybe this is the end of day two now of course this shows us what one of our base cases is going to be what happens if we stop too early we have additional days left but one of the parameters that we're keeping track of as we iterate over this array is of course going to be index I that tells us which job that we're currently at but a second one of course is going to be D the number of days that we have remaining here initially it's two by the time we end this day it's going to be one and then by the time we end this day afterwards it's going to be zero if we end ended all the days we expect I to be equal to the end of the array but it's not so here we return this is not a valid way of doing this so when we return we're going to return Infinity so basically to indicate that this was not a valid way this does not count as a solution so that's showing us one of the base cases basically the invalid one just to kind of continue with this here we might get to five and not consider it the end of the day now let me just kind of fast forward and Skip to when we get to four we get to three then we get to two and we want to consider two to be the end of the day and then we get to one and we want one to also be considered the end of the day so we have a day that looks like this and we have a day that looks like this we know this is the correct solution I'm just not drawing out the rest of the tree but from here how do we return a result of seven we know that from this group the maximum was six we know that from this group the maximum was one but how do we end up returning that well I think one possible way is to have a third parameter we have I we have the number of days remaining and I propose we have another one called the current maximum it's not the maximum from the entire array it's the maximum for the current day that we're at so initially when we get here okay we see a six we're going to set that to the current Max now we see a five current Max is still six four current Max is still six three and two current Max is still six but when we say this is the end of the day then when we call this recursively we're going to say okay the result now is going to be six plus this sub problem there might be more values remaining but the result is going to be six plus whatever the current Max from the second day happens to be which we know ends up being one so then we get the result of 6 + 1 once we then we get the result of 6 + 1 once we then we get the result of 6 + 1 once we get to the sub problem of course at that point we are going to reset the current maximum we're going to reset it from being six which originally was but now we're going to probably reset it back to some small value probably something like0 or ne-1 because I think all the like0 or ne-1 because I think all the like0 or ne-1 because I think all the job difficulties are going to be greater than or equal to zero and then immediately when we get here we're going to end up setting the current Max from negative 1 to being postive 1 and since that's the base case this is the case where we ended up reaching days are equal to zero and I is uh out of bounds I has gone through every value in the input that is the valid base case where we would return zero and then from this call we would return one and then from this call we would return six so we add those together and we would get the result of seven so that's how we can solve this problem at least this is the Brute Force way but when you notice that we have three parameters we know this is when we can add caching to the problem we can use the parameters to prevent repeated work so how many combinations of input parameters can there be for this well I can have a possible value of the length of this input array so far the time complexity is beo of n second D can have a possible value for whatever D happens to be so n * D is the time complexity so to be so n * D is the time complexity so to be so n * D is the time complexity so far what about current maximum what are the possible values it can have well at any given point in time current Max could be any of the previous values like if we had started the day here current Max could be four if we started the day here current Max could be three etc so this in the worst case could also be n so the overall time complexity if we add caching is going to be n^2 * D and add caching is going to be n^2 * D and add caching is going to be n^2 * D and the memory complexity is going to be the same and this actually is enough to pass on leak code so let's code this up now one thing I actually didn't mention is that it's possible for the number of days to actually be greater than the length of this array that would make it invalid we can't split this array into this many ways if there's not enough jobs so they tell us in that case to return negative 1 so we can handle that pretty easily just by hardcoding a if statement here so if the length of job difficulty is less than D then just return-1 as the default but continuing return-1 as the default but continuing return-1 as the default but continuing let's do our recursive backtracking or DFS whatever you want to call it and then we'll add caching to that afterwards so we know we keep track of the current index we keep track of the number of days left and we keep track of what the current maximum in the current day happens to be so the way we're going to call this is by returning DFS starting at index zero uh starting with this many days and current Max I think you can probably set it to zero but I'll set it to Nega 1 just to indicate that so far it's invalid now starting with the base cases we know that there's one base case where I reaches the end of the array the end of the job difficulty array now in that case we want to return zero if and only if D is also equal to zero but if it's not then we can return a really big value to indicate that this is invalid which is going to be Infinity in our case the reason we're returning zero rather than one is because think about it in terms of this sub problem we have nothing left in the array and we have no days remaining so from that sub problem of course it's not going to take us any work or difficulty or whatever so we return zero from there but from the other recursive calls you're going to see we do return nonzero values now the other base case though is what if we haven't reached the end of the array but it's still true that D is somehow equal to zero that is again where we return Infinity because it's not possible for us to do that we don't want any jobs remaining so we return Infinity here as well now let's go into the recursive case but before we actually do that we know we're keeping track of what the current maximum happens to be we might need to update it that's exactly what we're going to do we're going to set it to Max of itself and the current job so job difficulty at index I this will make it so that no matter what on the first iteration of the DFS current Max will be Nega 1 and we'll set it to whatever the first job happens to be so it won't stay ne1 for very long next let's do the recursive case there are two cases one where we continue with the day the second is where we end the current day how are we going to call this recursively for each case well one is going to be easier so let's start with it continuing the day we're just going to go to I + 1 the we're just going to go to I + 1 the we're just going to go to I + 1 the number of days is going to stay the same we haven't ended any day yet and the current Max is just going to be whatever it happens to be right now the other case where we end the current day is a bit more interesting we do go to I + 1 bit more interesting we do go to I + 1 bit more interesting we do go to I + 1 but if we're ending the day we should probably decrement the number of days and lastly what is the current maximum going to be we just took the current maximum this is the current maximum of the current day but if we're ending that day current maximum should be reset and we're going to reset it back to -1 or we're going to reset it back to -1 or we're going to reset it back to -1 or you could probably also do zero I think so this is the two cases and we know among these two we're trying to minimize the difficulty like it says up above so we should take the minimum of these two function calls so I'm going to do exactly that and don't forget to put a comma right there I'm going to assign this to a result variable which is what we're going to end up returning so while this solution is correct it's not as efficient as it can be so to add caching to this solution we're going to first create a hashmap cache it's usually easier than doing like a 2d or 3D array before we return this result we're going to throw it in the cache like this using the parameters as a key i d and current Max is equal to result and if we ever see this result has already been computed like this if it's in the cache as a key then we can return it just going to copy and paste it here if you're not familiar with this type of caching I would definitely recommend looking at some easier videos of mine probably leak code 70 is a good way to learn about caching or you can also check out like the courses that I've made on NE code iio but let's go ahead and run this to make sure that it works and of course it looks like we had a mistake which is a typo and there's actually one last thing I forgot about I said that we aren't always going to return zero and this is the part where we don't want to if we end the current day we have the maximum of that current day so to the result of like this sub problem we want to add that current maximum so just like this we're GNA add current Max we know that's the maximum of the current dat and then we're going to solve the rest of the sub problem for the remaining number of days now I'm going to run this and hopefully it will work as you can see on the left yes it does the runtime isn't as efficient as it can be because actually there is a way we can use dynamic programming I think in addition to a monotonic stack to get the time complexity from being n^ to get the time complexity from being n^ to get the time complexity from being n^ 2 * D down to just big go of n * D but I 2 * D down to just big go of n * D but I 2 * D down to just big go of n * D but I think I will leave that as an exercise for the reader if you found this helpful please like And subscribe if you're preparing for coding interviews check out NE code. thanks for watching and I'll see you soon
Minimum Difficulty of a Job Schedule
maximum-candies-allocated-to-k-children
You want to schedule a list of jobs in `d` days. Jobs are dependent (i.e To work on the `ith` job, you have to finish all the jobs `j` where `0 <= j < i`). You have to finish **at least** one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the `d` days. The difficulty of a day is the maximum difficulty of a job done on that day. You are given an integer array `jobDifficulty` and an integer `d`. The difficulty of the `ith` job is `jobDifficulty[i]`. Return _the minimum difficulty of a job schedule_. If you cannot find a schedule for the jobs return `-1`. **Example 1:** **Input:** jobDifficulty = \[6,5,4,3,2,1\], d = 2 **Output:** 7 **Explanation:** First day you can finish the first 5 jobs, total difficulty = 6. Second day you can finish the last job, total difficulty = 1. The difficulty of the schedule = 6 + 1 = 7 **Example 2:** **Input:** jobDifficulty = \[9,9,9\], d = 4 **Output:** -1 **Explanation:** If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs. **Example 3:** **Input:** jobDifficulty = \[1,1,1\], d = 3 **Output:** 3 **Explanation:** The schedule is one job per day. total difficulty will be 3. **Constraints:** * `1 <= jobDifficulty.length <= 300` * `0 <= jobDifficulty[i] <= 1000` * `1 <= d <= 10`
For a fixed number of candies c, how can you check if each child can get c candies? Use binary search to find the maximum c as the answer.
Array,Binary Search
Medium
907,1886,2000,2027,2188,2294
91
Tiger, in this video, I am asking you a question, very interesting, special type of shooting, completely successful, subscribe the channel. Okay, so you can do it one, two, three. Now on behalf of the school, tell me in how many ways the film can be folded. Okay. So if we have to do it in a small time then what happens, the sun causes harm, ghee presents option, there are many attempts, so see, like I got the input late, why did I try 1051 times, okay, see what I did, tell me all about it, how many numbers. There is a recording of today we have been asked to submit but I will print the same and show it to us in chords where the children will get interest. Let us do this work and make arrangements on the other side. Rahul has become 11 that he is feeling frustrated in this bhandara job. It seems that if I write here 4000 patients will even be folded in this manner, then even it will be added like behind the recording of Puttu, a room will be added to you quickly or with the husband. If you can also come, then friends, you want to listen to 15, now the team has become descended from the sky, three cost of 323, diplomatic cost of these two should be left out, or the recording of the balance is black, nothing happens for that, go to 2344, okay, now the couple had broken up behind this or And bank and special 2310 will have to be done, whatever that W and then the qualities of it increase to seam to be good enough but black, now we have got our certificate vitamin A B C and if Delhi Haryana receives the route, then you will become someone else. According to the supply, people went one and in. Whatever you are, health is fine for 2030, then cafe, it was two-three well s, this then cafe, it was two-three well s, this then cafe, it was two-three well s, this year it is an old sadhu, now let's see, if it gets connected in the same form behind the slaughter 123 according, then you both And we will not get another person BC 231 that you want 31k recording, now we need 231k according to it, he said that brother, 21k from 2310 coding, the other two recordings are weak DC and everyone will put that record behind him, we will become Muktibodh, this is true. Who said 223's BC Komal W. Give me one behind him, I will give you the health of the second try traveler's brother, give me your encoding, it is Dubai, I will give him 2031 quality. Well, because she is calling, she has spoiled that she would not have been a big girl for her children, otherwise she would not have stood up, so now do not believe that a little change is needed from the Commission from time to time. If you talk about 2000, what happened on this subject, you got a gun on it. Thank you, oh, it was fired. This time I have selected 2310, second is 100 or 125 test, we have a little love for 2 minutes, smoke. Click the like button and your Which character to put, then I request it like this, if I get the answer of bhaiya thirty one, then I will apply the liquid of his eyes, or if I get the answer like this, then put me the train game, then 231 method, what is this, DGCA and w10, nothing. It is wrong, it is okay, there are two of 2030, tell me the names of which DC and W and tank do you have, if you have this, then we will be able to place a zero call on this, together with the train people, we will be able to place that this 2310 is ours. Okay, let's do 1000 tests and send 12. Get together from here. If something with this name is connected between the trees, if you get two, you get B.R.A.K., let's boil B.R.A.K., let's boil B.R.A.K., let's boil this 1310 well. We are calling you. So, I am the first to use Bluetooth. Band Hero Song Ruk MB 9231 000 to 123 101 Let's see in this way that if you get the answer of 2310, then close them behind that this list is of temples, if you get the answer, then only their descendants have put it, then the Gurjars will have BCD. J Ajay person now second plate 2000 nothing happens try you and hope to increase I have now expressed this 1000000 now he said bag 11 we can forget we can take more pitts and try medium so we are 126 So we have no crack so there can be more 2310 can't become and the recipe on 2300 is very 101 and cut ours and citric is 26 so we should see what they need so that is not needed okay so 11 Is the photo speedy, this 2310 type, put it in the form of any person that you will get B C D J K L W and so on, if you get it then friends, Tantrik was done, basically A is good to you, okay, now I will give you something special. How will you be if you take a Zone Coordinator, how will be the questions, how will you be in this manner, then your I- this manner, then your I- this manner, then your I- Tourist has called in front, then she came to you, I keep listening, okay Guava, come to you, if the character is okay, then we have come and a lot of above the rectangle. Khush depends on how it goes. It depends on whether it comes - Mannat, it comes. Proper Sai Ne it comes - Mannat, it comes. Proper Sai Ne it comes - Mannat, it comes. Proper Sai Ne Surat answers. Okay, then you can understand. This can be 10, this can be 0, this can be sure and that. Like we can put a picture of both of them and neither can we put it when this is this because this is this so if the number is 26 small now it's okay in school so I try all these that when we solve someone else's There are that and that, the middle matter matters, dimension and rectangle matter, Guru is abstinent, it depends on whether we kiss or not and see again if we fold it in many ways like this, then do four-five more. fold it in many ways like this, then do four-five more. fold it in many ways like this, then do four-five more. Interest had been formed, I will write with the record, I will take a little chart, I will find Undhiyu that I will take exactly one, I will join it, so I just we input, we did our previous and on this occasion the students participated in it that DP Yadav Pawan put Given, it means that it is in the first character only, okay, that's what I am saying because first, if we say this first cricketer of Kashmir, this 10 of B heroine will not come then now first you need before 12345, now let's start oh my God 251 Ireland one oh my God 251 Ireland one oh my God 251 Ireland one point 148 mein aa is singh dot ja raha hai I want to search can send the best WhatsApp app from zero to zero we need I plus hua anna dhan chahiye job 232 to 234 this also subscribe May be we put in it come then this is a ring last to singh and subscribe is not last means if you want it came in the last to increase in servicing these children used to fry till then only then they said that You should do this as much as you can, why should you do this last to equal is the next question that comes in the poorness of the team that the last is that only the first zero cannot be done. Hmm, so I will not be able to write anything for Jeevan Mandir, so we use So you are me and that I am also your zero through both the apps. Mails paper from e-mail 12th Ajay ko Jai ho voice mail set that SSC exams page is good ok Ajay ko show more Ajay ko MP3 000 and here before both of them 0 The last that you are doing is the latest of two types of last 2108, I will be of that application, there is no problem in this, there is only one way to reach you and that is also here, now either plant a B, become this or use it in one form. Do that you will get one more in the form of 'West' should be made. Okay, now get one more in the form of 'West' should be made. Okay, now get one more in the form of 'West' should be made. Okay, now we want two one, so for one, I have put 600, 800 students as 1101. Yes, then you will get the method as banner1 11:00. put 600, 800 students as 1101. Yes, then you will get the method as banner1 11:00. put 600, 800 students as 1101. Yes, then you will get the method as banner1 11:00. If you use this Will you go here after making it? What is the relationship like whether you are in a family or a wish in the meantime, please do something good for you, now let us talk about the beginning, let's talk about this, hey, after becoming zero, it starts to feel like there is no recording of the salt of zero. It used to be 210, I can't do it because it is the letter BJ here, but now we have understood that now it is 20 and both and this so that I can understand it well, 200 is obscene that I have used zero no to explain. I am giving zero line Malashri. 0 Okay friend, if you are doing Ghoshal and it has been 20 years then please click on the like button, you can apply it here, we will apply this type of appointment to you soon. So like this, you will have to turn it on again from here. Apart from friends, now actually do 212 from here. So, if I tried to explain this in NS2 2002, then the subscription is 9000 between the two. So see here, it can definitely be done. This can be done here. That's what I will tell you, I am and BJP is famous by picking up the 19th, donkey, yes, it can be the biggest, it would have been 2030, both of them together, subscribe, if you subscribe, the last two of the last two minus one are more, that is disgusting and that should be if Soon the one with the alarms is suitable then he is loose 2036 so here I do daughter And this is a good thought, I will ask this once again, I want the health of the children to be bad, but if the train is in the last place, it is the devil, it is the 20th, then look first, at least I can put Zero and Singrauli in the last place. Cover it, I will put the printer flex, I can apply it to Singrauli, which they have to do in their to-do now, can apply it to Singrauli, which they have to do in their to-do now, can apply it to Singrauli, which they have to do in their to-do now it depends on what happened in 2015, now the children are given the last two, at what time do I take these two temples. Here if you search for broken in the last then put it in the last so let's see now we have this if you want to do it for ₹ 1 then 212 industry then want to do it for ₹ 1 then 212 industry then want to do it for ₹ 1 then 212 industry then adjust there was mutual behavior behind your children 23 stop it or set an alarm behind all this 3 normal You will get this dot subscribe - normal You will get this dot subscribe - normal You will get this dot subscribe - 151 ok we will remove this letter 226 ok then it will take two, once in a year it will start happening once in a year, a picture video, you listen, if this thing 26 is missing, now we will also add IDBI 512 to it. That I should write this love and eat it, you can write this message, if there was a small pimple, if there was 1 tsp chaat masala, 1 - 1the and the biggest one, it is 173, I am so much that on the side Madhuri became the biggest change, peacock and less. It is used only for burden, it is milk lettuce, on Islamic line no. 20 and on one side from line no. 26. If anyone has any problem then you want it here, it went in 2019, leave all this, if you stop 2000 then you have no problem here. So you have made this when you are making it and you will have to improve it whenever you were making I want to use, set it there itna a disgrace to think what to do and e 512 if otherwise you have heard by just adding in Because in this form, whose name is in whose name regarding this film made of metal, then this small one which he meant that from here it is single and we are therefore one tablespoon if you want to do this work then add this dishonor ghee like If you want to thank you, then subscribe, otherwise if you want to chant his name, then this is our thing, this is our memory of taking sweets here I remember that loot to koi, it means good, it has not been printed at all. The system no doubt in the form of Linga - The system no doubt in the form of Linga - The system no doubt in the form of Linga - 110 like this and 98100 that 18 submit then I had made my copy friendly Ajay has to keep key print a good and noble DPO satire - they a good and noble DPO satire - they a good and noble DPO satire - they new confuse good It seems that it will not be spent, so you are worried that how good they all were, they should be left in your last one, how they were, once again Aishwarya says like this, he says, no matter what happens in the future, in the last, both the zeros come to zero. Whatever it may be, 040 has come. These four fortunes have come. I would like to call again. Whatever it may be, now 90 have come. Whatever it may be, if we go to Meat and Mandira, if we come to zero, then neither can we put one back nor can we help the Gujjars. If you run behind, then from here we will put this Jio phone call - 100 0505, if Jio phone call - 100 0505, if Jio phone call - 100 0505, if you have it, as you can see, after this, like you can put a big gift of vegetation on 90, then okay, so this is 0. In college, if it is 90 and then you do more, then you turn on both of them like it is done and turn it off, it is Vipin, that small rooted bar is fine, but if you are taking it off, 2002 one, now keep a big thing. You could rate the interesting subject as a chapter, it is okay and whenever we use MS Word, what we do is check that you are clear about which players are all the many small and many small things of scientist MS Swaminathan on Physical Jawan Jyoti. There is a lot of education in this way, so it is difficult to increase its juice a little, but I hope that I have shown you how to break it in front of you and then this one towards this case, I would like you to pay special attention that when High-use, even then when High-use, even then when High-use, even then why should I try, so the meter is running against them, it will reach zero, so these first two cases will be cut with flames. If you want to say something to the children, where is the college, your makers will be full and we are going to update it in that chapter from your website also. How many questions should you want from our Instagram useful loot, if you want in the video because this is a comment. please comment i don't understand anything
Decode Ways
decode-ways
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into: * `"AAJF "` with the grouping `(1 1 10 6)` * `"KJF "` with the grouping `(11 10 6)` Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`. Given a string `s` containing only digits, return _the **number** of ways to **decode** it_. The test cases are generated so that the answer fits in a **32-bit** integer. **Example 1:** **Input:** s = "12 " **Output:** 2 **Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12). **Example 2:** **Input:** s = "226 " **Output:** 3 **Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6). **Example 3:** **Input:** s = "06 " **Output:** 0 **Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 "). **Constraints:** * `1 <= s.length <= 100` * `s` contains only digits and may contain leading zero(s).
null
String,Dynamic Programming
Medium
639,2091
1,630
hey everybody this is Larry this is day 23 of the Cod d challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's F today I'm in kyaan this is the great Gates and I'm ready to explore it uh yeah back to the problem but also if you want to you know learn more about my travels check out my walk with Larry Travel Channel yeah and come to Discord and we'll hang out anyway let's go hey everybody so yeah day 23 let's go hope you like the intro um yeah I'm still in Osaka for another couple of P today's PR is 6030 arithmetic Subway so sequence of numbers is called arithmetic give at least two elements okay yeah makes sense Fair uh you're giving an array of ing ends and you have to F return a list where can we rearrange to form a thing okay so one thing of course is that um if they're arithmetic oh no sub array not the entire thing okay well I was going to say it regardless um wait oh L and R okay how do I want to do it I see so basically you have numbers and you have queries and you're trying to figure out how to uh yeah I mean and you just try to figure out how to um how to answer the queries right so 0 Z so now the zero query uh 02 465 okay fine so okay so the thing to notice and you know sometimes you just have to do the math and N is uh well the number of lengths but n has 500 elements right and M has 500 elements so what does that mean that means that if we do n log n on every 500 queries what is that how fast is that right so that means that it's going to be M * n log M means that it's going to be M * n log M means that it's going to be M * n log M so 500 squar time log 500 right what is that sorry I'm just using a calculator right now 500 s time 500 it's about 674 th000 which is good enough for us to do cuz it's you know I mean it's back of the envelope but uh but I think we're going to be fast enough so yeah so that's really the answer then which is kind of a little silly cuz then it just becomes Force right so okay let's do n is nums um Q isal L of R right um and so we have a frame and then now for what is it um start n in sip of left R is it inclusive I think so yeah uh so then now we have kind of like a nums start n + one we want to sort this right so n + one we want to sort this right so n + one we want to sort this right so then now this is just what I'm working with and then basically for AP in sip of Cur right so this allow us to look at adjacent elements how we write this because I think that's actually little bit confusing to read but um yeah five length of current um one right so or we can start one maybe that's a little bit cener I don't know as long as you're consistent your convention I don't think it matters that much right so uh so Delta is equal to current sub assume that the length is at least two I guess two elements yeah one oops minus current Sub Zero right so then now if um okay so yeah uh. append uh something like if current sub I minus current sub i - one is not equal I minus current sub i - one is not equal I minus current sub i - one is not equal to Delta we change it to force and that's pretty much it right give a quick submit uh I didn't go over that in that much detail that's my fault uh but basically the idea um H I don't know why I just hacked out this one really quickly but my idea is just Bo Force right um but there's a little bit more than that I think um so obviously we did the math first and we saw that um o of n * Q * log n is fast enough um o of n * Q * log n is fast enough um o of n * Q * log n is fast enough because n q is less than or equal to 500 right and because of that we just sort every time which we said we would right and of course all space is going to be all of n plus Q um you want to say a reallocate memory with respect to current but you also need all of Q anyway um because of the answer away of space but yeah but the idea here uh I think the tricky part that didn't really go over is the arithmetic subarray part the subarray part I think this makes sense and you sort it um the part that allows you to sort is that you can rearrange to form arithmetic sequence and obviously uh you can form an arithmetic sequence if you know you go positive Delta and then negative Delta and meaning if you have something like I don't know 142 this goes up and then it goes down obviously that just means that it cannot be arithmetic means everything has to be either incremental or decremental with the same amount right uh and of course the uh the kind of fool you try to fool you a little bit by going negative but it doesn't really matter uh because it's just you know if it's negative then you just reverse it to get the same thing anyway right uh or you know not the same thing but a different but similar thing uh but the same weell right so yeah so based on that um you know the thing is noticing what did I do that like for example you have I don't know a sub one a sub 2 a sub 3 a sub 4 a sub five right and the idea behind arithmetic is that A2 minus A1 is equal to A3 - A2 is equal to this is equal to A3 - A2 is equal to this is equal to A3 - A2 is equal to this right and A4 - A3 is equal A3 - A2 or right and A4 - A3 is equal A3 - A2 or right and A4 - A3 is equal A3 - A2 or something like that and of course if you do um translative properly then you can just rewrite this as you know this is equal to this so we can just rewrite it as this and that's basically what I did here is that I just calculated Delta for the first two elements and I just go through all uh the entire thing for the rest of their elements um that's pretty much all I have for today let me know what you think uh if you have questions ask the question and don't say you know don't say explain more CU that's not like just tell me what you want yeah uh yeah that's what I have for today though let me know what you think stay good stay healthy to go mental health I'll see youall later and take care bye
Arithmetic Subarrays
count-odd-numbers-in-an-interval-range
A sequence of numbers is called **arithmetic** if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] - s[i] == s[1] - s[0]` for all valid `i`. For example, these are **arithmetic** sequences: 1, 3, 5, 7, 9 7, 7, 7, 7 3, -1, -5, -9 The following sequence is not **arithmetic**: 1, 1, 2, 5, 7 You are given an array of `n` integers, `nums`, and two arrays of `m` integers each, `l` and `r`, representing the `m` range queries, where the `ith` query is the range `[l[i], r[i]]`. All the arrays are **0-indexed**. Return _a list of_ `boolean` _elements_ `answer`_, where_ `answer[i]` _is_ `true` _if the subarray_ `nums[l[i]], nums[l[i]+1], ... , nums[r[i]]` _can be **rearranged** to form an **arithmetic** sequence, and_ `false` _otherwise._ **Example 1:** **Input:** nums = `[4,6,5,9,3,7]`, l = `[0,0,2]`, r = `[2,3,5]` **Output:** `[true,false,true]` **Explanation:** In the 0th query, the subarray is \[4,6,5\]. This can be rearranged as \[6,5,4\], which is an arithmetic sequence. In the 1st query, the subarray is \[4,6,5,9\]. This cannot be rearranged as an arithmetic sequence. In the 2nd query, the subarray is `[5,9,3,7]. This` can be rearranged as `[3,5,7,9]`, which is an arithmetic sequence. **Example 2:** **Input:** nums = \[-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10\], l = \[0,1,6,4,8,7\], r = \[4,4,9,7,9,10\] **Output:** \[false,true,false,false,true,true\] **Constraints:** * `n == nums.length` * `m == l.length` * `m == r.length` * `2 <= n <= 500` * `1 <= m <= 500` * `0 <= l[i] < r[i] < n` * `-105 <= nums[i] <= 105`
If the range (high - low + 1) is even, the number of even and odd numbers in this range will be the same. If the range (high - low + 1) is odd, the solution will depend on the parity of high and low.
Math
Easy
null
12
Hi gas welcome and welcome back to my channel so today our problem is wait you Roman so what have you given us in this problem statement, here we have been given a number wait number and what we have to do with it is to convert it into Roman number. You must be aware that what is a Roman number, what do we do, we convert the numbers into a symbol, a form, right, so some of our symbolic form is fixed for some numbers, so what will we do with it now? We will convert these numbers into Roman numbers. Okay, so what do we do? Let's understand through the example how to solve the problem. Okay, so what you have given here is that for van, you do ab, C for five, do that. Let's do Can you do that? Can do How far have you given the constant? Your constants will be from WAN to your number, it will be up to 399. Okay, it will not be much, so what do you have to do with this symbol? You have to convert the number, is it in Roman number ? So like what we do is ? So like what we do is ? So like what we do is take two-three examples and then understand the take two-three examples and then understand the take two-three examples and then understand the process okay suppose you have 3007 3792 okay then how will you convert it what do you have yours is 3000 okay but what do you just know If we know the value of 1000 then how many times will we write M which will become 3000. You will have to write M three times. Okay, so what has happened to you. If it has become 3000, what will we do with it? If we make it 3000, what will become of us? 72 Now in which range is this coming? This is more than your 900 but if it is above 500, then we can do it to someone, we cannot do it to 900, but we can do it to 500, so what will we do from here? 500 - We will do it, - We will do it, - We will do it, what will happen to you, if 292 is left then what will happen to 500, your di is di, you will do it, okay after that, your 292 is 10092, in which range will yours come, in this range but above C, the right is less than 400 but 100. If it is more than , then in this condition will 100. If it is more than , then in this condition will 100. If it is more than , then in this condition will you do it? If you do it to C, then how many times can you do it to C, because yours is 200, this is only for 100, so what will we do, you will do it to C, you will do it till the number of times, okay? We did C for 2 times, this becomes your 200, then 200, what will you do, min it, what is left with you is 92, now in what range will 92 fall, this If it comes in between then we can do it for 90. We can't do it for 100 but we can do it for 90. So we will do it for 90. What has happened here then we will do it here but here is this you? And for I van, if it happens then I, for how many times will you have to do it, you will have to do it for three times, so this is done, your Roman number is okay, this is done, now you are seeing, then repetitive, when are you doing it, you are 1000 You are doing it here, after that when yours was 100 like 500, you wrote it at the same time but what is still yours, this is the position of 100, there is still 200 left in it, what are you doing at that time. The again si to you times till the times you are doing it to the okay then here on the deputy time whom you are doing it to the van to the time you are doing it to the here because you had two look at it here you are doing it to it here you are doing it Okay and everything else you are doing it to everyone at one time you are just doing it okay so let us look at another example here like what we do is take 400 470 5 okay now tell me where will 400 come. You already have 400 CDs. So now people do it here. Write 400 CDs. How much do you have left? 75. Now 75 is in which range? Your 75 is your A. Here it is above and 96 is below so 50 is now doing it. You can pay L here, so what will you do with it now because by doing that people will be left with 25, right 25, after that you see where 25 will come, 25 will be yours, it will be less than 40 but what would have happened to 10, right here. Our What is Han? Five B is there. So we will write C here. Okay, this is done. Then you can see who is being repeated here. Here your C was becoming M. I was becoming I. What is happening here? Your tax is being done which is being 10 then your hundred is being done then your van is being done here now you are doing it repetitively right so how will we solve this problem what will we do here right here when our Also our 1000 will come, 100 will come, 10 will come, the van will come, then what will we do, we will do the loop, okay, so that till it goes below thousand, what should we do, keep doing that until it comes to 100. Till it goes below 100, what do you have to do? Whatever happens to 100, you have to do it in the represted mood. Okay, you will do it in the case of 10, you will do it in the case of van. Okay, so what is the condition here, what condition will you keep? Now you start yours with 1000, now I will start from the upper limit, maybe look at the number here, which will be the number as you have 1000 and 92, if you start below, but this too, yours will be 10 segrette, right this In this condition, if you start Excel, a lot of The range that we are seeing is not like that, we take access space and store it somewhere, then we will see in which range it is, then we will do like this, otherwise what will become of our extra? If there is space, then how can we solve this? What will we do? We will start in the above manner, like what we did from here, first look at 3000, start from right here, start by taking 3000 first, then work on 1000. When we saw that what happened now is that it has become less than the number, then we focused on 100. Okay, after focusing on 100, when it has become less than 100 i.e. when it has become 92, i.e. when it has become 92, i.e. when it has become 92, then what should we do about it? Focus on what we have given below, right, so you have to do it like this, so see what we have done here, we have to depend on the answer in the sting, okay, so we have taken the answer, what will we do, we will see here. Is your number related to 1000, can it be 2000, can it be 3000, is your three, will the number be only up to 2999, so if it is greater than 2000, what will you do? It can happen in repeat mode also. So now see people, okay if it will be only 1000, look, this will be your only thousand 99, so you will mine it once, okay, if you will mine it once, then it will do the condition, it will not cut the right, it will not be automatic that the right will look at the below condition. So if you had this 2000, what would he do? He would first see if it is a thousand seater, if it is greater, then he would take the M. Then he would see, then he would mince it. What would he do if it is 1000 cigarettes? Then he would take the M. Okay, so. Process: Okay, so. Process: Okay, so. Process: What we are going to do here is that we will take a loop here and see if our number is greater than a thousand. If it is greater then take M and append M to it. Okay, then what will you do with the number. 1000 - If you do this, then 1000 - If you do this, then 1000 - If you do this, then this will continue till yours goes less than 1000. Okay, as soon as yours goes down, you can check again, is it more than 900, like it happened to you in this case? Here I will show you the second number, okay, like you have 1090, what do you do in this, now once you subtract 1000, then what happens, your nine date would be 99, right, so what should you do in this condition, what will you do to make it 100. Or you will do it as 900 and after that you will do it for 900 right because you know the symbol of 900, so here now for 1000 you do M for 1000 and as you know that it is more than 900 or it is also equal to it. If there is a net then what do we do with it, here we reduce it and mine it, so what do we do here, you know the check win symbol, let's take all of it from above, okay, so here you are 900 Let's see that if the number that is left till now is more than or equal to 900 then what should we do in that condition, reduce it and minise it from 900. Okay, after that, the number that is left, now people check. Is it more than your 500? If it is more than 500 or equal to it, what will we do with its nature? Will we do it? What will we do with it? 500 - We will do it. What will we do with it? 500 - We will do it. What will we do with it? 500 - We will do it. Okay, after that we will see what is the number. Is it our food more than 100? Is it greater or equal then what will we do with its nature? We will CD it and mine it for 400. Okay, after that, what is your repetitive mode? In the case of 100, right, when will you have repetitive mode? When yours is less than 400. And if it is equal to or greater than 100, then what can you do in that condition, if it is your 100 then you will do it once, as soon as you mine, it will be reduced, right, then it will be your fullfill, otherwise it will be outside. You will go through the loop, so what will we do, here we will loop it, then what will we do in the answer and we will do 100 - Okay, then we will in the answer and we will do 100 - Okay, then we will in the answer and we will do 100 - Okay, then we will see whether our number is &gt;= 90, if so, see whether our number is &gt;= 90, if so, see whether our number is &gt;= 90, if so, what will we do, we will append it with X and get 90. - Will do ok and get 90. - Will do ok and get 90. - Will do ok then we will see here also in case of 50 if it is greater than or equal to 50 then we will do lpnd and what will we do with the number we will subtract 50 ok then in the case of 40 we will do the same and check if the number is greater than itself. Give equals tu will be 40 then what will we do we will append excel and make minus 40 ok then we will repeat mode in case of 10 it can be our when your 46 is less and more than 10 right 30 45 not 45 35 kind of If there are numbers then give them greater, if 10 is less then give 40, then in repetitive mode it will be there, then what will we do in that condition, we will do wild lab wire loop in it and keep on opening Then we can apply this condition, if the right number is ≥ can apply this condition, if the right number is ≥ can apply this condition, if the right number is ≥ 9 then what will we do, we will append If it is here, then what will you do by appending IC and -4 from here, what will you do by appending IC and -4 from here, what will you do by appending IC and -4 from here, what will you do by subtracting it, after that if it is possible that your number will be &lt; 4 and &gt; 1, then in that condition &lt; 4 and &gt; 1, then in that condition &lt; 4 and &gt; 1, then in that condition you can do it to Preeti like three. For you, for three, you will do 3i, for 2, now you will do it, then it can be your gift, in that condition, what will we do, we will do a loop, and finally the answer will be ours, what will we do by turning? It's okay, I hope you have understood. If you liked the video, please like, share and subscribe. Thank you.
Integer to Roman
integer-to-roman
Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. **Symbol** **Value** I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: * `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. * `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. * `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. Given an integer, convert it to a roman numeral. **Example 1:** **Input:** num = 3 **Output:** "III " **Explanation:** 3 is represented as 3 ones. **Example 2:** **Input:** num = 58 **Output:** "LVIII " **Explanation:** L = 50, V = 5, III = 3. **Example 3:** **Input:** num = 1994 **Output:** "MCMXCIV " **Explanation:** M = 1000, CM = 900, XC = 90 and IV = 4. **Constraints:** * `1 <= num <= 3999`
null
Hash Table,Math,String
Medium
13,273
4
hello and welcome to another Elite code solutions video this is problem number four median of two sorted arrays this problem is given two sorted arrays nums one and nums two of size M and N respectively return the median of the two sorted arrays the overall runtime complexity should be o of log M plus n example one for this problem we are given an input nums one array of one and three and our nums two array is just two our output will be two this is because you can merge the two arrays and see that it's one two three and the median of this would be two for example two we're given nums one of one two and nums two of three four the output for this is 2.5 and this is because when we merge it 2.5 and this is because when we merge it 2.5 and this is because when we merge it into one array we have four values in our array and the median would be the average of the two middle indexes so it's two plus three divided by two which is 2.5 so let's go through an example is 2.5 so let's go through an example is 2.5 so let's go through an example for this example we'll have nums one as one three five seven and nums two will be two three four for this solution we need to ensure that we're dividing the array in such a way that the number of elements on the left side is equal to the number of elements on the right side and we'll do that by using partition within both of our input arrays and we'll calculate our partition position in both of the arrays based on the mid index of our smaller of the two arrays and this partition will separate the left and the right halves of the combined array and we'll continue to Loop through our two input arrays until we have a valid partition to get a valid partition we'll have to have the maximum elements on the left side will need to be less than or equal to the minimum elements on the right side so to start off first thing we want to do is determine which of our two arrays is smaller so in this case it's our nums two array which has a length of three and we'll use our smaller of the two arrays to calculate our first partition we'll have two main points in our combined array that we want to keep track of are left and right and these are used to determine if we need to move left or right with our partition to find a valid one so starting off our left will just be equal to zero and our right will be equal to the length of the shorter of the two arrays in this case nums two is shorter and its length is 3. next we'll want to calculate our partitions our first partition will be based off our left and right points and will be equal to left Plus or right divided by two and for all the division we're going to be doing round down division so we stay with whole numbers these numbers will be used for indexes in our arrays so in this case three plus zero divided by 2 is 1.5 but we're going zero divided by 2 is 1.5 but we're going zero divided by 2 is 1.5 but we're going to round it down to one our second partition will be based off our first and it'll be equal to half the total length of our combined array minus our partition one so our second partition will be four plus three which is the length of nums one plus the length of numbers two divided by two rounded down so that's seven divided by two which is 3.5 seven divided by two which is 3.5 seven divided by two which is 3.5 rounded down to three minus one equals two next we're going to want to use our partitions to calculate our Max and Min values within the correlated array so the first thing we want to do with Partition one is make sure it's not equal to zero or the length of our shorter arrays so since it's not zero or three we're good now that we have our partitions we want to calculate our minimum and maximum values based off of our partitions so our partition one will be used with our nums two input since it's the shorter of the two arrays and our partition two will be used with nums one since it's the longer of the two arrays to find our minimum right value in numbers 2 we take partition 1 and use that as an index in nums two so partition one is equal to one and in position one of nums two is three now we'll use our partition two to do the same in our nums one array so our maximum left value in nums 1 is our partition two minus one so two minus one is one and our value in numbers one position one is three and now finding our minimum right value in our nums one we take our partition two and use that as an index in nums one array so in numbers one array at position two we have five now using these four values we can determine if we have a valid partition or not to have a valid partition we need to our Max left one value to be less than or equal to our minimum right two value and we need our Max left 2 value to be less than or equal to our Min right one value that's this statement here in our case this is true so we do have a valid partition and now we can use our Max and Min values to calculate our median since the total length of our combined array is odd all we need to do to determine our medium is to take the minimum value between our two Min right values in this case our Min write one value is 3 and our Min right two value is five so the minimum between those two is three so for this problem the median of our two arrays is three let's jump into the code the first thing we want to do is determine which of our two input arrays is shorter and swap the shorter one to be nums one and our longer one to be nums two just to make it easier for the rest of the problem next thing we want to do is determine the total length of our combined input arrays and we can do that by taking the length of our nums one array and add it to the length of our nums 2 array and we're also going to want to know half the total length so we'll take our total length divided by 2 and we'll use two division signs to round down next we're going to want to Define our left and right points and our left will be equal to zero and our right will be equal to the length of our shorter of the two arrays which since we've swapped them will always be nums one next we're going to want to use a while loop to loop as long as our left is still less than or equal to our right within this while loop we're going to be calculating our two partitions and our Max left values and our Min right values and once we have a valid partition we'll just be exiting this Loop early first we'll calculate partition one which is our left Value Plus our right value divided by 2 and we'll be rounding down again for this division next we'll calculate partition two which is equal to half length minus partition one now that we have our partitions let's calculate our Max left values and our Min right values for our Max left one and our Min right one values we'll be using partition one and our nums one array and for our Max left two and Min right two values we'll be using our partition two with our nums two array one thing we also want to do with our Max left and our Min right values is make sure that our partitions are not equal to zero or the length of the respective input array so we can add the checks in line for all of these calculations and if the partition is equal to zero or the length of the input array we'll just set the values to negative infinity or Infinity the max left values will be negative infinity and the Min right values will be Infinity now that we have our Max left and Min right values calculated we can check to see if we have a valid partition and our partitions are valid if our Max left one value is less than or equal to our Min right two value and our Max left two value is less than or equal to our Min right one value and if this is true and we have a valid partition we want to determine if our total length of our combined arrays is even or odd if it's even we'll have to take the max of our Max left values and add it to our Min of our Min write values and divided by 2 and if it's odd we'll just take the Min of our Min write values and at this point with our valid partition and our median we've solved the problem so we can just return our median value this takes care of what we do when we have a valid partition but now we need to take care of the case where we have an invalid partition when we have an invalid partition we'll either need to move our partition to the right or to the left and we can do that by updating our right and left values so when our Max left one value is greater than our minimum right two value we're going to want to move our partition to the right otherwise we'll be moving our partition to the left at this point we're done with our solution so let's try running this all test case paths so let's submit our solution was accepted so that's it for this problem if you like this video and want to see more content like this make sure to check out my channel thanks for watching
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
83
Hello everyone, Evgeniy Sulima here and today we are considering the solution to the problem years code number 83 removing duplicates from a sorted list and as the ambassador of this task we are given a sorted linked list and we must remove all duplicates in such a way that each element, that is, each value is repeated only once on the tribe on the input we have you linked list with the values ​​112 and on the output we list with the values ​​112 and on the output we list with the values ​​112 and on the output we should get 1 and 2 that is one of the duplicates of Agnieszka should be removed the second example is one two three on the output we want to get one two three that is duplicate one and three they should be removed now let's look a little at our code, that is, we were initially given some kind of api and here we have a public class with not which has an integer value in2u has a link to the next element or next and also the default mid constructor which initialize the given and node with some kind of integer value, let's think about how we can solve this example, that is, we have some kind of linked list that we can do, that is, I taught taking into account the fact that the sea link from the worksheet is just an amendment to the entire list sorted I can just loop through the entire list, that is, I iterate and say that if the current value is equal to the next value, then I just have to somehow remove this element, how can I delete in a linked list, I simply interrupt the link, that is, this element has a next element there will be not one, but this one, and thus then the garbage collector will collect it and the same will be the construction site, that is, for the three, I say that the next element it will be equal to with through one, that is, on the street yes you are here, we will put that it will be cash and this is a C grade, it will also be deleted, let's try this idea in code, dad, that is, what can we do here and so clearly initially we create some kind of snood that will be like temporary changes for me, that is it not caring, which is equal to head, this cool note that I was passed to this method further, that's all I do, I go through the loop, how it will look like the game that while the current element is equal to the channels and also while the trace is a link to the next element in car and a is not equal to can I do the following I check the game what if car and next. shaft is equal to caring shaft that is, the current value then in this case I write that the Koran. next is equal to car and next, that is, it interrupted from the next moment, which while it was before that, but if this did not happen, that is, everything is fine for me, this is not to repeat the element, then I am simply interrupting the link to here is my test fluid but with which we worked that Koran Travin car and next car and . car and . car and . next and thus I will get to the end of the list, that is, with these checks I run through the entire array and also avoid it in any case and now I do return head, let's check first with our compilation, then everything here should be correct, here it is also correct, now let's go through according to logic, that is, for example, I will go through this selection, that is, I come to the conclusion that the cards are equal to 1, now I check not equal to the moon, equal to all, now you compare that the value of my current ones is equal to the value of the next element, and now I say that the link on the next one is not equal to 2 and switch to the next element, then what do I do? I go to the two here, as if to work it out, I simply interrupt the pointer of the current element on the three. This moment is to work it out and I also delete the link. Let’s try to compile the link. Let’s try to compile the link. Let’s try to compile our method first and see that I don’t have any errors and so and that I don’t have any errors and so and that I don’t have any errors and so yes, that is, compilation errors they are now let's try this solution behind the event that you are not that in all test cases it works well for us and so we see that the problem has been solved, that is, there are no comments on the complexity here we have time complexity in the worst case latin because we have to go through the entire array in any case and from memory mun for no we don’t allocate a and from memory mun for no we don’t allocate a and from memory mun for no we don’t allocate a new one make peace that under the current new element this is where we end the reviewer given change I bid you farewell all the best
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
165
Ko Hi I am you Sherawat and welcome to my channel today we will discuss the temple jewelery no problem two numbers we live with 2012 - 09 nintendo character live with 2012 - 09 nintendo character live with 2012 - 09 nintendo character director point to point se 2.5 not to the return of the day quick revision number of units Level of weight number-20 for example first number 0001 number-20 for example first number 0001 number-20 for example first number 0001 number three and whose first second third fourth number 90 weight of a is 1051 to is 1.1 and you will return weight of a is 1051 to is 1.1 and you will return weight of a is 1051 to is 1.1 and you will return minus one big boss weight to is greater than words in one no key knowledge tree to understand It's post 102 weight and took it 1.5 2.5 weight twist 7.5 weight and took it 1.5 2.5 weight twist 7.5 weight and took it 1.5 2.5 weight twist 7.5 point 3 lesson stand slide or two players and obstacle flu 12308 first level player wave tough player weight 2072 subscribe and subscribe the 123 clearly straight 2012 - Subscribe Returns clearly straight 2012 - Subscribe Returns clearly straight 2012 - Subscribe Returns of the Day Quick and Simple Return Minus One Otherwise Give One is Equal to the Return of the Day Ajay Ko Baar Palt Hua Hai Calculate the Length of Wave in 2K Knowledge Tarlu Over Maximum Lens for Nikon D hua Hai Ajay Ko Flash Lights Understand This Fuking Name Pal off 7.5 2.5 128 7.5 to 1000 2000 two Pal off 7.5 2.5 128 7.5 to 1000 2000 two Pal off 7.5 2.5 128 7.5 to 1000 2000 two that and will do shampoo came now from half that access not why will simply written in this great dane one else will return - great dane one else will return - great dane one else will return - written in knowledge and notes of running code by submitting it a this IS ACCEPTED TO ITS USERS TO CONNECT WITH ME OR ADARSH SOCIAL PLATFORM DAL DEGEN ON THIS GIVING DESCRIPTION BOX LONG AS YOU WANT SOLUTION CODE TO 10 PROBLEM THE LANGUAGE MENTIONED IN THEDESCRIPTION BOX BELIEF AND IF YOU HAVE ANY QUERIES AFTER PREST WAS LIKE VIDEO HIT The Like Button Subscribe My Channel Thank You For Watching
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
133
hey everybody this is Larry this is day eighth of the league code daily challenge I believe yeah hit the like button in the Subscribe button join me on Discord let me know what you think about today's farm and of course there's gonna be a week two uh after that so definitely check that out as well um today's problem is gonna be one day three Chrome graph I feel like we did this very recently right remember I mean it's like way oh okay oh no I think the one that we did recently was a premium problem with like a random extra note I guess but it's still good I think that was like two three weeks ago maybe something like that um but I don't know time 45s okay fine I took a look at today's Farm I mean I think this one is just way um deformation the prom statement is pretty straightforward right it's just give it a deep copy of just giving a graph return a deep copy of it and in this case instead of um I think that one was maybe a trio linked list I don't remember but you have a list of neighbors instead and the part the hard part about this is that yeah you can there are a lot of ways to go and do this um you know you have to be a little bit careful I think the way that I would think about it though is kind of separate out the construction of the notes and um uh several construction of the notes and then the um the construction of the list right the way that I have it um the way that I usually do it and I didn't I don't think I explained it as well last time because I had some very good questions in the comments previously um but the way that I do it is having a lookup table um and then now for this node well how they giving us the lists you're just giving like one node so I'm just looking at input I guess you're just given one node and that an adjacency list okay fine I mean that's fine either way but the idea here is um okay so then maybe you do a recursive creation and N is equal to 100 this way easy or like in terms of complexity so you wouldn't have to worry about it um yeah and then you have a node right and then basically the way that I would think about it is this uh dysfunction returns a new version of this note right returns a new version of this node right um and here uh let's just say um I don't know new node is you go to fetch node right and then maybe you have a fetch function that looks like this for a node and then basically if you look up or if node is in lookup return lookup of node and move out by just a little bit differently if this is not in it then look up of node is you go to new node of Y of node.value we will just we'll we of Y of node.value we will just we'll we of Y of node.value we will just we'll we don't have to worry about the neighbors for this part but yeah um and I've gotten some questions about uh previously about why this works um and I don't think I kind of um kind of just skipped over it to be honest the last time I did this because I don't know I think it just uh it comes it's just an experience thing right and I kind of for sometimes forget uh people might not have the experience and which is that you assume that the key in a python hash table or lookup table a dictionary is going to be um immutable right but what so why is the node which you can you know make random changes why can't you use this as a key um to this lookup table well it turns out that for most things um it's not the content of the note that matters it's the address of the node because the address of the node is the immutable part so basically what I'm saying and there are other ways to write this you can even think about it um but basically this is just looking up the um the address of node or in some languages you've made quite a pointer you can call it an address and all this stuff and python is going to be the um I think it's called an object ID or something like this maybe or maybe not an object ID but something idea I forget but that idea is the core for it and you can even do it that way if you want to be more explicit right you can just do something like this and that will get you the um the pipeline address of the node and because we want to map exactly one node object with this second node object um this should be okay because um if we get a different address then it is effectively a different input right so basically that's what we're trying to do here so okay and then now um trying to figure out how to um how to clean do this in a clean way um I mean maybe you can do something like for uh be in no dot Neighbors um uh new node dot Neighbors dot append um construct a free but this doesn't quite work yet I'm trying to think real quick um this doesn't work yet because now you have like infinite recursion is why um I mean you could even see this yourself if you just have done something like this um right I'll give you a um yeah maximum recursion thing um and the reason is because it's going back and forth right I mean yeah you don't really need that many uh inputs there um yeah I was just trying to think foreign a lot of ways to handle it but I'm just trying to think about a clean easy way um I guess the other one that we had was a trio linked list so then it was uh effectively a dag uh maybe a double deal like this I don't remember but either way it was effectively a dag um which won't have this issue uh I did kind of expected this but and you can kind of um I guess the other way we could do that is do a fetch instead um so then now this won't um been infinite Loop it also won't be um it will also won't be correct because it's not uh oh this could be none wait what that's weird Why Can't This be none now I guess this if notice none okay well I mean that's just a silly case really right I mean that's just like useless waste of time but yeah uh as I was saying um you don't really return the right graph so this is going to be well um but I think maybe the slightly better I mean and you could do it in both ways it doesn't really matter but yeah I mean I guess it doesn't really matter uh you could I was thinking you could do it at a breakfast search or that first search um either one is fine with this construct but I'm just gonna do it recursively and then just you know have a done thing right and the same thing we've done a price here which is that um if notice and done we return uh done of node maybe I don't know right um and then now after all this we can do it one more time well after this we can do it one more time and just construct uh V Maybe does it still go oh um mm-hmm mm-hmm mm-hmm oh whoops that's why oops that was a silly type I was like don't think I think the logic is okay but let's give a submit to see if maybe I haven't still made a mistake I look okay 1103 streak um this is gonna be a linear time than your space can get around either of those really um linear spaces here but that's also the size of the output so you really can't change anything about it linear time because for you to know you only call this one thing once um well and just to be clear linear um time and space in this case well um well yeah linear time and space in this case is actually V plus e where V is the number of vertexes a number of nodes and E is the number of edges right because you have to process each Edge you know twice I guess maybe four times in both direction or something like this um and yeah but it's still going to be o of e um and then o b because you know you only call it just for each node once or twice maybe but the second time will be you know uh pretty early so yeah um that's all I have with this one I'm curious what I did in the past hmm man past Larry did have this much cleaner but I guess this is the same idea I just kind of added a new thing for fetch um yeah I guess that's what I did this one is way more complicated oh this one uh I was kind of maybe talking about it but I don't know yeah and then this well that time I did a buffer search and then also cached the thing explicitly yeah um but they all do the same thing really so yeah let me know what you think uh yeah hope y'all have a great weekend stay good stay healthy to good mental health have a great long weekend if you are in a country that has an offer celebrate it but yeah stay good stay healthy to good mental health I'll see y'all later and take care bye
Clone Graph
clone-graph
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph. Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph. Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors. class Node { public int val; public List neighbors; } **Test case format:** For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list. **An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph. **Example 1:** **Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Explanation:** There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). **Example 2:** **Input:** adjList = \[\[\]\] **Output:** \[\[\]\] **Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. **Example 3:** **Input:** adjList = \[\] **Output:** \[\] **Explanation:** This an empty graph, it does not have any nodes. **Constraints:** * The number of nodes in the graph is in the range `[0, 100]`. * `1 <= Node.val <= 100` * `Node.val` is unique for each node. * There are no repeated edges and no self-loops in the graph. * The Graph is connected and all nodes can be visited starting from the given node.
null
Hash Table,Depth-First Search,Breadth-First Search,Graph
Medium
138,1624,1634
31
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 31 next permutation before we get into the solution for this i just want to say i hate this problem hate this is my least favorite problem and i just want to say i know how to solve it i know the solution and i think i can explain it pretty well but if you want a deep understanding of the intuition behind it sorry i have no idea this is just one where i understand it enough to get through but if you want a proof of why it works this isn't the video for you i can't do it i hate this problem so that being said let's read the question prompt it's quite a mouthful a permutation of an array of integers is an arrangement of its members into a sequence of linear order for example for array one two three the following are considered permutations of array one two three one three two three one the next permutation of an array of integers is the next lexicographically greater permutation of its integers wow they really need to proofread this they are missing like spelling everywhere anyway more formally if all the permutations of an array are sorted in one container according to their lexicographical order then the next permutation of that array is the permutation that follows it in the sorted container if such arrangement is not possible the array must be rearranged as the lowest possible order i.e sorted in ascending order i.e sorted in ascending order i.e sorted in ascending order for example the next permutation of one two three is one three two similarly the next permutation of array 3 2 1 is 3 1 2 while the next permutation of 3 2 1 is 1 2 3 because 3 2 1 does not have a lexicographically larger rearrangement given an array of integers nums find the next permutation of nums the replacement must be in place and use only constant extra memory so if we look at our example here with the numbers 1 2 3 obviously the next biggest number that we can form with this is going to be one three two right because all of our possible options are three two one we could have three one two we could have two one three we could have two three one or one oops you can't see that or one three two and obviously this is the smallest uh number that comes after this one each one of these is bigger than this so obviously this is our next permutation here so we read the question prompt we looked at an example although the example is quite simple we need to put this into some sort of algorithm to solve it i'm going to wipe away all this text here because it's taking up too much room and we're going to come back and actually think about how we might solve this okay we read the question prompt and we looked at a very simple example but unfortunately it's not really going to be that straightforward because the numbers are usually going to be a little bit trickier and it's harder to actually derive what happens when you look at you know this basic example of one two three it doesn't really tell us how to do it so let's think about the two cases that can happen in this problem which the problem description tells us the first is that there actually is no next permutation and this is the case where we have something like three two one because this is already the largest number we can get by rearranging these three numbers the next permutation is just going to be the wrap around so basically it becomes the smallest number we can get so in if basically our input is sorted in descending order from left to right then we just return the reverse of our input and that's our answer so that's the first case that you need to take care of the other case is when you actually need to find the permutation so let's look at you know 1 four five eight seven right this is our number what is our next permutation here well we can see that if we swap the seven and the five we'll get um you know the next one because right we want to swap and then we also need to swap the five and the eight after we do the swap so it would be one four seven eight five eight is the next larger number right so how did we actually do this what we want to do here for this problem and again i'm sorry i don't know why this works agai i can't give you the proof for this but i can just tell you how to solve this problem what we want to do is we want to find the point in our array where it stops being um increasing starting from the left right so we can see that 145 we basically want to find the point where the array stops being sorted if it is even sorted at all it could just be that it's not sorted in which case that's fine i guess the first number would just be sorted and we'll call the number where the array sorry the index where the array stops being sorted as our pivot so in this case eight is our pivot here uh sorry five is the pivot apologies because at this number this is the final um value that is in sorted order right seven and eight are not in sorted order so we need to make some swap with five with one of these numbers here that's not in sorted order and what we want to do and the way that we're gonna do this is we're gonna start from the right and we're gonna go left and basically we're looking for the point where nums of i is actually greater than nums of i minus 1 right so this would be this 8 right because that would imply this is when the first point where the array stops being um increasing uh starting from the left sorry going from the right apologies so we will identify um our pivot as this eight so basically we oh sorry this is the number where it stops um i guess increasing as we're going to the left and then our pivot is actually the index before it so it's going to be this one so then the point where nums of i is actually greater than numbers of i minus 1. so this becomes our pivot and then what we want to do is we're going to start from the right again and what we want to do is we want to take the first number that is greater than our pivot and the reason that we want the first number that's greater than is because that will be the smallest possible number that we can swap with and the reason that this works is remember we're going from left to i keep saying uh the wrong way we're going from right to left and we're finding the first point where the array going from right to left is not sorted so because this portion is sorted in i guess increasing order right it's going up as we go to the left when we swap this will be you know whatever that first number is going to be the smallest possible one that satisfies you know our next permutation uh condition here so what we do is we swap it with the first number starting from the right that is bigger than the pivot number that we've identified earlier so let's do that swap so we'll say one four seven eight five now unfortunately this isn't our answer right we need to swap the five and the eight and remember that this part of the array after the pivot was sorted before in increasing order like we saw so that means that if we actually reverse this array right we'll actually get this part uh as the smallest one right because if this is sorted in increasing order if we then reverse it then it's going to be um sorted in decreasing order which is the next smallest arrangement of these numbers and if this doesn't make sense i invite you to play around with this remember the first thing that we're going to do is we're going to find the pivot and again these diagrams suck and i think it's much easier to look at this in code and kind of get what we need to do but essentially we want to find the pivot index and then what we want to do is we want to swap with i guess first num to the right of pivot such that um let's see the num is greater than yeah it's just greater than the pivot right and that's going to be our swap and then we just need to reverse so reverse uh to the right of the pivot and that will get the right side of the array uh after the pivot in the right order and remember the reason that we do that is because we are going from right to left looking for the point where this array stops increasing right so we go from seven to eight because that's increasing but then when we hit the five it stops increasing so this is our pivot point then we swap it with the first largest number greater than five to the right of the pivot point so the first largest number to the right of five is going to be the seven then we need to just reverse this because remember this part was sorted that was kind of our original search condition here and then once we reverse this we'll have it in the right order because now it'll be in that sorted order and now we'll have our next permutation which is our answer again i don't know how to prove that this works i just know that this is the solution and this is the most optimal way to do it this is the best i can do i'm sorry so let's actually go write the code hopefully that will make things clearer and if it doesn't i don't know maybe go play around with the diagrams if you have leak code premium go look at the solution maybe you can read it and understand uh this is just one of those questions like i said i absolutely hate this problem it is terrible uh how you're supposed to figure this out on an interview i have no idea you're probably gonna fail if you get this and you haven't memorized it um so yeah i have no idea i hate this problem so let's actually go to the editor and write this out and be done with this abomination of a problem okay we're back in the editor let's write the code for this so we can be done with this abomination of a problem and we never have to see it again so remember that we need to look for the pivot point if it exists remember it can possibly not exist in the case that we have something like 3 2 1 where there is no pivot and all we need to do is simply reverse the array so let's say our pivot is going to be equal to none because in the beginning we don't have one and remember we're going to be going from right to left looking for the point where the array going from right to left stops increasing uh for when it's going right to left so we're going to say 4i in range uh len nums minus one and remember we're going to the left oops sorry we're going to the zeroth index this time instead of the minus one because remember we're comparing with the or comparing index i with index i minus one so we can't actually go to that uh final index because we'll have it out of bounds error so we're going to say if nums of i is actually greater than nums of i minus 1 then what we want to do is that is our pivot point and remember that it's the index minus one the pivot is the actual number that um is the smaller one so for example like in our code i think it was uh what did we use so we use one four five eight seven so we go from the right okay is nums of i so is seven greater than five eight no it's not so we keep going is eight greater than five yes so that means that our pivot is actually going to be this 5. so we want to say that our pivot equals to the i minus 1 and at this point we found the pivot and we can actually break out of this loop now what we want to do is we want to add an else statement to our for loop and if you don't know how else statements work with for loops essentially if the for loop completes if it goes through the entire iteration here and doesn't return or break or some sort of you know exit out of the loop early then this else condition gets run so in this case if we go through the entire array and we don't find a pivot that means that the array from right to left is actually increasing the entire time so this is going to be the case that we have one two three right that means that it's sorted in increasing order from right to left which is that case where we actually don't have a pivot so in this case all we need to do is actually just numbs.reverse numbs.reverse numbs.reverse and then return and it actually tells us not to return anything we just modify nums in place that's why we just modify it and then we just return now what we want to do is we found our pivot now we need to find that first point that's actually great the first number to the right of our pivot that's greater than pivot and we can make the swap so in this case it's the seven so what we're going to say is we're going to say swap and this is going to be the index of the swap we're going to say length of nums minus 1 and we're going to say while nums of swap is actually less than or equal to nums of pivot remember we're looking for the num the first number from right to left that is greater than the pivot because this is the next biggest number that we want to swap with to get the smallest number when we actually you know return our permutation here so while you know we have numbers that are you know less than our pivot obviously it doesn't work that way because if we swapped it we get a smaller number and we can't have that we need the next bigger number so we need to find the smallest possible next number we can and because the array is sorted from right to left as we kind of established in this part the first number that we find from right to left that satisfies our condition will be the one that we want to swap with so we want to basically until we find that point where this is no longer true we just want to decrement swap and we're guaranteed to find it in this part of the array so now what we need to do is actually swap the numbers so we're going to say nums of pivot remember pivot is our actual index not the number and then swap is also the index so we need to swap these so we're going to say oops comma nums of swap equals to nums of swap and then numbs of pivot so we're going to swap these two and then what we want to do we want to say nums remember that after we make the swap so 7 gets swapped with 5 we need to swap this part of the array i'm sorry not swap we need to reverse it so that way we can get the order because remember this part is sorted in you know increasing order as we're going from right to left so to get it in the smallest possible representation of these numbers we just need to reverse it and that will have it in the opposite order and then we're basically done so we want to reverse everything from the left of our pivot index so we want to say nums of pivot plus one everything to the right of that we want to say revert is going to be equal to reversed nums of pivot plus uh plus one basically we just want to reverse everything to the left of the pivot and that's all you need to do um we just return here let's actually make sure we didn't make any bugs anywhere and submit this and cool we see that it runs so what is the time complexity for this algorithm well in the worst case we're going to make one entire pass through our array and this is going to be the case where essentially we need to um you know go through to figure out that actually there is no next permutation in that case all we need to do is we would go from right to left an entire time and then we need a you know a left to right iteration to actually reverse the numbers so it would just be big o of n plus big o of n so that's you know 2n but asymptotically this is still just big o of n and like the problem description told us uh we do this in place and we don't use any memory so as you can see we haven't defined any extra data structures uh the reverses happen in place and therefore our space complexity is going to be big o of one so that is how you solve this problem hopefully looking at the code made things a little bit clearer i think this is one where you may need to play around with it a little bit find some numbers try the algorithm prove to yourself that it works i apologize if this isn't the best explanation in the world i'm not going to lie like i said i absolutely hate this problem and i'm not going to lie to you when i was interviewing for you know companies that asked this i just memorized it i have absolutely no idea how the proof for this problem works um this is just one that i memorized and if i got it which thanked the lords i never got in an interview um you know i was just gonna regurgitate it try to explain it as best as i can if they ask questions about stuff then you know hope for the best but this i hate this problem and i pray to god that you do not see this in an interview um because this is just number one so uh thank you for watching this video hopefully uh you haven't been too put off by my um rambling and hatred of this problem i promise uh my other videos are not like this i just really hate this problem as you can tell anyway thank you for watching if you enjoyed this video please leave a like and comment uh you can comment you know i hate this problem too this problem whatever you want in the comment section below anything helps with the youtube algorithm if you want to see more content like this one obviously not this problem because it sucks but um if you want to see more videos like this then please subscribe to the channel otherwise thank you and have a nice day bye
Next Permutation
next-permutation
A **permutation** of an array of integers is an arrangement of its members into a sequence or linear order. * For example, for `arr = [1,2,3]`, the following are all the permutations of `arr`: `[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]`. The **next permutation** of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the **next permutation** of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). * For example, the next permutation of `arr = [1,2,3]` is `[1,3,2]`. * Similarly, the next permutation of `arr = [2,3,1]` is `[3,1,2]`. * While the next permutation of `arr = [3,2,1]` is `[1,2,3]` because `[3,2,1]` does not have a lexicographical larger rearrangement. Given an array of integers `nums`, _find the next permutation of_ `nums`. The replacement must be **[in place](http://en.wikipedia.org/wiki/In-place_algorithm)** and use only constant extra memory. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[1,3,2\] **Example 2:** **Input:** nums = \[3,2,1\] **Output:** \[1,2,3\] **Example 3:** **Input:** nums = \[1,1,5\] **Output:** \[1,5,1\] **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 100`
null
Array,Two Pointers
Medium
46,47,60,267,1978
350
hello everyone so in this video let us do two problems fine so both of them are easy the problem name is intersection of two arrays one as well as intersection of two arrays two let us solve both of them in this video see so the problem statement goes like this that given two integer arrays nums1 and num2 return an array of the intersection each element in the result must be unique and you may return the result in any order that's your problem as you can see that numbs1 and num2 is given to you there are different arrays and just have to like in the end it turns out an array or a vector that is storing out the intersection of both of these numbers in this whole array but they should be unique even if multiple intersections are there you just have to like print out the unique ones as you can see that there are two tools that are intersecting but you only have to return a single two because unique elements will be like returned so when i say unique things only one thing comes to my mind that is fast enough and like which can give me unique things that is set keep that in mind for further problem solving also fine so it means that set is somewhere used now the next thing is how can i find out the unique elements there are multiple ways you can use maps you can use sets whatever you can use but uh there is also one more technique that is two pointers that is also very much fast and you can use that will help you to actually use this technique in a lot of problems also so let us do that technique so for using two pointers to find out the matching elements what you will do is you have to first sort out both of these errors so for sorting it takes n log n but no problem it is under time constant only so because it's only a thousand so what you can first do is that sort out both of these arrays okay let us move on to a drawing word so after sorting let's say the array becomes like this okay so what is a two-pointer technique okay so what is a two-pointer technique okay so what is a two-pointer technique what you'll do you'll you use two pointers so pointers mean that there are two arrows as you can see or two variables you can name it i and j okay and then what you'll do is that you will take these two variables or pointers i'm just using pointers here so pointers means that these are two variables that are pointing towards these indexes and what they do is that i will just check them whether both of these values are giving same like the both of these values are same or not so what you can say is let us take some change some different color as you can see that both of them are one so what it means that both of them are one so it means that it is giving some intersection because i want to find out the numbers that are same in both of the arrays so i can use some array to store out one fine let us move down because both of them are same let us move out our i and j both to the next value so i and j both comes down to the next value so this is i this is j so whether they are same or not so they are not same i is 1 j is 2 what to do like which pointer to move can you tell me what you can see here is that j is larger that is equal to 2 and i is smaller that is equal to one now moving my smaller pointer like the value that is smaller to the larger value will actually get a probability to like they can become same but if i move the larger one obviously this is a smaller one if i move my j to the next element it is obviously that i have sorted it out because there is a sorted i have sorted in the initial part if i move my j to the next element it is obvious that the next element will be either equal or larger because it is sorted got it so if it is larger or equal they will never becomes equal to this i why because i is always smaller got it so it is always beneficial to move the element that is having a smaller value not the pointer the element that is the pointer point into should be having the smaller value that pointer should move to the next element got it so which means that i will move my i to the next value this i will move to the next value this will become i and voila as you can see both of them become two again so i will push again a two let us move the same pen two in this array okay that is what other intersection because now both of these elements matched out when both of these elements match out i will move both the pointers by one okay so i'll move both the pointers by one so this will come down to this point that is this i and this will come down to this point that is j and again both of them are same so i will again push two here now i again move both the pointers by one so as you can see now i has gone out of bound and j is still inside but because i have gone out of bound either one of the pointers go out to bound which means that there are no more elements to compare so i will just stop at this point now as you can see that the only difference the array intersection of the two problems in is in the one problem you have to print all the intersections irrespective whether they are unique or not so in the area two intersection you will print out this as the answer but in the array one intersection like the first problem you will have to print out only a unique numbers and for unique what you can do is that you can use a set so either inserting this intersection into a vector or an array you can insert both of them into a set when you insert both of them in a set only the unique ones will be stored out and so only one and two will be the answer for the first problem and in the second problem what you can do is instead of using a set you can directly insert them into an array so that all the occurrence or all the matchings will be stored out and that is that just the whole solution for both of the problems actually okay nothing more difficult or complicated so let us move down to the actual solution part let us see what is the solution so that you will become more familiar to two pointers so what i've done here is that i have first sorted out both the arrays using the sort function provided by the c plus stl and then find out the length of that then this is a set because in the first problem you have to only provide the unique instances so using a set then there are two pointers i and j i is upon the first array and j is up on the second array and both are initialized to zero because they both start from the zeroth index then i use a file loop so a while loop is only done till both of them are inbound as you can see both of them i is inbound that is i is less than n and j is less than m so both are inbound and if any of them goes out of bound i will stop this value got it so what i mean checking here if the current element the ith element the it's pointer value is larger i will move my jth pointer because that is smaller so like which means that if this is larger which means that j1 is smaller so whichever one is smaller i will move that similarly if the i1 is smaller i will move the i1 if the like if both of them are smaller they are equal then what i'll do i will push that equal element into the set instead of the vector because it's the first problem and move both i and j by 1. got it that's what i've explained if the any one is smaller i will move that but if the equal i will move both of them and also insert that element into the set and in the end because i want to return is it as a vector i will first iterate over this set all the elements stored in the set are unique i will just take all the elements stored in the set and push them into a vector and just print out the vector answer i hope you get the solution of the first problem let us move on second problem the whole problem is same nothing much different just you have to print out all the instances not the unique one so let us move down to the submissions directly so what you can see here is that uh in the submissions i use all of the same code i sorted them out using two pointers but instead of pushing them into a set now i'm pushing directly into the answer vector as you can see and just printing out the answer vector so that is the difference between the first problem and the second problem i hope you get the possible logic and the code for both of the problems if you still have routes you can mention now thank you for watching this video till this end i will see you next one till i keep coding and bye
Intersection of Two Arrays II
intersection-of-two-arrays-ii
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**. **Example 1:** **Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\] **Output:** \[2,2\] **Example 2:** **Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\] **Output:** \[4,9\] **Explanation:** \[9,4\] is also accepted. **Constraints:** * `1 <= nums1.length, nums2.length <= 1000` * `0 <= nums1[i], nums2[i] <= 1000` **Follow up:** * What if the given array is already sorted? How would you optimize your algorithm? * What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better? * What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
null
Array,Hash Table,Two Pointers,Binary Search,Sorting
Easy
349,1044,1392,2282
283
Hi guys hello welcome to the channel I am doing 90 days software engineering prep this is question 10 lead code 75 overall question lead code 283 move zeroes ok so before I start the question I would request you that Generalize your progress with me. I keep a daily journal on another channel to see what is going on and what is not going on. You should also be aware of what I am doing these days and what I want to do. Okay, so am I. You will get to know how many people are preparing with me, so general, share your progress, whatever you want to share, you can post your comment there, now let's focus on the question, see what is this question is not quick sort. It means whatever algorithm will be used in it is a part of quick sort. Whenever you have to create two types of split in the array, elements of type one first and elements of type one later, anytime you want to do this split, type Elements of one type first, then elements of type two, then odd-even first, then elements of type two, then odd-even first, then elements of type two, then odd-even is split, zero is split of non-zero, if there is a is split, zero is split of non-zero, if there is a split of elements smaller and bigger than one element, then this strategy can be used. Listen again to the basic of the algorithm which is behind the algorithm. What is that? It segues the elements of type one and type two into an array. Type one all come first, all type two go later. That type one and type two can be anything. Odd or even can be zero. It can be non-zero Odd or even can be zero. It can be non-zero Odd or even can be zero. It can be non-zero or any given element is taken, which is called pivot, on one side smaller than that, on one side bigger than that, it can be anything. Okay, it is basic in the algorithm, it is used in quick sort, it is also used in quick select. See what it does, what it achieves, in this, like you have been given an array of 0 1 0 3 and 8, so as I say, you have to split zero and non-zero, split zero and non-zero, split zero and non-zero, bring non-zero forward, send zero backward, bring non-zero forward, send zero backward, bring non-zero forward, send zero backward, then type forward. It comes like non-zero is then type forward. It comes like non-zero is then type forward. It comes like non-zero is coming in front and that is going behind. Okay, so the relative order of the type that comes next remains preserved. Look, if there was t after th, then in the type that came next, 1 is 3 after t. And the order of the type that goes back may also change, meaning this row which was later may be zero here, and the row which was earlier may be gone later. Okay, so you Always remember that Type A, which comes first, its relative order is preserved. It is also good to remember this. Algorithm runs in The entire array is, we split the entire array, so this is an area from zero to j -1 to j my and j is j -1 to j my and j is j -1 to j my and j is sitting here then this is an area from sitting here j is sitting here then this is an area from j to i. Till -1 and then here j to i. Till -1 and then here j to i. Till -1 and then here it is sitting here and this is the next array which is an unknown array, so we know what happens in it. Let us assume that from 0 to -1, happens in it. Let us assume that from 0 to -1, happens in it. Let us assume that from 0 to -1, we have collected type A. Type B has been collected in j2 aa-1 and the place Type B has been collected in j2 aa-1 and the place Type B has been collected in j2 aa-1 and the place where aa is sitting is unknown. Such a situation usually happens that aa is sitting unknown on j to aa-1. sitting unknown on j to aa-1. sitting unknown on j to aa-1. Keep this in mind on j. The first element is of type B and till i-1 there are all type B and till i-1 there are all type B and till i-1 there are all type B elements. From row to j-1 there are all elements. From row to j-1 there are all elements. From row to j-1 there are all type A elements. Now the algorithm is very simple. Look, now above aa you will find type A elements. Element can also be found. Element of type B can also be found. If you want to find element of type B then what to do. If you want to find element of type B then it will be a simple task. Look carefully if it is an element of type B then just increase aa. If you have got an element of type B then just increase i then think about what will happen to you. Let us say that here you have got an element of type B then what will happen by just increasing i. Look carefully what will happen by increasing i. What will happen to you by increasing i? If you increase i, then your segment from j to i-1 has increased, which segment from j to i-1 has increased, which segment from j to i-1 has increased, which means that this segment has increased, the segment of type B has increased, if you have increased i, unknown elements have decreased and in fact, Where did the growth occur? If i increased then i-1 also increased, it automatically then i-1 also increased, it automatically then i-1 also increased, it automatically moved forward, that is, this area became bigger where all the type B elements were, if type A comes on i and a comes then what has to be done. First let's swap a and j. Let's swap i and j. Look carefully what has come on a. If the element with 'a' has come on 'a' then 'a' then all have to be collected further then element with 'a' has come on 'a' then 'a' then all have to be collected further then element with 'a' has come on 'a' then 'a' then all have to be collected further then what do we do? Remember j to j. But first b is lying on j, there is b type element, so let's swap aa and j. Now if we swap, then first b is lying on j, but first b is lying on j, so a went there and i came here. But now b has come, now increase both i and j, what will be the effect of this, what will happen if both a and j are increased, unknowns have reduced and if you look carefully, the area of ​​type A has and if you look carefully, the area of ​​type A has and if you look carefully, the area of ​​type A has increased, j has also increased. Neither did it increase from 0 to j -1, you are right and the type B -1, you are right and the type B -1, you are right and the type B element remained the same but that area moved forward. Maybe you have not understood this, now let me explain my point again with an example. Listen carefully, you will understand, it is very simple, I will revise it again so that you can understand, this is your complete array, I draw these elements in it and instead of type A and type B, I will call only A and B, I will call all A's. We have to collect all the B's and send them ahead. Okay, so we have processed some areas. We have processed some areas. Here all the A's have been gathered, so here all the B's have been gathered and my I is here, I and J. There are two pointers, my eye is here, this area is also unknown, I do n't know what is here, as soon as the eye reaches there, I will check whether I found A or B, then now in this situation, if this These are my A's, these are my seeds. In this situation, let me tell you where my A's and J's would be sitting. I is sitting above the first unknown. J is sitting above the first B. This area is called 0 to J. -1 This is the area of ​​a, is called 0 to J. -1 This is the area of ​​a, is called 0 to J. -1 This is the area of ​​a, what is the area of ​​b, what is the area of ​​b, what is the area of ​​b, j2 i -1 i -1 i is sitting on unknown, so now j2 i -1 i -1 i is sitting on unknown, so now j2 i -1 i -1 i is sitting on unknown, so now look carefully, I always have to maintain this while walking, do I have to maintain that in 0 to j -1 There should be A, this has to be maintained, in 0 to j -1 There should be A, this has to be maintained, in 0 to j -1 There should be A, this has to be maintained, j2 Aa-1 should have seeds, j2 Aa-1 should have seeds, j2 Aa-1 should have seeds, now you are detecting i, check the i, what are you getting here, only two things can happen, either you will get a or you will get b, now you will get b, then see. What will you do if you get b? What will you do? If you get b then you only know what to do. You have i+p. Now understand this. What happened to it. If you pushed i then i+p. Now understand this. What happened to it. If you pushed i then i+p. Now understand this. What happened to it. If you pushed i then what happened to you. Here you got b. You pushed i so see what else. Hu, this has reduced your unknown, you had got B, here you had got B, you made Aa Plus, then come from here, you have been erased and gone here, come here, gone here, now think about it and look at the area near you. Has it become bigger or not? Yes, if it has become so much, then your seed area has become bigger, your unknown area has reduced, earlier there were four unknown elements, now there are three elements and A area did not make any difference, it should not have made any difference because If you get a little bit of B then you have to push only i when you get b, but now if you get a here, then you know what happens, first i and h will be swapped and then both will increase. Understand its effect. What will happen is a is swapped first and what is swapped aa and j elements are swapped at j b occurs j occurs first at b 0 to j -1 j occurs first at b 0 to j -1 j occurs first at b 0 to j -1 a occurs j to i -1 a occurs b then b occurs a occurs j to i -1 a occurs b then b occurs a occurs j to i -1 a occurs b then b occurs ok so When you have swapped i and j, right on i, then the condition is that you have got this, only then we activated the algorithm swap i+p j+p algorithm swap i+p j+p algorithm swap i+p j+p and j, the first one is b, so b will come here and b will come here. a Now after this you have done both i+p and j+p, you have done both i+p and j+p, you have done both i+p and j+p, understand what will happen from that, what will happen with i+p and j+ aa has understand what will happen from that, what will happen with i+p and j+ aa has understand what will happen from that, what will happen with i+p and j+ aa has reached here, j has done pps, j has reached here ok, know its overall impact, what is yours? i प means unknown elements have reduced which is true now there are only two unknown elements earlier there were three which you did i + प why did you do j + प you did i + प why did you do j + प because j first resides at b and due to swapping there is a If you look carefully, it should have happened, why should it have happened, because zero to j is minus a, then you get a If you have got an extra A, then the area from G to J should become bigger, so A and J have increased. If J has increased, J Mive has also increased, then the area from 0 to J has become bigger. If that area has become bigger, then you have an extra A. And if you think very carefully, then you will be able to understand that the seed area has only shifted forward, why has it only shifted forward? Look, look, if both Aa and J have increased, then where did it start from? Where did it end from i-1, if a and h both increased then the from i-1, if a and h both increased then the from i-1, if a and h both increased then the size of the area did not change, it just shifted a little further, it will start from one ahead and end one ahead and ch is actually ok, so we sent this one b here. Gave and this one A was sent here, then the A area grew and the B area, because from here it ended and there was extra in front, then one less from the back and moved forward, then the B area shifted and the A area The area has increased and the uncertainty has reduced. The area with uncertainty means from the shoe eye to the end has reduced. Okay, so this can be used for any type of slit, so I will show you the code for this. Code with me. You will see it is a very simple code, the work continues till then, remember this phase, 0 to J in this case zero non-zero has to be split, this case zero non-zero has to be split, this case zero non-zero has to be split, in the beginning we need non-zero, apne ko will in the beginning we need non-zero, apne ko will in the beginning we need non-zero, apne ko will remain non-zero, okay J2 aa will remain zero in the second remain non-zero, okay J2 aa will remain zero in the second remain non-zero, okay J2 aa will remain zero in the second and from Everything will be unknown in the beginning, that's why it is sitting at zero, so 0 is not defined and even 0 is not defined, everything is unknown. No, because a is sitting at zero, so from a to the end, it is unknown, so everything is unknown in the beginning, so it means 0 to j-1 should not be defined, means 0 to j-1 should not be defined, means 0 to j-1 should not be defined, non-zero should not be defined, so yes, non-zero should not be defined, so yes, non-zero should not be defined, so yes, j-1 is - 1 0 to -1 This is not formed j-1 is - 1 0 to -1 This is not formed j-1 is - 1 0 to -1 This is not formed j to aa -1 j is 0 and i-1 is -1 so 0 t -1 If the to aa -1 j is 0 and i-1 is -1 so 0 t -1 If the to aa -1 j is 0 and i-1 is -1 so 0 t -1 If the second area is also not formed then the remaining two areas are also not there and aa to end is the same area. So now what will I check, I will check the names of a's every time, what did I get a zero or a non-zero, if I get, did I get a zero or a non-zero, if I get, did I get a zero or a non-zero, if I get a zero, then zeros are coming later, so it will be simple, if I get a non-zero, then first. Swap will be swap get a non-zero, then first. Swap will be swap get a non-zero, then first. Swap will be swap equal to I want to swap my tp equal to nums of a put in nums of j and nums of This time I will make you go through it, now I will make you go through it according to zero and non- you go through it, now I will make you go through it according to zero and non- you go through it, now I will make you go through it according to zero and non- zero, without thinking about other things, watch the simple algorithm go through, forgetting the rest of the area, like one is t is f is zero is 8 is zero. Isn't it from, so this is 58, put one more zero, okay, this is 58 97, it should come in front, zero should go behind, so look at the beginning, A is kept the same and J is also kept the same, non-zero is kept the same and J is also kept the same, non-zero is kept the same and J is also kept the same, non-zero is non-zero, non-zero. If both of them non-zero, non-zero. If both of them non-zero, non-zero. If both of them increase by swapping, then both of them have increased on their own. If nothing will happen by swapping on their own, then here you will not even understand because it is not that area, you will see them separately. If both have increased, then both are non-zero again. Then come. increased, then both are non-zero again. Then come. increased, then both are non-zero again. Then come. Swapped with means nothing happened and both are increased i here j is here again non zero then i and j are swapped with each other no effect will come and if both are increased then i has reached here j has reached here ok If it is zero for the first time, then i alone increased. If i alone increased, then now you should understand. Now you will see whether what we are carrying is happening or not. So look carefully, you can see the areas. Look 0 to j -1 are all non see the areas. Look 0 to j -1 are all non see the areas. Look 0 to j -1 are all non zeros yes j to i -1 are there zeros yes j to i -1 are there zeros yes j to i -1 are there zeros yes ok now here comes non zero what happens in non zero if both increase after getting swapped then there will be swap here at here comes this zero So see, the non-zero was gathered at the back, the zero moved forward zero So see, the non-zero was gathered at the back, the zero moved forward zero So see, the non-zero was gathered at the back, the zero moved forward and after that both increase, both aa and j increase, this aa went here, j became here, this time I will not analyze the region, it will be some time later. I will do zero, aa will increase alone, okay now if you look carefully again, let me draw your segment, look carefully, you see this, 0 to j -1, look carefully, you see this, 0 to j -1, look carefully, you see this, 0 to j -1, you are seeing non-zero, I am seeing 1 you are seeing non-zero, I am seeing 1 you are seeing non-zero, I am seeing 1 58 and j2 aa -1. You are seeing zeros, I am 58 and j2 aa -1. You are seeing zeros, I am 58 and j2 aa -1. You are seeing zeros, I am seeing them, now nine has come, so there will be a swap, with whom will it be swapped, if I and J are swapped with J, then first this nine will be swapped with the zero, then the non-zeros nine will be swapped with the zero, then the non-zeros nine will be swapped with the zero, then the non-zeros got together and the zeros were here and now. Here zeros have gone, two zeros remained but moved forward and non- zeros have gone, two zeros remained but moved forward and non- zeros have gone, two zeros remained but moved forward and non- zeros gathered behind, so after that both i and j increase, now if both i and j increase then what will happen, this is the area of ​​io, this is the increase then what will happen, this is the area of ​​io, this is the increase then what will happen, this is the area of ​​io, this is the area of ​​j and now aa is area of ​​j and now aa is area of ​​j and now aa is first. V is in the undefined area and J always increases to zero first. Now again it will be clear, so seven here, zero here and both J and I will increase. Okay, so now I will process the last one, only then I will show you this. If you get zero, then it will come alone and will increase. If you come alone, it will increase. So whatever it was, I thought we were here together, then J was sitting here I was sitting here, now I have reached the end, the game is over, this 0 to J -1 is game is over, this 0 to J -1 is game is over, this 0 to J -1 is your non There are zeros, yes g 1 2 5 8 9 7 and j2 aa -1 aa has reached the end then j t aa j2 aa -1 aa has reached the end then j t aa j2 aa -1 aa has reached the end then j t aa -1 you have three zeros so your work is done -1 you have three zeros so your work is done -1 you have three zeros so your work is done so this is the algorithm and this algorithm is very important because This becomes a part of quick sort and if you want to split any type then this can be used. Keep in mind that the order of the type that comes next remains the same. The order of the other type can also change. Talking about fear, like If we get shocked by this then fear will always remain. I hope you enjoyed the question. Good question.
Move Zeroes
move-zeroes
Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. **Note** that you must do this in-place without making a copy of the array. **Example 1:** **Input:** nums = \[0,1,0,3,12\] **Output:** \[1,3,12,0,0\] **Example 2:** **Input:** nums = \[0\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 104` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Could you minimize the total number of operations done?
In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.
Array,Two Pointers
Easy
27
1,720
Hello viewers welcome to you quotes on in this video will be looking at the New Delhi to Swayam Record accept what are the a quadrilateral that is a problem statement piece rate of this software's one and interior and good show hotspot were given and the are endowed 120 300 first the first Slovenian to find the original urgent need to find the original are from which are in court was created pound and 1000 operations me on Monday andaz and operation not aware of great distance quotare switch to find this original and element first hair is The first element of soil 100 ki and select state other values ​​of rs ki and select state other values ​​of rs ki and select state other values ​​of rs loot if balance xy z soft and latest look at the answer operation understanding and operation death roots that plant is one to respect loot representation in wave in have another interior 6000 i so Only Beta Different In Different Size Different Pimple Give Me The Value Vansh Beat Same Like Share One Will Give Me The Value From 0a [ Share One Will Give Me The Value From 0a [ Share One Will Give Me The Value From 0a 0508 Will Give Me Two Different Roadways And Operation In The God Are That Nci I Have One Two Three Sides 08000120 Actor Will Give One That I Once Action Wider Will Get 200 Oye Give Will Give Me Two Same For Boys And Results Will Give Me 3S So In General Icon Writer Yaar Of That I Will 600 Cleanliness I One thing and actions will give me the value of and code of it so now he register latest important points your Hair a date in words turn off Off Soon for the Joe President watch and share this statement from 087 is so called the value of Eggs And Latest And You Can Destroy Example Will Satisfy And Sports Puberty Variables That Avnish 706 200 Maine Duniyaan 1600 Value One Should Reduce 6000 1510 154 Is Graduation In This Situation Different One Dead To Back Side Effect Hindi Stupid Exams 7 And Similar For 7206 Show And They Can See But Enough 1608 Search Listen Latest Produced Questions and Quotes for this Question Speed ​​Simple Quotes for this Question Speed ​​Simple Quotes for this Question Speed ​​Simple First of All They Need to Retail Investors Will Just a Quarter of Interior So Please Request Rohini Zodiac and Villages in Sardi Value First Interview After Snow Mein Novel Just Look At rupees inko dare ki Bigg Boss bluetooth and codes are Ajay ko for bill gates a ki raipur to value in access encoded rumors eggs and a view of i ki anna ho will just book the value of x flashlights now in this step jay Hind step wears insulting value of And Snacks and Uribe Subscribe Button and
Decode XORed Array
crawler-log-folder
There is a **hidden** integer array `arr` that consists of `n` non-negative integers. It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`. You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`. Return _the original array_ `arr`. It can be proved that the answer exists and is unique. **Example 1:** **Input:** encoded = \[1,2,3\], first = 1 **Output:** \[1,0,2,1\] **Explanation:** If arr = \[1,0,2,1\], then first = 1 and encoded = \[1 XOR 0, 0 XOR 2, 2 XOR 1\] = \[1,2,3\] **Example 2:** **Input:** encoded = \[6,2,7,3\], first = 4 **Output:** \[4,2,0,7,4\] **Constraints:** * `2 <= n <= 104` * `encoded.length == n - 1` * `0 <= encoded[i] <= 105` * `0 <= first <= 105`
Simulate the process but don’t move the pointer beyond the main folder. Simulate the process but don’t move the pointer beyond the main folder.
Array,String,Stack
Easy
682,874
326
foreign with the lonely Dash and today we're going over leap code question number 326 power of three which states given an integer n returned true if it is a power of 3 otherwise return false an integer N is a power of three if there exists an integer X such that n equals 3 to the X so what does this mean well it just means that we need to figure out whether N is a power of three that's not the most complicated thing in the world um and the way we're going to solve this um is well there's a couple of different ways we can solve this in fact though I think maybe for this video we will solve it in two different ways so how are we going to do this well let's take a look down here to an iterative approach um so first and foremost when we're thinking about what n is going to be because 3 is going to be 2A power um n is always going to be positive right so it's always going to be positive so let's say they give us the number 13 we need to figure out if 13 can be a power of 3 which we know it's not right because 3 to the first power is three to the second power is nine three to the third power is 27 so there's no integer that will come along where we will reach 13 right so if we take 13 we divide it by 3 we end up with 4.3 and because this is not a whole 4.3 and because this is not a whole 4.3 and because this is not a whole number then we also know it can't possibly n 13 cannot possibly be a power of three I think even the example they give us on the website it says what if n is 27 well we know 27 divided by 3 is 9 divided by 3 is 3 divided by 3 is 1 and because we got to 1 we know that um that 27 or N is a power of 3 it is in fact 3 to the third kind of looks interesting there so uh in order to solve this iterative approach this is all we're going to do we're going to divide n by 3 and if it comes out as a whole number then we're just going to keep dividing until it gets to 1. if it's one then we're going to return true if it's not a one then we're going to return false so that's the first approach that we're going to do it's pretty simple and straightforward the this is all of the iterative iterations we're going to need in order to solve it but there is an even easier way of doing it and we're going to talk about the mathematical approach now if we get a little bit more into computer systems we know that the largest 32-bit integer know that the largest 32-bit integer know that the largest 32-bit integer that we can process is oh look at this I must have left out some left out a number or something like that it's something I got to look up this number it's 2 million oh yeah it's 2 million 147 483 yes that's right is this big old number which um the closest number without going over that is a what do you call this thing a oh my gosh I can't even remember a power of three thank you the word power just flew out of my head is a power three is three to the 19th right because 3 to the 20th is larger than this number so we give us a bad answer but 3 to the 19th is below this number now all we have to do is take that big old number and determine that if we divide it by n that there is no remainder then it is a power of three so this is the most simple way of doing it but a lot of people don't think about uh 32-bit integers being think about uh 32-bit integers being think about uh 32-bit integers being this way to work so that's why we're going to do this in two ways we're going to do this iteratively first and then we're going to solve it in the mathematical way which is just taking the modulo of the largest value uh that is a power of three and determining if it's zero so let's take a look at any of the constraints and see if there's any other edge cases that we're going to have to consider for either of these approaches and look at that all the constraints say is that it's going to be an integer n that is within the 32-bit stream so uh that is within the 32-bit stream so uh that is within the 32-bit stream so uh nope there is absolutely nothing to consider for our edge cases we can just move on to writing I guess two sets of pseudocode okay so for our pseudocode we're going to do two different ways of solving this problem so the first one is the iterative uh solution of the approach and the second one is the mathematical approach so the first iterative one right so this is going step by step the first thing we need to know is that n always has to be greater than zero so that's we're just going to do this iteration while n is greater than zero what are we doing while n is greater than zero well if n divided by three is a whole number right so basically if we keep dividing over and over again and it's a whole number that means it's possible that it is a power of three so if n divided by 3 is a whole number what do we do um what are we doing we're saying n now equals n divided by three we're reassigning the value of n so I'm going to write that in then re-assign the to write that in then re-assign the to write that in then re-assign the value of n to n equals n divided by three done pretty simple uh otherwise if n divided by 3 is not a whole number what do we do well we're just going to break out of the loop because we know at that point that um that it's not and I guess you could say return false because we know it's not going to be a power of 3 but we're not going to do that in this case just because I want to build this slightly differently then once that Loop is broken we can ask ourselves if n is equal to 1 right and we're going back to where we were talking about once it gets down to one here then we know it's a power of three so if n is now equal to one then return true if n is not equal to 1 then return false and then we're done so that is the entire iterative uh way of solving this problem I don't think it's all that confusing but it's pretty simple the mathematical one is even more simple right the first thing we need to figure out is the same thing if n is less than zero we're going to return false because remember it has to be a positive integer the next one is if 3 to the 19th power divided by n is a whole number then we're going to say yep it is something that is 3 to that whole number will equal n then we can just return true on the converse if 3 to the 19th power divided by n is not a whole number what do we do while we return false so those are the two ways of solving this problem let's copy them let's paste them into our work area and let's get coding and here we are working in the Java Works section of the lead code website and we're going to start with the iterative approach that we just talked about here so the first thing is while n is greater than zero so that's a while loop here so while n is greater than zero what are we going to do well we need to evaluate if n divided by 3 is a whole number and for the US the easiest way to do that is if n modulo 3 is equal to zero right because this is basically saying hey if we divide n by 3 and there's no remainder then we know that it is uh that then n divided by 3 is a whole number so that's all that is if that's the case then we need to reassign the value of n so that it equals n divided by 3. so n is equal to n divided by three uh otherwise so if n modulo 3 does not equal zero that's going to be an else statement what do we do well we're just going to break out of the loop and that's what we do here and that's taking care of most of this section of the iterative approach then we need to make a determination if n is equal to 1 because if that's the case we can just return true so there's that there's our spot so we're outside of our while loop so if in this case n is equal to one what do we do well we just return true else meaning that n is not equal to one if it's not equal to one then we're just going to return false and that is all of the code we need for our iterative approach let's hit run make sure I didn't make any mistakes as I sometimes leave out punctuation and it runs pretty quick if we submit it we can do a comparison nope as I hit my desk sorry if that was really loud and the comparison is pretty good we've got 97 runtime and 61 percent in memory so this is just the first way to approach this question that we had talked about so instead um we can try something completely different and we can try our mathematical approach so I'm going to let's see I'm going to comment out all oh you know what I'm going to do it the faster way I'm going to comment out the code that we've already written here and then we can try there we go we can try our mathematical approach instead so how are we going to do the mathematical approach well we can decide if n is less than zero we can return false so let's go over again you know what I think I might have made a bit of a mistake here so if in our case n is less than and I should be equal to zero right if n is less than or equal to zero then we're going to return ah let me fix this here less than or equal to zero we are going to return false okay so that sets us up first then we can say hey if uh 3 to the 19th power divided by n is a whole number we can return true so that is if n uh sorry 3 to the 19th power modulo n is equal to zero then we can return true otherwise that's just our else statement if that's not the case then we're going to return false and that's all of the code that we need for our mathematical uh solution I'm going to hit run to make sure I didn't make any mistakes there of course I made a mistake uh illegal start to an expression if three oh you know why I'm still thinking in Python world uh of course we can't just do threes in the 19th power this is Java so in that case we're gonna have to use math dot power is 3 to the 19th power okay uh let's see if that works a little bit better gotta remember what uh what language I'm typing in here there it is run time is zero milliseconds so I'm just going to hit submit and see how we're doing here um against all the other cases well it does not look very good uh but you know what I'm going to fix this a little bit more okay I'm just going to make it a single return statement um and in that case we're just going to ask it to return something and what are we going to ask it to return well we're going to ask it to return whether n is greater than zero right so that's the same as uh if n is less than or equal to zero so if n is greater than zero 0 and we have math dot power three to the 19th power modulo n is equal to zero right so if the opposite of this happens and then this also happens then we will have our answer so that's our one answer or one line answer let's see how we do there of course I left off the punctuation this video isn't going well bam let's try it again should work there I'm going to hit submit that answer and we should know that it is about the same slow run time slow memory so it kind of depends on what your preference is if you like shorter code this answer using mathematics is pretty darn small it's may not be the fastest and the fastest is most likely the iterative way that we have highlighted here so if you're looking for two great ways of solving lead code question 326 power of three here is our iterative approach and here is our mathematical approach thank you
Power of Three
power-of-three
Given an integer `n`, return _`true` if it is a power of three. Otherwise, return `false`_. An integer `n` is a power of three, if there exists an integer `x` such that `n == 3x`. **Example 1:** **Input:** n = 27 **Output:** true **Explanation:** 27 = 33 **Example 2:** **Input:** n = 0 **Output:** false **Explanation:** There is no x where 3x = 0. **Example 3:** **Input:** n = -1 **Output:** false **Explanation:** There is no x where 3x = (-1). **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Recursion
Easy
231,342,1889
167
hey guys Greg here and let's solve two sum 2 where the input array is sorted it's a really interesting problem I like it a lot so we're given a one index array of integers numbers doesn't really change anything it's just the way that they're expressing it in the problem that is already sorted in non-decreasing that is already sorted in non-decreasing that is already sorted in non-decreasing order non- decreasing basically just order non- decreasing basically just order non- decreasing basically just means increasing but there might be duplicates so we'll find two numbers such that they add up to a specific Target number okay same as two sum and so basically we need to return the indices of the two numbers index one and index 2 and since they're doing one index you add one here you just need to find the two numbers that sum up to the Target and return their indices added by one the tests are generated such that there is exactly one solution so you don't need to worry about the case where there's you know no two numbers that sum to the solution but this time we must use only constant extra space okay if you remember how the normal two sum works and they actually have the same example here what you would do is you would use a hashmap where you make the key be the number and the value be the index so that you can kind of look up the number that you're looking for however you can't do that here because you must use constant space okay you can only just have you know some pointers some indices or whatever and so how does this work well this only works and it's only possible because the numbers are sorted here now the brute force method that's going to be o of n^2 time is that's going to be o of n^2 time is that's going to be o of n^2 time is actually going to be a constant space solution so you could look at all the different pairs we'd have I starting at here J over here and we could move j through so we'd have a total of six that's not right 11 not right we could have 12 nope 16 nope 26 that did not work you would set I to be over here and you would start J here and you'd say Okay 15 that doesn't work 16 nope 20 nope 30 nope so then here you'd start to find it we have I is right here J is here and immediately you would find these two and so that is actually a constant space solution however o of n^2 constant space solution however o of n^2 constant space solution however o of n^2 runtime is really slow and so you're not going to use that now when the problem says something about it being sorted and we don't do anything with it being sorted you know we're probably not being optimal here so how do we use this sorted well it's actually by using a two-pointer technique okay so by using a two-pointer technique okay so by using a two-pointer technique okay so we set L over here L at the beginning and are at the end okay so we're calling this a twop pointer technique if you have it like this they're usually going to go in towards each other now what are we looking for we want two numbers that sum to 21 well we have a number one we have our other number 25 we could get their sum and that's 26 now this sum is wrong but it's not just wrong it is specifically too big what is the only way to make this better okay well if we move L forward we know that the numbers are increasing or at least they might be increasing they're never decreasing so if we move L forward we know beforehand we know that's not going to help that's going to make a bigger sum but we need our sum to be smaller we need to get our sum closer to 21 so what do we do okay well to make the sum smaller well we're going to move R over okay so that 25 turns into 15 and we say okay well nope it's still wrong except now it's wrong in a different way 16 is too small we need a bigger sum how do we make it bigger well it's sorted in increasing order we'd move this over and so one turns into a five and so this is 20 okay we're getting really close now our sum is still too small it's still smaller than 21 so what do we move L forward again try to make it bigger nope now it's too big at this point we need our sum to be smaller how do we do that well we move R over of 21 okay so we found it and remember as part of the problem we're guaranteed to find it so we finally found it we' return these two we finally found it we' return these two we finally found it we' return these two indices which are going to be since we're calling it one indexed we would return three and four in this case now the time complexity of this is going to be Big O of n because we're really just moving once through the array over here we're moving once through the array over here and so that's just going to be Big O of N and the space complexity of this well we're just using two pointers we have L at the beginning r at the end they move over we you know calculate a sum that's just one variable and so that space complexity will be o of one so we can code this okay so for this we get n is the length of the numbers that we have so that we can get our position L at the beginning L is equal to Z and our other pointer r at n minus one yes I'm calling them pointers no we're not using C they're really just indices but that's the terminology L is 0 R is n minus one and we do hey while L is less than R you could technically do this permanently because you know we're actually guaranteed that there's going to be a solution so we don't have to worry about kind of breaking out of this and not finding it but something that makes a lot of sense is like you know you do this while L is less than R anyway and so we'd get our current sum that we have that's equal to Simply numbers at L Plus numbers at R then if the sum is equal to the Target we can immediately return our answer we found it and so we'd return L and R except because of this annoying one index thing I don't know why they did that but you should return L + one did that but you should return L + one did that but you should return L + one and r + one so if we found it that's and r + one so if we found it that's and r + one so if we found it that's great we will find it eventually but if not well otherwise is the sum less than the target okay if our sum is smaller than the Target that means we need to make our sum bigger how do we make our sum bigger we move L forward cuz they're sorted in increasing order if the sum is not equal to the Target and it's not less than the target then it must be that the sum is bigger than the target if the sum is too big we need to make the sum smaller how do we make it smaller we bring R down by one and again since we're actually guaranteed exactly one solution we can actually just run and submit this right away and again the time complexity of this is going to be Big O of N and the space complexity as is required in the question is going to be constant we just have n l and R and we get a sum at some point it's definitely constant space all right so that's it I hope that was helpful guys drop a like if it was and have a great day bye-bye
Two Sum II - Input Array Is Sorted
two-sum-ii-input-array-is-sorted
Given a **1-indexed** array of integers `numbers` that is already **_sorted in non-decreasing order_**, find two numbers such that they add up to a specific `target` number. Let these two numbers be `numbers[index1]` and `numbers[index2]` where `1 <= index1 < index2 <= numbers.length`. Return _the indices of the two numbers,_ `index1` _and_ `index2`_, **added by one** as an integer array_ `[index1, index2]` _of length 2._ The tests are generated such that there is **exactly one solution**. You **may not** use the same element twice. Your solution must use only constant extra space. **Example 1:** **Input:** numbers = \[2,7,11,15\], target = 9 **Output:** \[1,2\] **Explanation:** The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return \[1, 2\]. **Example 2:** **Input:** numbers = \[2,3,4\], target = 6 **Output:** \[1,3\] **Explanation:** The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return \[1, 3\]. **Example 3:** **Input:** numbers = \[\-1,0\], target = -1 **Output:** \[1,2\] **Explanation:** The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return \[1, 2\]. **Constraints:** * `2 <= numbers.length <= 3 * 104` * `-1000 <= numbers[i] <= 1000` * `numbers` is sorted in **non-decreasing order**. * `-1000 <= target <= 1000` * The tests are generated such that there is **exactly one solution**.
null
Array,Two Pointers,Binary Search
Medium
1,653,1083
118
hey what's up guys so let's solve this pascal triangle so personal triangle i think everybody learns in the junior high school so one two one uh one two three one four uh six four one so it's very simple that's given an array right the next array will be uh each element will be sum of the previous uh row right so three plus three six one plus three is a four yeah i think everyone no what hell is going on okay and you need to return this one so five one two one four six four one okay so very simple that you just get you just uh start from one and get one so i think uh for a previous two you can just remember it okay so if the number is one you return the first if the number rows two you're just returning right so this is the base case yeah this i mean you can start from the first one right but i think it's very simple that you just i just code the first two okay so now i minus two because uh i need to produce the rest three okay and i take the first one i take s to be one and i p to be n zero minus one okay so let me just explain what hell is going on okay so for example uh let's say on this let's say three okay uh maybe i'll take these all right so i take the answer this is n zero minus one suppose i want to produce another line and i for j range then p minus one i define s to be append p j plus p z plus one okay so this means that uh this one will give me uh sorry will give me two because these one plus one and they'll give me one and i pin one okay and then for the second line it will produce uh these two will produce three oh sorry uh yes three and the final one will get the one okay and i append one and the one three one uh i so will give me four six four and at least give me one and i add one so basically you just start from pj and pj plus one will give you a row and then you append the first one right you get one and you gotta pin one yeah so and then answer pin s and then just return it okay so this is the step that's just uh you can just write on the board or on a paper so that you understand what is the step okay and let's go through and answer is uh so pascal yeah okay yeah so this is the answer uh see you guys next video
Pascal's Triangle
pascals-triangle
Given an integer `numRows`, return the first numRows of **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** numRows = 5 **Output:** \[\[1\],\[1,1\],\[1,2,1\],\[1,3,3,1\],\[1,4,6,4,1\]\] **Example 2:** **Input:** numRows = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= numRows <= 30`
null
Array,Dynamic Programming
Easy
119
1,799
foreign this is me doing day 14 of the legal daily challenge hit the like button hit the Subscribe button join me on Discord uh totally clicked on it let me know what you think about today's vlog so what did I click on also as you can see my internet is very slow I don't even know how what happened but uh yeah clicking and clicking anyway so as you can see I'm still in Greece uh I hopefully you saw the Drone video then you know that's exciting and stuff why there you go uh yeah I'm having a lot of fun here a couple of days more so yeah let's look at today's prom uh oh before that uh if you enjoyed that follow my Instagram uh the handle is downstairs somewhere uh you find the link on description um yeah try to support if you like especially if you like pretty pictures and travel and stuff like that um it would be uh I would be uh you know it's kind of like an ad but it's also like I'm upselling you from this thing that doesn't make money lead code to another thing that I also don't make money from Instagram is just a hobby of mine so it feels you know just traveling and stuff anyway okay let's take a look at today's program 1799 maximum score after an operation so you're giving nums in a way of positive engines two times and you must perform an Aboriginal in this way choose to number X and Y receive a score of I times what's I oh the if operation remove X and Y L kind okay so basically you have to pair two times n and the first thing I'm going to do is just look at oh okay well that just makes a dumb okay I was like trying to think about I don't know different properties of gcd or things just thinking about it but given that n is less than 7 or 14 I suppose or the length is up to 14 and this um the way that you want to do this is a bit if it wise fit masks is what I try to say sorry um yeah I try to use fit masks and I did get a bit mask I'm going to do it very brief overview I am still in Greece time and um I haven't slept well to be honest so I'm a little bit tired and I'm trying to do a virtual contest after this so uh yeah but basically the idea behind a bit bitmap is that okay so to think that you're trying to cash is a is in a way of in this case 14 elements right uh up to 14 anyway so it could be Force true and basically the idea is that you have just used away say like keeping track of the numbers that we've used so you know it looks something like this right and instead of so the idea of a bit mask is that instead of using this we convert this into a numbers away say so force is equal to zero true is equal to one and then you have something like this right and then the next step from that is converting this number it but like oh it's zeros and one so it's just a binary number right so then now you just convert this to you know uh let's just say this is uh one two four eight sixteen thirty-two so then this is just sixteen thirty-two so then this is just sixteen thirty-two so then this is just of course a binary number thing of two plus eight plus sixteen right so that's basically the idea behind a bin mask I'm not going to get it and every other operation that we're going to do with bitmask is just about flipping excuse me I'm not going to do it too deeply but it's just about changing this from Force to true or true to force or checking that the element is for so true or whatever so that's basically bit mask I know it's very short and maybe you need to learn a little bit more if you haven't done it before but at a high level concept like if you wanted to really learn it that's really all that's uh you know that's all that it does it's a fancy way of doing this because it's just more memory efficient but that's pretty much it okay so then now uh we can do I don't know I call it calculate because I'm lazy uh so we have a big mask of the numbers that we've seen and then kind of I right I being the I think that they tell you right there's a little bit of a weirdness here that I'll go into in a second um but yeah all right yeah hopefully I do remember it but yeah but basically now all we have to do is take any two numbers and just uh yeah just take any two numbers and then see if we need to do it right so basically the idea is that for kind of what we want to do is write X and nums but we just want to get the index of it so maybe I call it um X I for X index in range of n for y i in range of n uh here because of symmetry reasons we can actually start from x i plus one right because gcd of x Y is equal to G Series Y and X right so that's basically the idea um yeah that's basically the idea and then the score so let's just say we have a best score right for now and then the best score is just to go to the Max and this is standard dynamic programming or recursive things or greedy things in general which is that now that we know that this is best we it calculate uh I kind of skipped a few steps so we have to make sure that XI is not used so the way that we did that is if this is you go to zero then we can use it right as we said this is basically equivalent to say if used of x i or if not used of x i something like this way if you want to use uh away notations same thing but with X Y oops and then now we calculate uh well to get the score first right well maybe not doesn't matter we took down this mask and one to the x i want the Yi right just basically the or because we know that these are force in The Mask because by when we check the or The Midwives or just flips it to yes and then now uh and then we have to add the thing which is I times gcd of uh nums of x i num sub y i right pretty much it uh I mean I forgot the I plus one so because we have to increase I every time but that's pretty much it we return best and then we're happy for the most part right so we calculate zero being if you set everything to false to begin with uh and I is just one I think right you start with one doesn't matter as long as it's symmetric right so it should be okay so yeah but that's coming up next it's okay so that there's a lot of overlapping sub problems so we want to uh we want to memorize right to think that is funky about this one funny about this one is that uh let's analyze this thing right so Mass can go from zero to two to the end minus one uh the reason why this is that you can kind of think about it as if n is equal to say 10 you can just think about it starting as uh 10 uh all the way to do right 10 zeros and 10 ones and everything in between so that's going to be 2 to the 10. for this n uh minus one right it's the big and then I can go from zero to N I think or maybe n plus one but you know o of n anyway right um but the thing so you may be very tempted to say and this takes n Square inside so you may you so and each um each core each input takes o of N squared roughly speaking so then you may be time to say oh then this is just we have all of n times to the N inputs so Toto is O of n cubed times to the N right but one thing that you should notice is that I is a totally dependent variable on mask right what I mean by that is that for example if mask is say zero one I don't know I'm being lazy so actually just uh this way then I the next I has to be two right why because we already used one of the eyes on this right and every time so basically I is equal two number of ones divided by two plus one or something like this right um and maybe I'll buy one but the idea is that every time you increment I two more things a mask uh has a one right so that's basically the idea so this I is a totally dependent variable and mask so therefore we can actually eliminate it the reason why we kind of keep track here it's just that it's easier to do the math like this uh nothing tricky about it otherwise you can do something like I is equal to Big count of mask over two plus one or something like that it'll be exactly the same right um that's basically the idea and therefore the re the next thing that we want to say is that uh yeah the reason why uh we say this is that now we can say it has cash a mask then we return mask and you know notice that we do not even need to use iron just at all so that's basically the idea and now we can run it again with the caching did I mess up the caching that is weird right foreign that's just a silly typo I was like you can't really mess up that caching right well except for we have to do typos right so okay so yeah uh looks good let's go submit hopefully I don't have any silly other mistakes and yeah it looks good and yeah 11 39 day streak and that's all I have with this one let me know what you think uh yeah and the complexity is actually going to be and square times till the end time and all of two to the end space um cool that's what I have with this one let me know what you think and yeah stay good stay healthy to come into Health I'll see you later take care bye
Maximize Score After N Operations
minimum-incompatibility
You are given `nums`, an array of positive integers of size `2 * n`. You must perform `n` operations on this array. In the `ith` operation **(1-indexed)**, you will: * Choose two elements, `x` and `y`. * Receive a score of `i * gcd(x, y)`. * Remove `x` and `y` from `nums`. Return _the maximum score you can receive after performing_ `n` _operations._ The function `gcd(x, y)` is the greatest common divisor of `x` and `y`. **Example 1:** **Input:** nums = \[1,2\] **Output:** 1 **Explanation:** The optimal choice of operations is: (1 \* gcd(1, 2)) = 1 **Example 2:** **Input:** nums = \[3,4,6,8\] **Output:** 11 **Explanation:** The optimal choice of operations is: (1 \* gcd(3, 6)) + (2 \* gcd(4, 8)) = 3 + 8 = 11 **Example 3:** **Input:** nums = \[1,2,3,4,5,6\] **Output:** 14 **Explanation:** The optimal choice of operations is: (1 \* gcd(1, 5)) + (2 \* gcd(2, 4)) + (3 \* gcd(3, 6)) = 1 + 4 + 9 = 14 **Constraints:** * `1 <= n <= 7` * `nums.length == 2 * n` * `1 <= nums[i] <= 106`
The constraints are small enough for a backtrack solution but not any backtrack solution If we use a naive n^k don't you think it can be optimized
Array,Dynamic Programming,Bit Manipulation,Bitmask
Hard
null
1,481
welcome back to my channel today's lead code DCC question is least number of unique integers after K removal problem statement says given an array of integers ARR and an integer K find the least number of unique integers after removing exactly K elements the problem statement says so we will be given an array of integers and a value K so what we have to do we have to remove key elements from this array any key elements from this array and after removing it we have to calculate the number of distinct elements from the remaining elements distinct elements and our task is to minimize this number of distinct elements so given an example five 5 4 and K = to five 5 4 and K = to five 5 4 and K = to 1 if we remove five from this array so number of distinct elements will be two and in the same example if we remove four the number of distinct elements will be one so our answer will be one not two because we have to minimize the number of distinct elements after removing K elements so the answer for this example will be one so how we can approach this question so suppose take one more example suppose we have integer one i1 and we have one instances of i1 I2 and two instances of I2 I I3 and three instances of I3 now if I would ask you what will be the minimum value of K such that we can reduce the number of distinct elements from this array So currently number of distinct element is three so if I would ask you what will the minimum value of K such that we can reduce this three to two so from this if we see if we remove one instance of i1 we will reduce the number of distinct elements to two but if I will remove instances of I2 we need to remove two instances of I2 and using I3 we need to remove three instances of I3 that means if the K value is one and if we remove one instances of i1 we will be able to reduce the number of distinct element to two if you want to reduce the number of distinct elements further then in this remaining elements I = 2 I3 = 2 I3 = 2 I3 = 3 then what will be the minimum value of K such that we can reduce the number of distinct elements from 2 to 1 so if we remove two instances of I2 then the number of District elements remaining will be one right and if we remove three instances of I3 then we will be able to reduce the number of distinct element so minimum we need at least K value two to remove to reduce the number of distinct elements so from this example it is clear like to ruce the number of distinct elements one by one from 3 to 2 to 1 first we have removed that instances that number which have minimum number of instances here i1 we have removed i1 because it was having only one instances and from 2 to one we have removed I2 because I2 have only two instances that means to achieve minimum number of distinct integer after removing key elements we should remove those element first which have minimum number of instances so let's take this example we have 4 3 1 3 2 and K is three so what we have said we have to remove those element which have minimum number of instances so one the fre quency of 1 is two 2 is 1 three is three four is 1 so out of 1 2 3 4 who have the minimum number of instances two and four so we can remove any one so let's suppose we remove two on removing two one instances of two so K will be r used to two now if we further remove want to remove the instances the minimum frequency of DeMent has four have the minimum number of instances so we will next we will remove four now it have one instances so our K value will reduce to one now in one and three who have the minimum number of instances one right so but can we remove all the two instances of one no because we have remaining elements to remove is one so we can remove only one instances of one so it is one so once our K is finished so what are the instances we have left one instances of one and three instances of three so the number of distinct element present after removing three elements from the array will be two right so this is the output so let's write the code here so what we need to do first we need to calculate the frequency of each element right let's name it frequency so we have calculated the frequency of each element now we are not bothered with the instance value we are bothered with the number of instances right so we will take another Vector in which we will put the frequency of each elements let's suppose name is V now we will iterate the map we will put the frequency of each instances inside the vector so frequency of each instances is our value so now we have the instances of each element the count of instances of each element in our Vector now we will sort the vector so that every time we will get the minimum instances first so once we have sorted so once we will sort the vector what will happen so taking example two again we have frequency of four is 1 3 is three 1 is two and 2 is one and now K value D so in our map we will store the frequencies like this right for four we have one instances three we have two in three instances one we have two instances and two has one instance so this is key and this is value now in our Vector we will store this frequencies that is the value so now we will have one now we will sort this Vector so we will get one after sorting we will get one 2 and three so why we are doing the Sorting because every time we want to find we want to reduce those elements remove those element which have minimum number of instances so we will iterate from the starting index and we will check whether we can remove this whole instances of that element or not depending on the remaining value of K so while we have K we will check if so first our in the beginning our index will point at zero so this is zero index one index 2 index third index so we will check whether Vector of current index the count is less than equal to K this is so we will reduce the count of K increase the index SSE that means we don't have sufficient K value to remove the instances then we will break so let's understand the solution so in our Vector after sorting we will get one 1 2 and three and our K value is three currently our index is pointing at zero So currently our index is pointing at zero so what we are doing we are checking whether the index pointing to the vector the element that frequency is greater than or less than K so it is less than K right so we will reduce we will remove those instances so it is one so K will reduce to two and we will increase our index it will point to index number one again we will see whether this instances is greater than K or not so it is less than K so again we will remove this in instances now K will reduce to one and our index will point to two now if we see that means we have removed this and this now if we will check whether second index Vector pointing to Second index that is 2 is greater than K or Not So currently the K value is one right so it is not greater than k then what we are doing we are breaking the V Loop so we will be so after breaking the V loop our index will still be pointing to two that means we are left with the elements from point from the current index till the end of the array right so how many instances we how many distinct elements we are left with so we can calculate that by vector by size of the vector is four and our index is pointing at two if we will reduce two then we will be finding we will get the number of distinct instances that is two that means here we can return the size of vector minus current index let's try to run the test cases it is let's try to submit the solution yeah it is accepted meet you in the next video thank you
Least Number of Unique Integers after K Removals
students-with-invalid-departments
Given an array of integers `arr` and an integer `k`. Find the _least number of unique integers_ after removing **exactly** `k` elements**.** **Example 1:** **Input:** arr = \[5,5,4\], k = 1 **Output:** 1 **Explanation**: Remove the single 4, only 5 is left. **Example 2:** **Input:** arr = \[4,3,1,1,3,3,2\], k = 3 **Output:** 2 **Explanation**: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left. **Constraints:** * `1 <= arr.length <= 10^5` * `1 <= arr[i] <= 10^9` * `0 <= k <= arr.length`
null
Database
Easy
null
270
foreign binary search tree problem I thought it has been a while since we have been doing the graph problem so why not to change the topic and tree is my favorite topic it is my favorite topic so the problem is 270 that is closest by the research tree value so in this problem we'll be given a binary search tree and a value to search for and we have to return the closest node to that Target node in this example a tree is given and the target value is 3.71 out of all these nodes the closest 3.71 out of all these nodes the closest 3.71 out of all these nodes the closest Value to 3.71 is 4. if you see the Value to 3.71 is 4. if you see the Value to 3.71 is 4. if you see the difference of 3.71 with 4 it's 0.29 if difference of 3.71 with 4 it's 0.29 if difference of 3.71 with 4 it's 0.29 if you see the difference of 3.71 with the you see the difference of 3.71 with the you see the difference of 3.71 with the 2 it's something around 2 1.71 and with 2 it's something around 2 1.71 and with 2 it's something around 2 1.71 and with the 5 it's 1.29 so closest value is 4 the 5 it's 1.29 so closest value is 4 the 5 it's 1.29 so closest value is 4 and we are going to return that okay so the one thing that I would like to remind you or I think in that way the difference between binary tree and binary search tree whenever it's binary tree you cannot just structure in left and right like you have to go left and right both the ways but whenever it's binary search tree the very good thing that you can do is you can shorten your search either you can go left or right as per your parameters so the algorithm that I'm thinking right now is which is coming to my mind uh if value at my node is 4 it's greater than the target node that means my solution will be either on the left sub it can never be on the right subtree either the root will be the node itself or it will be left subtree so I can discard the right subtree because all my right sub tree will be greater than 4 so it cannot be closed so this way we are going to shorten our search so this is the pseudocodeine like in itself so let me try to run the algorithm so also let's also discuss that if there are two more than uh two values so we have to print the smallest so we have to see like which is smallest if we are going if I am going in my left sub tree then the value I'm getting from the subtree will be the smallest if I am going to the right subtree then the root value will be the smallest this is the important point to notice also when there will be null node I'll return that the difference it'll be it is having with the uh no target node is maximum just to simplify the solution so I'm gonna return which node has the smallest difference okay so if my root will be null then I'm gonna simply return uh maximum it has maximum difference max value okay so otherwise let's consider all the options if it is less than Target if it's less than so it means like my 4 is less than 5 then I have to go to the right sub tree so this is for right sub tree else if my root dot well is greater than Target then this is for left subtree as this is equal to in this case we don't have to do anything we have to return my function because that is equal okay so in my left sub tree uh what I will do I'll firstly I have to go through the right sub trick so let's make a call to the right is equal to closest value and I have to pass my right node and Target similarly I'll copy the same call to the right subtree as well okay here I have to see so uh it's I am going to the right sub tree my root dot my root is 4 and I'm searching for 4.5 my root is 4 and I'm searching for 4.5 my root is 4 and I'm searching for 4.5 perfect so here we have to see like uh there will be two values so I'll be returning the node itself whenever I'm doing it I am returning the node itself so just for simplification let's say uh double diff of right node so that will be you can take math dot apps off uh write minus Target you can take it like any Target minus right or it will be absolute value and there is another difference that is no difference diff of node okay this will be math dot apps of root dot 12 minus Target so now here is a main solution that is coming so now we are talking about the right subtree value of my node is less than like let's say the difference of the right sub tree is greater then I have to return the node so let's say uh the difference of write node is 3 and the distance of node is 2. in this case I have to return the node itself because its difference is less I have to so I'm using ternary operator so if my def of node and death of right node you can say less than equal to because we have to return an equal to case as well if this is less than or equal to then I'll be returning my root value otherwise I'll be returning my right value similarly for the left subtree let's copy all the calls left and here we also have to do left and I'll copy paste that because this will be exactly same I'm changing my indentation difference of left node this will be left a difference of node perfect so here when I am going to left subtree my distance of left will be shortest this is a very interesting point to note that whenever uh I am changing the value it'll be the other thing will be shortest so in this case what I'll be doing um if my def node is let me also take def off in that node okay if my def of node is less than def of left node uh I think equal to won't come here then it will be root value okay this is less put value otherwise have to return the left in equal to case as well I have to return the left value because that will be the small F I think this should be the logic let's try to run the sample cases um I have this okay there is some typo in my code yeah let's try to submit perfect it's submitted and it's it is beating 100 perfect so let's also discuss the time complexity of this problem as we are traversing like uh shortening one half so it will be log n so I'll be doing this uh like different problems as soon like I was doing graphs now I'm doing trees I'll be covering all the data structures topics so stay tuned bye thank you foreign
Closest Binary Search Tree Value
closest-binary-search-tree-value
Given the `root` of a binary search tree and a `target` value, return _the value in the BST that is closest to the_ `target`. If there are multiple answers, print the smallest. **Example 1:** **Input:** root = \[4,2,5,1,3\], target = 3.714286 **Output:** 4 **Example 2:** **Input:** root = \[1\], target = 4.428571 **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 109` * `-109 <= target <= 109`
null
Binary Search,Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
222,272,783
120
welcome back to this video in this video we're going to solve this coordinative equation triangle in this problem we're giving a list of lists this is our list of lists in our first row we have just this list which is found in one of one item then this is our second list third list and fourth list these are row so first row second row third row fourth row this is column first column second column third column fourth column in this problem we have to find out the minimum path from top to bottom we can move uh if the index of this column is i then in the next row we can move to at index i of column index i or at column index i plus 1 if we moved here from 2 to 4 then from here we can move to if the index of this column is i then we can move at in the next row i or in the next row at i plus one this is the problem we have to find out the minimum path from top to bottom how do we solve this problem the first thing you might think of okay this is our first uh first column initially we will have two plus in the next roof so we can move at in the next row at i and at i plus 1 for the column index we'll take the minimum is 3 okay so we moved here from here we'll take the minimum of i and i plus 1 so the minimum is 5 then from here the minimum of in the next uh in the next row we can move at i and that i plus 1. so minimum of 1 and 8 is 1. so the sum of this is 11 this is correct answer but if we have here let's assume we have here -10 -10 -10 then what would be the minimum pattern would be this two plus three equals to five plus six equals to eleven minus ten equals to one the minimum pattern would be a one for this problem this is not a valid answer so how do we solve this problem first let's draw our tree we can draw a tree from this i'm gonna change it to four now let's draw a tree from this list of list first we have two then we can move from two to three or four so from two we can move to three or you can move to four now from three we can move to six or two five so we can move to six or we can move to five now from four we can move to five or you can move to seven so here seven from four we can move to five or we can move to seven then from six we can move to four or one so from six we can move to four and from six we can move to one then here from five we can move to one or to eight so to one or two eight from seven we can move to eight or we can move to three so from seven we can move to uh eight or we can move to three this is our tree we draw this tree from this list of list now if we start solving this problem from this last row then uh then we can solve this problem pretty easily we're going to use dynamic programming let's see how to solve the stroller using dynamic programming it's uh going to be pretty simple if we look at this tree so first we have here four we have here one then we have eight and three so here uh from uh we see that from here we can move to the last row uh the cost of b4 from here to the to move to the last with the cost is one from here to move to the last group the cost is eight from here the uh cost is three to move the last row this is the last row okay so here uh let's start from this row this is our second row from the last now here we see that we'll take the minimum we can move here or here the minimum is four and one so minimum is four and one is one so here we'll take one plus six so seven so from seven uh so from six to uh last row from this uh from this node we can move to the last row and the cost is seven this is the minimum cost and what is the minimum post to move from five to uh to the last row we can move to one or we can move to eight the minimum of eight and one is one so five plus one is six then from seven let's find out the minimum cost to reach the last two from seven minimum is three so three plus seven is ten the minimum is 10 so we have computed these three values 7 6 and 10 now let's move to this row from here to reach the last row what is the minimum cost okay so we have solved this problem for this and this so we have solved this problem for five and four six from five we can move the last ring cost six from six we can move to the last row in cost seven okay and we see from three we can move to six or you can move to five so we'll take the minimum six and seven the minimum of six and seven is six plus three goes to nine okay now from four we can move to five we can move to seven we have already solved for this node five and for this node seven we're treating the element as node now we see that this is minimum 6 so 6 plus 4 is 10 now let's move to top from 2 we can move to this or we can move to this we have already solved for this node and already solved for this four so the minimum cost is the last row from this node three is nine the minimum cost to raise the last from this is ten so minimum is nine plus two is eleven is the answer this is how we can solve this problem but how to implement this what we can do we can create um we can create an array of dynamic programming this is dynamic programming array we'll have here four element this is the four element of our last row so initially we'll have your four one eight three we'll start from here okay so we'll have here this at the first three positions we will have the value going to move to this row uh we will have the answer here seven six and ten will have your seven six and ten let's see how we can calculate that when we i have calculated uh when you're calculating the value for this node six we'll move to this and this so from here or here the index of this is zero right the index of this column is zero so here is zero so zero at index 0 and at index 0 plus 1 so if we say call the index is if we say the call the index then we can find it out at index call and add call plus 1 so mean is 1 plus 6 is seven so here we'll update this value with seven now for this is at index one okay this five at index one at call index one so we can move to at index call index one this is at calling this one and this is at calling this call plus one so we have here the value in our dynamic programming table so one and eight minimum is one so five plus one is six let's update this value with six then here we have seven right so we can move to eight or we can move to three here we have the value the index of uh from seven we can move to eight or three the index of eight is uh zero one two and the index of 3 is at 3 so the minimum is max minimum of 8 and 3 is 3 so 3 plus 7 is uh sorry here we have 3 plus 7 is 10 here we'll have 10. now let's move to this row in this row we have solved this right so for call at call index we have seven and four plus one we have six so mean of six and seven is six plus three is nine so here we'll have nine now for this we have access to this six and ten we updated this value nine for this value okay so we have access to this so at index column five it is called plus one we have here at index call we have six at index score plus one we have ten so many so minimum of 10 and 6 is 6 plus 4 is 10 okay so here we'll have the value 10 let's move to 12 to this row the minimum is 9 and 10 for this we can move to an index call and it call plus one call and call plus one right because zero and this zero plus one is one so minimum of nine and ten is nine plus two is element this is your answer and whatever well we have at this positions so here we'll update at index 0 with 11 this is our answer at index zero this is called dynamic programming this is how we can solve this column uh this is called a top down uh we're moving to or not solving from bottom up we're moving our solving it from top down okay we're uh solving for the last problem the last sub problem that we're slowly uh down slowly moving to the smaller problem so this is called a top-down problem so this is called a top-down problem so this is called a top-down dynamic programming this is how we can solve this problem if we have here minus 10 then also we can solve it let me show you quickly we have here minus 10 what would be your answer the answer would be okay let's place it minus 10 the answer would be 2 plus 35 so it will answer will be my answer would be 1. let's see how to find it 1 here okay so we will start from uh this from this reward for this level if you consider this is a tree so minimum is -10 minimum this is a tree so minimum is -10 minimum this is a tree so minimum is -10 minimum is -10 and 6 is four minimum is -10 and 6 is four minimum is -10 and 6 is four then here minimum is one so six minimum means three so ten then here anyways minus four so here we will have minus one now minimum is six plus four is ten minimum is minus one you remove two so you will have one this is your answer this is how we can solve this problem this algorithm will takes of n square time complexity and it will takes off in space complexity for the dynamic programming table then underneath government the size of bending problem table is the size of the last row this is our algorithm to solve this calling triangle now let's correct this problem let's call a function triangle let's assume it sticks the list the name of list is t now first thing what i'm going to do i'm going to find out the number of row we have so let's call it num row equals to number of rows t dot length uh it we're given a list so let's use here a site now what i'm going to do i'm going to create a dynamic programming table so in uh let's create an equivalent table i'm just going to write the serial code so dp the dynamic programming table the site of dynamic programming table is the site of the last row okay so new int uh t dot gate the last row the size of last row so num row minus one this is the last row the size of the last row so side this is your dynamic programming at table now first thing what i'm going to do i'm going to copy all the value from the last row to this running programming table so for i equals to 0 i less than the length of dynamic programming table so dp dot length and here i plus now right inside here at index dp at index i we're going to copy the last value from last row so t dot get from last row so num row number minus 1 dot get at index i okay so at this point we'll have the envelope last row into this dynamic programming table now let's run our algorithm for uh i equals to uh let's call here the row okay row equals to the on the second row from the last so number minus 2 num row minus 2 while ru is greater than or equals to zero and we're just we'll just decrease the size the move to the previous row is step in easiest step now right inside here i'm going to run a nested loaf so for i have to iterate uh i have to iterate the uh the all the element from the row okay so if we have something like this let's draw here input so here we might have something like this okay so you will be positioned at here by this for a loop from here iterate with all the way to the end so for column so column equals to zero from zero to well column is less than or equals to the last element in this row the length of this row is r so r and c plus but now right inside here we will compute the value for our uh for our is column for first to this column they put this column for this column and only move to the previous then this column and so on so dp at column zero okay so at column zero what we will do we will move your dynamic programming table right a dynamic programming table uh so here we'll have the answer at c and at c plus one so minimum of let's move to dynamic programming table at the first position we have the value at this value okay so dp c and dp c plus 1 the minimum value plus t dot get this value okay this current value so d dot get uh at current uh index at current row dot at the current column so c this is your algorithms without the answer at the first position of our dynamic programming table okay at the first position we'll have the answer so here we'll just return uh the answer from index is zero this is our dynamic programming a solution this is how we can solve this problem hope you've understood this video explanation this algorithm will take so often square time complexity and it will takes off in space complexity hope you have understood this video explanations if you have any questions you can ask thanks for watching this video
Triangle
triangle
Given a `triangle` array, return _the minimum path sum from top to bottom_. For each step, you may move to an adjacent number of the row below. More formally, if you are on index `i` on the current row, you may move to either index `i` or index `i + 1` on the next row. **Example 1:** **Input:** triangle = \[\[2\],\[3,4\],\[6,5,7\],\[4,1,8,3\]\] **Output:** 11 **Explanation:** The triangle looks like: 2 3 4 6 5 7 4 1 8 3 The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). **Example 2:** **Input:** triangle = \[\[-10\]\] **Output:** -10 **Constraints:** * `1 <= triangle.length <= 200` * `triangle[0].length == 1` * `triangle[i].length == triangle[i - 1].length + 1` * `-104 <= triangle[i][j] <= 104` **Follow up:** Could you do this using only `O(n)` extra space, where `n` is the total number of rows in the triangle?
null
Array,Dynamic Programming
Medium
null
275
Hello guys welcome back to record degi team from June record challenge and toubro limited index in this problem will also go through the problem description and will try to understand with few examples and will explore different a solution approach for these problems and also will discuss time Complexity Wipro Chiffon YouTube Channel Please Do Subscribe Vishal Laute Quantity Problems All Right Knowledge Within R Problem Solved Problems Its One and Raw Fuss Addiction Spotted in Ascending Order Site Question Is Not a Good Teacher of Research White Function to Complete the Research 8 and Its Own Right according to the definition of H index on Wikipedia Scientist is if Izhar and paper is wet research and the in - paper is they no more than its research and the in - paper is they no more than its research and the in - paper is they no more than its citizens among right short clips 8 bit difficult to understand from the problem description knowledge contained with example daily will Be More Clear Dried Air Water In The Cases For The Scientist To Measure The Performance It's Kind Of Rank Under Shoulder Is Paper That Gay Polaroid And You Will Find Out Which Index Of Their Observe Submit So Let's It's Everyone A Different Sites For Different Weapons Definition Caesar A Scientists Have Been Indicted Only 34 Her And Papers Have At Least 8 Sanskrit Beach Election Vote Se Is Click Salicylic Acid To 4 Sheets More Than Duty Also At Least For Citizens Which Is Great Having Great Dane Citation C Code For Shelter For In The Early Two Pairs Have Winger Stations Will Give Into Great Content For All Night Shift That They Cannot Take That Is Index Of Will Take It's Three Languages ​​Have Three Papers Three Languages ​​Have Three Papers Three Languages ​​Have Three Papers Having No Affair And Moderation Value Added To Compare To Be Taken As A 3D Printed S8 Index For Governance in food is going to be option and Rafael Nadal is Vv Hai Wah Stations Papers For The Best Fights With Active Voice And Answers But What You Want This Will Want To Highest Score In That Case Wolves Mitthu Select Alarms Value From The Giver Result And Write Damini Solution Students Problem And Ride Solve And Quick And Your Linear What do you want is different from one side and linear that to the end and till hindu only years whichever you have land record 210 hello and you can stop you right from fear is in the given in food and original software online travel tube check clear weather This Jeevan Index In This Site And Satisfying And Not Know What You Will Welcome On Twitter - Is Without Number And Like This On Twitter - Is Without Number And Like This On Twitter - Is Without Number And Like This Great Content Will Move To The Number Sudhir And It Is The Number Video Subscribe Char Looter Ne Yeh 70 80 Points 372 That Aapke Manju Where I want it should be worn tears and cheers 72 - You are due to be easy for cheers 72 - You are due to be easy for cheers 72 - You are due to be easy for that your end acted with greater and record to for which is not truth in the cabinet to reverse or last satisfied and subscribe result * 40 first of the Time subscribe result * 40 first of the Time subscribe result * 40 first of the Time Complexity of this will take you can go to go slowly with a positive energy torch light show in this is what we use to this will take to pointers that is from your help to your health sun lover point is this point and will always using Which you will find out who meet pointer ok left submit key and will check whether given target number is matching with her to know this meeting will return that number otherwise what we will do effects of class 10th target is this number is the target technique jatar ghat Reliving this area ok a target is the government number 21 2012 same way we change in the normal channel subscribe attached index seoul wave and 65 more element always want to bid to be always want to travel in this area which ultimately 2 return result Gum 100g No change previously in verse Let's you have this quotation value right It's going to target number and password Target number and the number which we can - number and password Target number and the number which we can - number and password Target number and the number which we can - meet G hall at which gives you this number of elements of this great and your stations of meet That Aapke Dekh Meenu Savi Hai He Steal Possibilities And They Can Still Travels In This Area Hai Pimple Dissatisfied What This Condition Se Is Pest Middle East 80 Condition But You Can Still Go To The Next Year That Them Is It Is Last In These Indicators What We What you're doing is you'll change your highest point up-to-the-minute minus highest point up-to-the-minute minus highest point up-to-the-minute minus one torch light handle and you'll return. The Water But You Have Ujjain 8 - What Were The Law Officer You When You Have 8 - What Were The Law Officer You When You Have 8 - What Were The Law Officer You When You Have Correct Number Your Lover Point To The Number You Will Remove Dhund Index From The Total Length And You Will Return This Value The World And They Can Return The Result Your Show In This Binary Search Case It Will Reduce Time Complexity From Near To Off Login To Switch Board The Optimal Approach Which Can Apply For This Problem Laddu Code For Next Flight Knowledge And Different And In Here Fall Winter Interior Logical 204 And Is Going To Be pure citation scotland that i have this one ok animals will define a length approximately riches that your that and also will define if meat 204 you ok know it rest till very feel procedure that your knowledge first sacrifices and in - that your knowledge first sacrifices and in - that your knowledge first sacrifices and in - knowledge first calculator need some medicinal plus Yes thief one month sale bittu ok whatever calculator and meet soft and n - meet that calculator and meet soft and n - meet that calculator and meet soft and n - meet that is great 04 which patience that mir than change and that short to the meet plus one that bike sales change and height if definition ok and last will Return - Online Source ok and last will Return - Online Source ok and last will Return - Online Source Code Loot Knowledge Compiling That Your Inputs Compile And Vigor The Correct Output Separate Submit That Your Hindi Old Accepted All So Let's See The Memory And The Time Education I Online Digital Studio 20 Per Cent And Memory Boil Solid Looked Wick And Churchich In this video hot yoga liquid fear different problems solution of deaths due to write down the comment box see you in next problem at a time when oo
H-Index II
h-index-ii
Given an array of integers `citations` where `citations[i]` is the number of citations a researcher received for their `ith` paper and `citations` is sorted in **ascending order**, 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. You must write an algorithm that runs in logarithmic time. **Example 1:** **Input:** citations = \[0,1,3,5,6\] **Output:** 3 **Explanation:** \[0,1,3,5,6\] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 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,2,100\] **Output:** 2 **Constraints:** * `n == citations.length` * `1 <= n <= 105` * `0 <= citations[i] <= 1000` * `citations` is sorted in **ascending order**.
Expected runtime complexity is in O(log n) and the input is sorted.
Array,Binary Search
Medium
274
108
hello guys today we will solve the question convert sorted array to binary search tree and the question number is 108 and the question type is easy and the question statement is given an integer array where the elements are sorted in ascending order convert it to a height balanced binary search tree so what is by height balanced binary search tree a height balance binary search tree is a banished tree in which the depth of the two subtree of every node never differs by more than like i can show you if it is a node and it is a one children and this is the second one it can be like this it will be bad in sub tree because height is if we count one then it has two so two minus one like this it will be height balance history but not more than this now see another example so what is now we will discuss what is the question statement so we have given the integers as a num and we need to uh give the output as a tree balance history where it should be height balanced and all the values should be in proper way as uh binary search tree uh like uh the you know left uh left challenge should be less than this one and the all values also should be less than like that you know what is binary searched if you don't know you can google it because i'm not going to explain this right now so let's see an example how we can solve this question so i'm going to solve you uh for two example that is first one is for the odd number like minus 10 minus 3 and zero five nine right it is one of the example and another one will be the here it is odd number right five i will solve for the event number like let's do 5 right so i will solve this for those for these two questions so what we can do like we can use recursion right because every time uh like we call a function we will do the same thing like uh for a node then after this node will be exactly like this same function same rules will be applied on this node also because left sub tree should be a smaller right intercept tree should be larger and it is uh sorted so there is no problem like that so we can find a base node that is that will be like here it will be zero because we need to give the balance uh mandatory so we can find the medium number that made will be so what we are doing here we will pass we will make a function let's assume it is f and we will pass left right will be n minus 1 if the size of this is an n here it will be 5 n minus 1 and this so what will our function will do it will ask it will check what is the mid value i mean the base node it will do the left plus right by two because minus 10 will be zero and this will be four so four by two will be two right so zero one two zero will be base right now you must be wondering what would happen if it would be even number like 5 by 2 it will be 2.5 in that case the base will be 2.5 in that case the base will be 2.5 in that case the base will be second if it is 0 1 2 the base will be the same like here also base will be 0 only according to our code after that it will call 2 function the left part that will be it is 0 1 2 medium is 2 right middle one is 2 so it will call same function for the left like you can call the 2 dot left here i am calling it is two it is not synthetically right i am just calling it two doubt left will be same function f will be called with zero and middle minus one and because same thing will happen right for the left part and 2 dot right function g middle plus 1 because middle is the root node midi plus one is the arrow right we can do this now what will happen for the left part it will be minus ten and minus three right and for the right part it will be five nine right 0 is our base so minus 10 minus 3 and when this function will be called it will be 0 left will be 0 right will be 1 so again the base will be what zero minus base will be zero plus one by two that will be zero point five and zero because it is integer it will be integer value so our base will be zero right so as i told you the formula left plus right plus by 2 so 0 will be base so minus 10 will be our base and what will be right for the right purpose of this node but for this node will be this 5 and 9 so here also base will be 5 now for this function what will happen for the left purpose it will call 0 mid minus 1 its mid is 0 so 0 minus 1 will be called for the left of this function right and for the right mid plus one that is one and the right one is one array will be called for the right now what will we do for because we need to give b null when there is a vacant place we will give null so for that we will have to code a base case what will be that base case whenever will be left will be greater than right return here for this left purpose what we our middle is zero so zero and the left middle minus one here left is zero and right is minus one so this condition full face so null will be given here null and right will be minus 3 exactly same here 5 right will be 9 and no so it will be our answer 0 minus 10 minus 5 null minus 3 n minus 9 right you can see how we solve this i will show you the code part also and for the when whenever there will be even number like here 0 minus 10 minus 3 will be for the left side and 2 5 9 for the right side so here's exactly same will happen minus null and minus 3 but this side five to nine so it is pretty simple now see the code you can see the code right see it is a given definition and all leave it from here it is our given function name is tree node we need to return tree node we just calling the function that is called helper and we are giving the array left right only these three things are needed left right and there so it is the best case what i told you like whenever left will be greater than right return null right and for the middle of the array left plus side by 2 and we are making a new node that will be base node and for the left side we are calling the same function again with the um input num slab middle minus 1 as the right and for the right side middle plus one as the left and the right has a right and returning we are the that tree right thank you now you can see the code how this codes are working or not like that see my code is running thank you
Convert Sorted Array to Binary Search Tree
convert-sorted-array-to-binary-search-tree
Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_. **Example 1:** **Input:** nums = \[-10,-3,0,5,9\] **Output:** \[0,-3,9,-10,null,5\] **Explanation:** \[0,-10,5,null,-3,null,9\] is also accepted: **Example 2:** **Input:** nums = \[1,3\] **Output:** \[3,1\] **Explanation:** \[1,null,3\] and \[3,1\] are both height-balanced BSTs. **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in a **strictly increasing** order.
null
Array,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
Easy
109
6
Hare Krishna guys so welcome to my youtube1 day we are solving one or the other question of lead quote so today our question number is six which is we have to make zigzag conversion okay so we will be given a string we will have to make it in zigzag form. So if you have solved pattern questions, then you can think of making them in the style of pattern questions by dividing them into more approachable ones, then you can try first and I will tell you what is actually to be done in the questions, so let us know here. We have to make a zigzag pattern on it. Okay, so here it has been given a name. First of all, we will go from this side till the bottom, then here we will go diagonally till the top, then here like this, then like this, we will be making zigzag here like this. Okay, so we have to make the questions in the same way in the future also, like here also we have been given a first example, so we have seen above. Okay, so here we can see, here we have gone down till four rows and then again diagonally. Now we are going down, then we went back down, then we are going up, so if you have made the question of the pattern, then it will be a little easier for you to make it, so first of all, here we check whether the approachability is there. Let's take it here, as we are coming here, we will lower it down and write it on us, after that as soon as we have to go diagonally, we will put it at this place which will be our third index, then it will reach this place in our fourth index, okay and Then in the same way we will be making a zigzag pattern here, so we will make it like a question in the pattern, we will try to make each question mean something or the other and make a relationship. Okay, so like how much gap is there between P and A? So we have some gap coming between P and A, like there is a gap of four between zero and four, then between four and eight we have a gap of four and between eight and 12. There is a gap of four coming in between also, in the same way here also we have a gap of four coming between t and six and four and sorry, we also have a gap of four coming between six and 10 so we have this thing I understood that in this question we have been given the number of roses, so the number of roses has been given here as three, so if we have been given three then there is a gap of four and if we have given four here. If given then there must be a gap of six here, so let's see. Yes, we have a gap of six here. Okay, so you will see this question also by dry running it. And if you dry run this question then see it in the same way Excel. Meaning in the form, by making rows and columns in the matrix form, you will understand that what we are going to do is OK, so we have the formula for this, here we do this that 2 times n - 1 OK, we do this that 2 times n - 1 OK, we do this that 2 times n - 1 OK, so n is our number off. Rose will be here and if we change it to -1 then our it becomes three to two change it to -1 then our it becomes three to two change it to -1 then our it becomes three to two and we get 2 * 2 4. Okay, now we are and we get 2 * 2 4. Okay, now we are and we get 2 * 2 4. Okay, now we are here in this middle one, we will see what we have to do, so here we are seeing. Three is coming after one, so here we are getting a gap of two. Okay, so if you directly look at this question here, what we have done is that 2 Malla by n - we have done is that 2 Malla by n - we have done is that 2 Malla by n - 1, which is our solution here. In the beginning -2* So if you are In the beginning -2* So if you are In the beginning -2* So if you are thinking here that if we convert the minus directly to two then will it work properly for us? Yes, it will work properly for this question but if you dry run this question and see. For question number example two, you will understand why we have written here I, so we will leave it to you because as our number of days is changing, it is changing. Okay, so this is our I. Whatever our loop is running on, it will depend on it, that is, it will depend on our daily routine and will be completely dependent on the column, so let's code this question and then we will discuss the solution again, so first of all We are looking at a third example here, so in the third example, A is given to us. If simple is given to us, then its output is given to us as A. Okay, so first of all let's solve it if nam rose e is equal to two. If our this is equal to one, then we have to simply return this string. Okay, so we have returned this string. Now what do we have to see, so first of all we take the length int n i to a dot length. And we have made the length here, now what we have to do is to make a gap here, gap, what will we make, what was the formula of gap that I told you, Multiply by numbers, row, minus, and okay, so this is our formula of gap, which is gap. And remember, where our gap will change, whatever will be our starting row and ending row, except those two rows, wherever our gap will be, here we will have to use this second formula. If this is fine, then we do this. So we create a string here, let's create a string or string builder, let's create a string builder, which will be good for us, string builder and we create this. Okay, so first of all we have to create two loops here, the first loop, what should we do? Which will be our full from top to bottom i.e. from the starting till the last, i.e. from the starting till the last, we will be checking all the elements one by one, so first of all we put for a i equal to 0 a is less than names ok so this is our above. Our loop will be running from here to here, so first of all we will be printing the top line from here to here. OK, from here to here, then in the next line we will be printing from here to here. And in the same way, we will be doing it slowly till we reach here. Okay, so we have put the loop. Now first of all we have to create the index. What do we do? Index is equal to I. Okay, whatever our number of rows will be, we have pointed the index beyond that because we will have to change the value of our index and print it. First of all, we will be printing zero index here, then second time our index will be straight. He will be pointing to four, then he will be pointing to us, then to us, now you must be understanding why we have done this work, that we are doing this, it means just like you solve the question of matrix, in the same way. We have put the first loop for the row. Now we will be printing it like this, so we are increasing the value of the index. Okay, so here we do the further code. While as long as our index is less than a, then what about us? Till the length is OK, so what do we have to do as long as it is less than the length? What value do we have to put in the string? Whatever will be our index, if we have to put that value then we will use a function because we are using string builder. Ok so append a dot caret i ok sorry index so first of all we have appended now what will we check so we have done this for the starting row because we have applied the formula for that now if our starting row Or if it is not in the ending row then what formula do we have to apply so as we discussed then first of all we do this if i is not equal to zero and end i is not equal to two row sorry numbers row I think I had started somewhere Nam Rose Ok Nam Rose and somewhere else it will come at the time of compilation Ok so my so here we have this condition if it is not inside these two then how do we have to increment it so we Let's first take a J and we'll be incrementing the index because we're incrementing the index Okay so how will we be incrementing the index Whatever our gap is, what we're doing first of all in that gap is minus which Also we have a gap in it, we will be doing minus by multiplying by 2, multiply by a. Okay, so we have already put the value of the gap above, so let us see in this question, like here we were multiplying it and subtracting it. If we come to this T, then its value, we have already taken the gap here, so we minus it in the gap, this is how our J index has become, now what we have to do is that we have made the index, so now if we call it J I Lesson A So we're checking the condition again to see if our It is at this place below where my cursor is lying. If it comes to that place, then we will have to check it again and again. So atr dot append s dot ker at and here we are putting J. So first of all we are here. After doing this thing, now here we see that we will be incrementing the index, so what index will we increment, whatever is our first index, what are we increasing in it, we are incrementing from the gap. Because what will be our first gap? What will be the value of the gap? What have we got? If we have got four then we are incrementing by four. Okay and what we have done at this place is we have printed it but from our gap we will be incrementing because see. Let's first reach here from top to bottom, after that whatever other condition etc. we have imposed, what are we changing in it, basically we are handling this place specially, okay, so for that we will do this middle loop. And then here we now take it out of the while loop, what do we have to do, as soon as it comes out of the while loop, this is another for loop, after coming out of here, we return it. Also if this is our string then what is our string SR OK let's return ATR oh sorry ATR dot to string because this was our string builder so we will have to convert it into string so I think we should run it now Let's run it and see if there is any compilation error. Okay, I thought I have done this mistake somewhere else and at another place I did it Namroz, so all our test cases are running properly and giving us the output. Now we If we submit it, then OK, our question has been submitted and once again we see how approachable we have made it, from here till here we are incrementing it, which is the formula of which we have written here and For this side also, we have written the formula and whatever our upper means in the middle, we have this formula for that, similarly we are increasing here, so if you dry run many questions in the form of matrix, then you will get You must be understanding how our work is working, so I hope you liked this video and see you in another new video tomorrow, till then bye take care Hare Krishna.
Zigzag Conversion
zigzag-conversion
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "` Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); **Example 1:** **Input:** s = "PAYPALISHIRING ", numRows = 3 **Output:** "PAHNAPLSIIGYIR " **Example 2:** **Input:** s = "PAYPALISHIRING ", numRows = 4 **Output:** "PINALSIGYAHRPI " **Explanation:** P I N A L S I G Y A H R P I **Example 3:** **Input:** s = "A ", numRows = 1 **Output:** "A " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. * `1 <= numRows <= 1000`
null
String
Medium
null
1,706
Hey Guy, today we will do our first question number 27. What is the question trying to say and what response do we have to send? Okay, you will have a 2D grid, this is your grade, okay, the values ​​in the grade will be only van your grade, okay, the values ​​in the grade will be only van your grade, okay, the values ​​in the grade will be only van and minus van. Okay, if it is a van, let's say that this one of mine, this one is great, okay, its value is a van, if that means the road in it will be from top left to bottom right, okay, that means here value van There must have been a van here too. This is from top right to bottom left. So there must have been a mines van here. Okay, here these mines must be being built. Okay, similarly, here a van here. Van mines, van mines. Van mines van similarly the whole field will be like this ok what do we have now that for now I remove van and mines van for now to make it easier to understand ok you got the idea so let's go ok jo road In which direction is it going? Each cell is like this, then this is like this, so friend, what is the question, in each column, the ball was dropped from the top, okay, the ball was dropped from here He is speaking from here. Okay, so he is asking from where each ball will fall. It is okay and if it is not falling then it means it will be a mine van for him. It is okay to tell him as if I take it. They are talking about the red ball. Okay, so let's choose the red ball. It is a red ball. See how it will fall. It will fall like this. There is nothing here to stop it. It is going smoothly, going. It is going to pass from here, so you see from which column the ball with zero fell from the van, then look from which column the ball with zero fell, the answer is van, okay, it went like this, okay, now look, this is a block. It's done, it's blocked here, now how will it go from here, there is a road here too, look at this, there is a road here too, there are such roads here too, so it has actually blocked the green ball, it is green. The ball will not be able to go anywhere, that is why look for the green ball, there is a mines van here, okay, let's move forward similarly, look at this ball will also not be able to go anywhere, it will be blocked here because look, this one and this one blocked it, okay So there is a minesweeper for the second ball as well. Okay, this ball will also get stuck here and cannot go anywhere. This ball of ours is the last one. Let's go through how many columns in it. One, two, three, four punches, then the punch size. You have to send a character and for each ball you have to tell who will fall from which column and the one who will not be able to fall, the answer below will be Mines Van and this van was falling from the van in the column, so the column here is van, we have sent it in the answer. Okay, so let's see how we will solve the question, it is simple, there is not much to do. Okay, let's see how we will solve it, so let's see how we can make it. Let's also write the numbers here van mines van. So see, we have filled all the values. Okay, now look, let's think with each ball, just like we take a man, now I am thinking for ball zero, okay, I am thinking for this, okay now I am thinking for ball zero, so where does ball zero start? Look, all the balls are equal, you are starting from zero, right, all the balls are starting from zero every day and I take the ball, I am near zero right now, I am fine here, the ball is zero, okay, so it is obvious. What can be the value of any cell, either it will be 1 or it will be 1, okay and if it is 1 then two things can happen, or if it is 1 then two things can happen, first if it is in the last column. You are standing in the last column here, you will get stuck, say, you understand, I am standing, if I am in the last column, then brother, say, you will get stuck, what else can happen, if the cell in which I am standing is a van, it is okay and the one next to me is This is a cell, that is a mines van, okay, next we can do this - Neighbor - Neighbor - Neighbor Cell, which is -1, still the ball will get stuck, it is here, will the ball fall like this, if it does like this, then it will go to the next column, then if both of these If the condition is not there, what will we do? Brother, we will make column plus, right? Column plus, then the speech will get stuck, again if the speech gets stuck here, then the speech will get stuck. What is the second condition in this too, that if there is a mines van, then it is fine and its Man let's take the ball, if it is here then it is okay, who is its neighbor? If there is a van, then the ball is still stuck, okay and if these two conditions do not happen, then if these two conditions do not happen, that means the wall can fall further down, then the column mines. We will do it, okay, till now I have understood, let's try it once and see whether this ball is zero or not, how the column comes out of the van, okay, let's do it first, okay, let's see the ball. How does it go to zero, so now cry, what is mine, what is zero, it will start from zero, okay now look and what is the value of the column, so what I told you, it checks two things, right side, then who will cry if you go to the right side? So the same will be column plus one, that is, what is there in 0 1, I am not in the last column, okay, so there is also good from this also, okay, so that means we can do column plus, okay, this means this ball which This is mine which is my ball B zero from here now A has gone here Column plus A is gone Okay so now let me race here Okay now what is my row What is row is my van Okay and the column is also done The van is fine, now what is its value? The van and the value of the van are neither van nor two things can happen. Firstly, it is a van and its value will go to the right side. So my ball will go to the right side. So let's check the right side never. Who will be the van earner? The value of the right side of it will be there. If the value of the right side is minus then the ball will get stuck but look here, who is the neighbor on the right side of the van, its value is not -1, meaning the hair can fall or else not -1, meaning the hair can fall or else not -1, meaning the hair can fall or else what else do you check. Is the column not the last column? No, there is not even the last column, that is, CR is good from every also, so now the ball can move forward, so the ball has moved from here, the ball has come here, so row plus, is its value plus van? No, can the ball fall further or am I in the first column? No, I am not even in the first column, so C R Also good, so now the ball will move from here to here, okay, similarly, now here I was going to do row plus because I Mines was in the van one No means, if the ball goes like this then I check my cell which is on the right side, which one is not on the right side and secondly what if I am not in the last column, no, that is also correct, if it is not in the last column then tell me. If it can go then the ball moved from here and came to the set ball here, so what happened this time, if Ro plus goes, then we check the left neighbor, otherwise we check the left labor, if Left Neighbor says, then Ro will remain the same and Column will become van, is it plus van, if it remains plus van then it will block me but it is not plus van, look here there is no plus van, it is minus van meaning it will not block me, it will fall, okay so what to do then see what It will be done, my row will become 5 and the column will become one. So it has become five, which means we have come out of the grade. Okay, so it's simple, you will put a for loop, and where will the column come from? Think for yourself, every ball is like zero. So the ball starts falling from the opposite column, the first ball starts from the second column and the second ball starts from column C, that means whatever ball is the number of the ball, then the column must have started from zero, right, whatever the number of the ball is, it should fall from the same column. It's okay to start, and the cry is zero for everyone, all the bosses are starting to fall from zero, right here, the fall is starting from here, all the balls are okay, till now I have understood, okay, let's move on, okay, and here There will be two things, one van, if the van went to the value of my cell, then I had said two things in it and if the mines van went, then there were two things in that also, I had said, it is okay to check if any of these two in your result - 1 Will give the team and if not, it your result - 1 Will give the team and if not, it your result - 1 Will give the team and if not, it comes out of wild look, then whatever is the value of the column, it will be given in the result, then our course will be solved, it is a very simple story, meaning you just had to visualize that the ball is taken by the man, it is here. So who can stop it, there will be a mines van next to it, only he can stop it or else the ball would have been here and there is a column next to it, the last column is man lo, so you can write the code just by visualizing it, we will write the code for this now. Neither, if you write the story exactly like this, then it will be understood well. Okay, so the question is exactly what I told you. Okay, I told you this example. Let's come to direct coding. Okay, first of all, what did I say that this is Just take out the credit dot size and the grid is zero dot size, row and column are taken out as per the total, ok after that we will run for every ball, end ball = starting from 0, ok, one result number is standing in the last column. Or grade of row earn call plus van which is the one next to me on the right hand side, if it turns out to be my -1, side, if it turns out to be my -1, okay, what does it mean that I am going to laugh at you, okay and if this case happens then it will get stuck, then left. If I go to the side, I will get stuck, if that banna comes out, he will get me stuck again, in this case also stuck, this equal will be true and we will break, okay and if the wallet is not there, then what will be the obsession, then in both the cases, if there is no ball. Let's take the man who is stuck here, see in this case if the ball is not hit then I will go to the next column and in this case the column will be mines. Remember if the ball is not hit and mines is one value then I will go to the column on the left side of the office. And see in this case, if the ball is not atkegi and the value of crit is one then I am shifted to the right column then call will be plus. Okay and every time my row becomes plus because I am going to the next row every time. There is a bar, right? If I exit this form, then I will check that if it was stuck once it is true, then it is ok if it is stuck and when I exit from this form, then it silently returns its result. Is there a submit question? You are visualizing and imagining it yourself, right? If I am standing in the grid with a van, then it will want to shift to the right side and if a guy with a mines comes from the right side, a guy with a mines van comes and stops me. Will give or if there is no column on the right side then I will get stuck and if I am there then if I can't go then I will get stuck on the left side or if some guy with a plus van on the left side will get me stuck then that's all you need. Wanted to know that let's do a cup of hatke, okay if there is any doubt, race in the comment section and try, help you gas video thank you
Where Will the Ball Fall
min-cost-to-connect-all-points
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. * A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`. * A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._ **Example 1:** **Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\] **Output:** \[1,-1,-1,-1,-1\] **Explanation:** This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. **Example 2:** **Input:** grid = \[\[-1\]\] **Output:** \[-1\] **Explanation:** The ball gets stuck against the left wall. **Example 3:** **Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\] **Output:** \[0,1,2,3,4,-1\] **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 100` * `grid[i][j]` is `1` or `-1`.
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
Array,Union Find,Minimum Spanning Tree
Medium
2287
26
Hello Gas Myself Amrita Welcome Back To Our Channel Techno Says So Inner Court Series They Have Bin Solving Lip Code Problems Per En Wile No Or No They Are Going To Start Up With Top Interview Questions On Lead Code These Are One 150 Questions And Bill Be Solving Which D question one by one so I have already solved first two questions assign mention D link in D description box you can check date out and in this video bill be starting up with D problem number three date remove duplicate from sorted are so late get STARTED IT IS QUESTION NO. 26 SO LET FIRST UNDERSTAND PROBLEM LIFE AND WAIT ERROR NUMBERS SORTED IN NON- IN NON- IN NON- DEcreasing ORDERS REMOVE D DUPLICATE SUCH DATE WHEN YOU NEED ELEMENT APPEARS ONLY ONCE AND THE RELATIVE ORDER OF DUPLICATE SHOULD BE FROM AND RETURN D NUMBER OF UNIQUE elements in d number so they have bin jivan one so they have you remove duplicate and let them have you return count of unique elements they have bin jivan one you so once you remove this duplicate your left had two elements this 1 and 2 so you Are you going to return the same and also after removing the duplicates what you leave behind you can see undersc so that Vasant Matar Vativer is there you just have to return the count of unique elements so no let understand how you are going to solve this problem let Me take one you are three four five and six right remember so it's main if there is this else duplicate it has you be the next element right so what they are going you do they are going you check if you are current element if current element is Equal to next element give date means it is an duplicate right so in how of duplicate what you are going to do you are going to continue date means you are going to ignore date particular element and if date current element is not equal to give next element Date is a unique element so you are going to date particular element in the era simple D elements they can not take other separate are they have too D elements in this particular are themselves and come given and they have you return count of these unique elements After removing the duplicate correct so let's go we are going to perform these steps so let's arrange one two three and index are zero one two three four what is current element one and what is next element date is also one One is equal to one true so when both d elements are equal then date mains it is duplicate they have tu no date element and continue right move on to next element i one so in this how current element is 1 and next element are not equal then date mains it is a unique element so we are going to say date element in the are correct d first position date mains date d zero index record n ​​first element so we are going to say record n ​​first element so we are going to say record n ​​first element so we are going to say date on date bill b taking one variables name set Count is equal tu step dr second last element they don't have tu check they can directly say this particular element in the and what is de count tu tilhar right so when you saw this particular element again count wickham plus one which bill wickham three so no Count of element is 3 and you are going to write d output test three so this is ho we need to solve this problem so let move ahead and let write d solution on it so this is r class date is removed duplicate from sorted are no let Right D method date would be public static in the sense they are going to written count duplicates and it would expect only one input date is names are and give what is your first step they are going to travels through the arrange plus and let they have you check Length -1 right because they have tu check only till d -1 right because they have tu check only till d -1 right because they have tu check only till d second last element is not going to be duplicate so they are going to date directly in the are else what is d next condition date if current element is equal to next element Let They Are Going To Continue Else They Are Going To Say Date Element In The Count Position Let Right Print Statement
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array `nums` sorted in **non-decreasing order**, remove the duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears only **once**. The **relative order** of the elements should be kept the **same**. Then return _the number of unique elements in_ `nums`. Consider the number of unique elements of `nums` be `k`, to get accepted, you need to do the following things: * Change the array `nums` such that the first `k` elements of `nums` contain the unique elements in the order they were present in `nums` initially. The remaining elements of `nums` are not important as well as the size of `nums`. * Return `k`. **Custom Judge:** The judge will test your solution with the following code: int\[\] nums = \[...\]; // Input array int\[\] expectedNums = \[...\]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums\[i\] == expectedNums\[i\]; } If all assertions pass, then your solution will be **accepted**. **Example 1:** **Input:** nums = \[1,1,2\] **Output:** 2, nums = \[1,2,\_\] **Explanation:** Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). **Example 2:** **Input:** nums = \[0,0,1,1,1,2,2,3,3,4\] **Output:** 5, nums = \[0,1,2,3,4,\_,\_,\_,\_,\_\] **Explanation:** Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). **Constraints:** * `1 <= nums.length <= 3 * 104` * `-100 <= nums[i] <= 100` * `nums` is sorted in **non-decreasing** order.
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
Array,Two Pointers
Easy
27,80
279
Welcome back to our new video and today we are going to watch Perfect Square so as usual we will read the problem statement first because people have said that the solution lies in the problem itself so let's read the problem again. You will find your solution so you have been given an error and return the list number of perfect square numbers that sum to an ok size. Must be even up to a and at the least number of. Okay, so now that you understand parity. Okay, so let's say what is a perfect square, which is the square of one becomes the square of two. So, what is this, it is a perfect square. Okay and 16, now what do you want to make by mixing these, you can take a and one or two twice, like you took four, then you took one, or what is made, okay now you will notice one thing, you neither have this thread, so I do n't need them, I don't need them, I alone is enough, I don't need them. 10 re f and this is our own 10 re f so if I consider it as a perfect square then it will come to me as 10 rate which is our own 100 ok then we can take 100 numbers till here which will be 10 because above that it is its If it is not there, then there is no need to go there, Apna, now how can we do it, let us see Apna, first forget all this, you forget whatever you have done till now, okay, now Apna comes, if A If Apna is zero then what will be the answer? If Apna is obviously zero then what will be your answer? If Apna is at only one, then Apna knows that if the next one is a perfect square and a four, then do not juggle with the one less than this. If necessary, let's make our jugaad by doing 1 pv, A = 3. In this, bheev pv psav, it is a jugaad of three. A = 3. In this, bheev pv psav, it is a jugaad of three. A = 3. In this, bheev pv psav, it is a jugaad of three. A4, here apna knows that apna can be done like this, brother, why should I divide 1 psv pv but, I have four already. So if I don't do this then I will just replace it with four, then how much will its count be? This is not a count, don't get confused, this is your count and actually this is your answer too. Okay, now coming to A5, let's come to A5. So make it 1 p, one, this is another four, you already have one, you can make your four in one, so what will you do with it, if you make 1 p 4, then what is your answer, this is the count, okay, so this The question is now, if I observe from here, okay, then what can I observe from here, my perfect square is 9, 16 and 25, what are these, the perfect square will be beyond this too, okay, so n has to be made from these. I will try to make A from One. I will also try to make A from Ch. I will also try to make A from N. If let is equal then I will try to make Se. Is it not yes because if Y is more than perfect square then Lee will not be made. It will not be equal, if it is more than this, then whatever is less than this, I will go to that place and try all the combinations, so what has become of my function has become of A's perfect square, now square, perfect square, now what is the perfect square of A, whatever is it plus In the function of a minus perfect square, why now like a is our own and we have taken four perfect squares, so we have no one left, now we have to solve our one, okay, so the perfect square is like four, whatever is their count. It will happen, right? You stick four on Y, there will be only one on Y, it is okay because that four is the only one, 4 P, one, it will be even, it is ours, so this is the count, so our method is done in a way, now if it is ours If you look carefully, it is recursive, obviously, okay, if it is recursive, then it will obviously have a base condition. If you read Ric, then you will know what happens in Ric, it gets reduced, it goes on like this, Ric. Now there must be such a point too. There should be a place where one can say that enough is enough, then this meaning will go back to its origin, neither is the point left by brother, nor do they tell us what it is, one, they said that n is equal to 0. n is getting less and less n will be less every time n will be zero also there will be one anything can happen n will be less than zero also we will discuss that also n is equal to 0 then zero answer is now n is less than zero So what will you do? First of all, if -1 comes in the function, you do? First of all, if -1 comes in the function, you do? First of all, if -1 comes in the function, then it is not valid, it is non- then it is not valid, it is non- then it is not valid, it is non- valid, so now it is non-valid, so it needs some valid, so now it is non-valid, so it needs some valid, so now it is non-valid, so it needs some identification so that it can tell whether it is not valid at all, then this is the condition. I will do that, I will define it from the maximum range of int max to int ger. I will tell you why I will do that. Now I have told you that brother, I have to pick the minimum from whom I have to pick the minimum. This one is the one with the perfect square. Whichever function n will be in plus, which is n minus perfect square plus whatever was my previous result of this, whichever of these two is the minimum of function n, I will pick it, now I will pick the minimum, so if it is valid, then if I integrate it with let's Let's assign max to it, let's make it 'int max', then it, let's make it 'int max', then it, let's make it 'int max', then obviously the valid one will automatically get picked. Okay, if I make it 'int minimum', then if I make it 'int minimum', then if I make it 'int minimum', then what will happen in this method is that ' what will happen in this method is that ' what will happen in this method is that ' minimum' will be the minimum pick and the non- minimum' will be the minimum pick and the non- minimum' will be the minimum pick and the non- valid one will be picked. When you sit, always keep in mind that when there is a non-valid condition in the recursor, that when there is a non-valid condition in the recursor, that when there is a non-valid condition in the recursor, then you should keep something like this, if it is a minimum then keep it maximum, if there is a function of maximum then keep it minimum. Okay, so you have to keep this in mind. Now give us a little recursive tree. We also understand that it is okay like we have five, we do n't take five, we take ours, we come late, so we take one, first it will be sen, after that it will be six, which means I have taken a perfect square one. Okay, here it became five, it became four, it became three, it became one, and it became zero, he will say from here, this is my own, that is this, when he returns from this, then I will keep increasing it also. Why is it not returned or will it be done by coming or will it be done as soon as it comes or will it say when I am taking the perfect square, I have taken the perfect square then I can take the next one after that also, the one with four cannot be taken because If the no one is bigger than this then I will take the f one, now if I find the four one then I will get fo. Okay, four is my perfect square, after that I will take four again, so this is zero, now it will return one plus one here. He will say that I will make it into two, this is saying, from here I am making it into eight, from here I am making it into two, so which one will I pick, you tell me, obviously I will pick the one which will be more beneficial for me, okay I have to pick minimum e, my profit is here so I will come here now like this is going to be seven, now it is not like this in Rikers that when you do it in seven then in this also you will have to do one and four, so in this there will be three and then Later on, you will not have to do three after that, you will have to do one here, you have already solved the three here, okay and this three, you will come here again, this was Jov ji, if you see this one, I mark it like this. If this one and this one are fine, then if you have calculated these two or are calculating them again, then what will happen to you, if your time is unnecessarily complex, what can you do that these three are called solve? Keep doing it brother, when you are done then take an array and store your answer in number three, what will happen when I come to number three next time, I will check in that array that my answer is stored in that array. Or not, if it is stored then I will leave from here itself. Now, those who know recursion and have some knowledge of dynamic programming will understand it very easily and those who do not have knowledge will have to understand that like you have solved these three. You can do it here, there is no problem in that, but what is actually happening is that the time you are wasting here, you have not wasted time here but here you are wasting time. Obviously, because here you have already calculated, then you will store it in the array and return it directly, brother, my answer is like here three came late, here as soon as three came, it will return three right away. Now is the next time, when will P come here, when will the four section open, let me change the color of it, here P two will be four, if perfect, now this two one too, it has solved it, look at this two one is on Y. If I have already solved then I will return the second one as well. Whatever answer I get from here, I will store it here. If the answer is late then I will return it like this. Let us see it from the code. I have also written an approach for this. We will see that also and let's see that first, so actually tell me first of all what I did, first I made a big mistake like he is a nine, no sorry no, my test case is I think 12 so what did I do I thought that my perfect square is 149, okay 16, I want the minimum, okay, I put my mind to it, I said, if I want the minimum, then I will pick the maximum, it is like nine, and after that, I will pick the maximum of whatever is left. So, what was my result due to that, 9 pv, so this was my greedy approach, I got greedy, that means, later my answer was returned as four, but I saw in the solution that brother, the answer is three, after that I found out. That Greedy will not work here Then after that I tried to sort the problem a little that brother if n is equal to zero then my answer will be zero A if it is less than zero then he said minimum pick If you do, I will say that it is not valid, then I will assign the maximum to it, now whatever happens will be seen, okay, after that I calculated a formula, that was function n perfect square plus function n minus perfect square, okay so this What is the perfect square? Whatever is your 149, if you have picked it once, like you have picked four out of eight, then now you have four more remaining, right? Now you solve four and it will continue like this. Time p will either be zero or less than zero. If it is zero then return zero. If it is less than zero then return int max. Okay then let's come to our perfect square of our judge's which is square or basically perfect square whatever it is. Their square is and should be smaller than I have to solve the problem by approaching it again. I have discussed the function. I have also seen its tree. So now I have written its code. Okay, so tell me how I wrote its code. I have created a function. Solve n. If n is zero then return zero if n. Is less than 0 return integer dot maximum value ok, this is non valid, after that I assigned maximum value to an answer because I mean minimum, ok now answer dot math minimum answer which is updated. I will do it 1 p solve n minus this is a perfect square one second guy hello okay no problem so okay guys let's continue to this which comes in aa hai apna this is a perfect square and isko I break it one by one I will go and why is it one plus because like if I take four then my count will increase by one, okay so as I submitted it told teel and why did it tell tel, it discussed because I am doing unnecessary computation here. Whatever I am doing, I am going to 3 again, so what will I do now? Now this 3 one, will I optimize it? I have taken an array, first gave it n+ 1 size taken an array, first gave it n+ 1 size taken an array, first gave it n+ 1 size and refilled it with -1, meaning -1. That and refilled it with -1, meaning -1. That and refilled it with -1, meaning -1. That it has not been computed yet, like it will be computed, I will assign some value to it, okay and if there is no minus in it, that means you have filled it, then you will return it from there, you will not go to the computation, so if you go to the previous one. If you look at the code, one 2 3 4 and there is a little modification in this line, then four new lines are dead and one is updated and its time complex is of n * this √ n is fine, this r will go complex is of n * this √ n is fine, this r will go complex is of n * this √ n is fine, this r will go till n, so this is its time complexity. Okay, now I will convert this into iterative code. Okay, let's see how to do that because whatever questions there are in dynamic programming, they can be answered with our recursion and the iterative solution can also be done with a loop. So if we do it with our loop then first of all we gave size n to the memo and then filled it with maximum value because I mean by minimum if minimum is asked then assign maximum and if maximum is asked then fill it with minimum and my joe. The base condition was, I filled it that Memo G0 is equal to 0, after that I iterated to A. My recursive function, you will see, has also started from n and is going from n to zero, so it will also go from 1 to n and end. This is my inner loop, this one is ok, it will remain the same, this is the current value of memo plus 1 pi minus whatever is the perfect square, that is ok so those n plus the perfect square one which is minus. Will do from that current element and which is the current element and will build our one by one till one to A is ok and I have assigned it then after that I will return memo to A and I think it's guys so if you like the video Please do subscribe our channel and I would like to tell you one more thing, if you have unbounce neck or a coin problem, if you have read it, then it is almost similar to it, how I tell, then what happens in it, I have given you an idea. And some coins are given in the tooth. If you have to find out the sum from the minimum coin from these coins and make the sum, then how is this problem related to it, I will tell you that the sum in it is our own and the coin in it is Let's say a in this our perfect square is 4 na 16 25 these up to our 10th photo and what is its size, do n't be so surprised, its size is only 100 isn't it because it is a square of 100 so this is up to 100 now these are ours. If you want to mix and make A, then you can do that also and you will be surprised that this is the same question, that is, the solution that I have written, it is related to this, Unbound, I have said, it is okay, so I think it is guys keep working. And Keep Solving Questions Thank You Bye Byam Bye Tata Good Bye Gaya h h h
Perfect Squares
perfect-squares
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`. A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not. **Example 1:** **Input:** n = 12 **Output:** 3 **Explanation:** 12 = 4 + 4 + 4. **Example 2:** **Input:** n = 13 **Output:** 2 **Explanation:** 13 = 4 + 9. **Constraints:** * `1 <= n <= 104`
null
Math,Dynamic Programming,Breadth-First Search
Medium
204,264
1,326
Hello friends, welcome question number 1360 number of text open two water garden, how many steps should be opened so that the entire garden is covered, let's see during plus one tap, basically the garden is from zero to the end, if the size is five, then the garden is ours. It is from zero to five and each index is a tap and how many taps to open and so that when the entire garden is done and there is a range that which tap can see how far water we can see a range, let us open a given test case and understand. Let us take this question of Read and Agree, it is for every level and this question was suggested to me and Aman Manocha ji had said that please consider the video on the list as 13 266 approach, you may want to see similar questions. So jumped into the list is on the court, I have also made a video of the same to the same questions, if you do that question then you can also do this, if the admin does this then you can cover all such questions that in this you will get more information. Come, you will see this modification, it is very simple, when we come to the game, we come to our garden and the garden is given some kind of input, this is our garden and if I have seen the garden, then let us understand basically what is indicated. Total if seen in this is zero 12345 inductive then we have every end expect app which means tips to the garden, we can give water to the garden by using the app. There is every end expect app and a range is given. What is the range or zero. There is a tap on the index, it is actually free, so its value means it is free and can cover the distance, if it gives water, it can cover three distances further. Similarly, if I told you, there is one more index, value-2, there is Similarly, if I told you, there is one more index, value-2, there is Similarly, if I told you, there is one more index, value-2, there is lineage on the index. That point express which is the five index number, we have to find out the minimum number of tattoos to open, how much tape should we use so that the entire garden is covered, let's start with zero tape which is here, so it will cover our free distance. If there is water then there can be water till here and this is the one which has been said that it is said that the left boundary is told that the water which is there can be given till Mind IS-Ranger and if I can be given till Mind IS-Ranger and if I can be given till Mind IS-Ranger and if I + range came then I have made it I+ range. + range came then I have made it I+ range. + range came then I have made it I+ range. Means Jatin ahead. You can take up to three, it may hurt your back, but negative. This is my garden. It starts from zero, so I am not using it here. I am not writing. I am not making it. Okay, let's come next. The tap on the indicator on this one is mine. And water can cover the for distance, so if you take the folded distance from here, then the eco distance post is OnePlus 4 reaches up to here, meaning the warning expert is that it can cover up to here, what have I done wrong? And similarly, how much can it cover behind, what information will it do behind you, it will do index - range means information will it do behind you, it will do index - range means information will it do behind you, it will do index - range means one - do, so it can cover behind - 13th, one - do, so it can cover behind - 13th, one - do, so it can cover behind - 13th, but right now we are not looking at the rear, we do not need it. And the tap on the top of Induct, I quickly write that one distance is covering two plus Vansh is free, whatever is on the industry is plus one four, so it is covering till here, okay, now on index four. Coming to the one which is zero, the tap is on index four, it is starting here and this is where the water is neither ahead nor behind the favorite and similarly, the water which is on index five is up to this point, the water is regional good, okay, so this is the diagram made and in this You minimum number What can you say Minimum number tap If I say then if I take 1 top of this and this at a time then the whole garden is covered If I take the first and if I take the second then the whole garden seems to be covered to me Basically, I do n't know, it reports till the back, so my tap of index 54 is going forward to the plus and going further back, so basically one tap is enough for me and similarly this is the tape. My plus three is going forward, plus three is going backward, but the second step is that plus form, it will go forward, plus 4 - and if it goes backward, then it is behind forward, plus 4 - and if it goes backward, then it is behind forward, plus 4 - and if it goes backward, then it is behind or till it is covered, so my last second is sufficient, so I will say brother, this There is one tap, it is covering the entire garden. I did not make the back part but you can see that it will go till the negative. It is good, okay, I will write down once what is whose range. The range on the zero index is plus three. This is the distance to be covered further - it is free basically zero is going six covered further - it is free basically zero is going six covered further - it is free basically zero is going six pips behind also so let's do one thing - pips behind also so let's do one thing - pips behind also so let's do one thing - write woman and we write this is going three defense ahead of zero, let us write three, this should be our range. Ok now let's come to the second range secondary inch what happened index 104 is going forward and going back so I write now one - phone will go - 13th will go back and till further - phone will go - 13th will go back and till further - phone will go - 13th will go back and till further we see then oneplus will go up to 5 basically If the hero is touching then we have to cover it till zero. The garden one is in minus no but while writing inches and if you see from zero the water is covering the entire range, one tap alone is enough, we will open the entire garden quickly. I take the range, this video may be a little long but can be submitted. If you come to the second index then two minus one is one and two plus one is of 153 news or after that you will get the third index then 3 minus one is our two. f3 plus one will cover which is up to the floor and ours which is 4500, it will start only for four taps and it will give water only till four, it is a useless type and can spoil and it will start only for five and it will give water only for five. One and a half okay what was this if I say this is the ride point we calculated this is I gave us the plush rangers and Range is this is the range we did this so intact matter of candles on one we folded so I plus and we did and Family, if you see, there is the left front, what is that? I - Rangers I, that's it, we understand which one you come on the daily, direct, how to select one, so see, first of all, we are from top 10 only. To start, if you want to do garden roast, then look for a range in which 10 is included because first we select from the pictures and select the maximum, which one is starting from 1000 and cover that maximum. Okay, so all these are four from zero. No, this tap is reaching to the gang, it is just these two types which are reaching, so basically I assume that I picked up this tap and this tap which starts from zero and which is going to maximum, then both start from 0. But the maximum is going to be my skin, so now the pick I made is - 3 - 3 - 3 or I will take it to 0 minimum, the minimum I take is zero, now it is - 3 so I take is zero, now it is - 3 so I take is zero, now it is - 3 so I don't care, starting from 10 and the maximum. He is covering the maximum pipe, ok, this top five is covered, so we have taken the first pick, now what to do, the village does one thing, let's say the size of the garden is tan, I give it a tanker, then I will come here. I come to the neck line and I want to see that I have picked till the pipe, now I want to see something like this, whatever will be the minimum, I want it to start from five and then I have to find which one. I am covering the garden which is going till the maximum and my garden is of tens size. As soon as I complete 10th class, I have to stop it, this is my work, so now I have to be next, is there someone who can start me from five. And at least extend it a little further till the time without panchayat, so we have selected these two, now we see that as your minimum balance was zero when you started your protest, then that is the maximum of your job, right, you will make 60 from there. So in a way, that has become the minimum for you, so we will start with these five, so this time we will see which is the range, first we did a complete scan and found out this range, if one way of looking at it is complete, we took out all the rallies by placing four cloves, so basically you In the next week's content, we will see who were such jobs which are at least five or less than five but can reach further. Okay, so this five is less than f5, this is also less than 525, this is also less than 505, but this Everything had already reached me till 5 or is it not saving me also got this I have work from 2525 but before it is taking me till now I got arrow this range valleys of which is less than 505 but it is taking me till idli stand so I will select this account. I selected the first one - from 3 to 6 - from 3 I selected the first one - from 3 to 6 - from 3 I selected the first one - from 3 to 6 - from 3 to 5. Now I got the second manager. I thought that if someone gives a strict five to send it home, if he gives 10th then the work will be over, so I set that It is saving me from four till the end, now I saw that if we reach 10:00 then we just use this two taps reach 10:00 then we just use this two taps reach 10:00 then we just use this two taps and the answer is our you have come, open the tap which was there, if I open two then the whole cover will be done. Pick this contact and code it, use the same logic, the code will be very simple, there will be no much difficulty, we have to start from the minimum by taking zero or the maximum air is nothing of ours, we will take out the maximum because this maximum was manufactured in this fabric. I had done this and now my maximum is starting at zero, I will keep updating the maximum, and one thing, what do we have to take, how many taps will be opened, then okay, how long do we have to work? Well, the size is five, it is Airtel, it is the size of the garden, the size of the gang. Once we reach our maximum, we will have to keep velveting in the smallest till the maximum, like this is a garden, if we reach here, we will stop our work, like you saw, we will be till the first, this time it was like I We have stopped our work, we will do the same to the same, we are now moving forward after making the body, now let's start, we have to put the loop, do the first scan of the village, ok, Rangers, ok, and what will we find in the first scan, what do you think we will find? I had already told that in the beginning this athlete will start from zero, whether to start from zero and what is the maximum that can be reached, then both of them were starting from valid 30 and out of these, the hydrate was going, this you had told earlier. If you have picked then pick first friends. Okay, how will you pick one percent? This is the Rangers. Come, this is our athlete. Minimum minimum should be small. Minimum should be 080. If it is smaller than that then there is no problem. If you contact 380 then it will be a problem. Need condition and condition which is my play store rangers this is our which but it is greater than I mean gold should be taken out this is the max and once it is found in the first scan then we will update our Mexico that our new which is Max is made, that is made, so here if I see Akbar below - 3 and whatever is max, it will keep updating me - 3 and whatever is max, it will keep updating me - 3 and whatever is max, it will keep updating me and I will get the first range. Okay, so basically Mehak, take this tape case, so both of these are under control. What was happening was that both of them were less than zero, both of them were races which are satisfying the conditions, so the one who is going to the farthest is going to be five, so my Joe Mexico is updated till five. It will be okay and this is my max, I got it, the first scan is done and we got a tap which we are going to open, okay what is this for loop doing, this follow which I have run, basically it is doing that one. Take out the range and show it is like four cloves. He gave me the range - 370. Grandma, okay, He gave me the range - 370. Grandma, okay, He gave me the range - 370. Grandma, okay, so what did I do? I said, let's arrange one, so we got one tape, we did that, we got one tape, okay. We have found a tap, now what do we have to search next we have to search our Ranger 510, the first range in the house has been found right from zero, which is at one end - 305 Meena, now I will - 305 Meena, now I will - 305 Meena, now I will start from the least five that here If it gets reduced to 5, then I will look for 510, so 510, I am getting all these in less than five, but on the right side, they are smaller than white, that I found a range which was less than f5, Meena, and actually it goes till further. I mean, I was going to go ahead like this, so I picked the range for Saturn, so let's see how to do it in the loop, what will I do in the second time, once and understanding this below, now I will see the maximum is five, I am ranger from ahead. Abuse again, the minimum will be five now, my Muslims will be updated and I will click on the next range, then do the same as mentioned below here, update the minimum which is your minimum, now it has become five, whatever is further you You will see the race as far as it will go from the least five or till here, now we will scan the neck, then we will catch this range, we will follow it once more from five and all the ranges we get will remain so tight open but as soon as we get this tan Khurram had got the last time in the range. Once Khurram got that time by his neck, he was upset brother. Now don't scan. You have scanned twice. It is enough so you don't have to scan. It's just this code and you can't do it. If you don't understand then try repeating once more what I have said below, the same thing I have written above, just do not do anything with this product and finally what will you return, how many taps were opened, you have to tell us if you returned the phone, how many taps were opened. See this happened brothers, it was going on till this volume till the size of our garden reached less. What did the first scan find? First scan found rally - 3 to 5. Then we started searching rally - 3 to 5. Then we started searching rally - 3 to 5. Then we started searching from five onwards. Take a second in the second virus scan in the range, if we got the range from four to 10th, then our work is done, we got the range from four to 10th, our work is done, so all we have to do is to do this and do nothing else that one base and Handle it, they have said that you are seeing that even the cotton notes are worded, they return minus one, so that gas can be tested with such a test that if you see, you can find such a deficiency case when our vegetable which is What will happen to us if you have this, if the minimum is visible to maximum then it is not possible, if we did a complete scan and it came to maximum then now return - call and came to maximum then now return - call and came to maximum then now return - call and basically set it, rest nothing has to be done once. Let's try coloring, I remove all this and check, friend, if a compiler comes, we will mix it, here is winter, it is difficult, 10000 small mistakes keep happening, so then let's scan once. We submit it is accepted and we check whether there is any mistake or not. Successful submission is happening and it is very easy. If you understand the approach, then this code, I think it is It is a code of very few lines, it can be easily said that it is not a very long code, after calculating its final bus tap, applied this simple logic and also look at our code, it is a little fast, one millisecond health is 60%, if the code is shortened a little. If health is 60%, if the code is shortened a little. If health is 60%, if the code is shortened a little. If you want to optimize further, then you can do one thing, start from zero, again and again we are doing full scan from zero, then you take each Bolero index and make the index zero, that is, start from zero. Let's do it and once we cover the old steps, the back one, then we have to run the loot again from zero, we can run it a little further in the garden and from the front tape, so if you update the index, then the loop. Some attractions will increase in this, it is a simple mode of question, there is no need to explain much in it and if you submit then the performance should get a little better, then you will see that earlier this was our code which was giving eight seconds, eight milliseconds and taking fiber. Is Faster Than Sixty Percent of Verses Done So that's it and I would like to give credit for the concept and score to Ashif Isnai, he has written this solution in the list court, I did not get any star or any thumbs up but I found it to be a very good solution. I would like to give credit to Shawn Chapman, thank you very much for the solution, see you in the next video, thank you very much.
Minimum Number of Taps to Open to Water a Garden
sum-of-floored-pairs
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-indexed) means the `i-th` tap can water the area `[i - ranges[i], i + ranges[i]]` if it was open. Return _the minimum number of taps_ that should be open to water the whole garden, If the garden cannot be watered return **\-1**. **Example 1:** **Input:** n = 5, ranges = \[3,4,1,1,0,0\] **Output:** 1 **Explanation:** The tap at point 0 can cover the interval \[-3,3\] The tap at point 1 can cover the interval \[-3,5\] The tap at point 2 can cover the interval \[1,3\] The tap at point 3 can cover the interval \[2,4\] The tap at point 4 can cover the interval \[4,4\] The tap at point 5 can cover the interval \[5,5\] Opening Only the second tap will water the whole garden \[0,5\] **Example 2:** **Input:** n = 3, ranges = \[0,0,0,0\] **Output:** -1 **Explanation:** Even if you activate all the four taps you cannot water the whole garden. **Constraints:** * `1 <= n <= 104` * `ranges.length == n + 1` * `0 <= ranges[i] <= 100`
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
Array,Math,Binary Search,Prefix Sum
Hard
null
1,486
my name is I am currently pursuing my bet degree from P School of Technology I am currently in my second semester and in my first semester I have donear some programming languages like Java JavaScript stml CSS to intermediate level and I'm currently solving some DSS DSA problem um in lead code and in this video I'm going to solve two easy level deod problem so let me share my screen first so in this video I'm going to solve two easy level deod problem so first uh the name of the first question is relative ranks the question is given an integer score of size n where score I is the score of I athlete in the competition all the score are guaranteed to be unique so we have been given an array of integer of size n and the element of the array is the score which are unique uh it means not any Two element is repeated so the athletes are placed B on their score where first place athlete has the highest score second has the second highest score and so on the placement of each athlete determine their ranks the first rank athletes rank is gold medal the second place athletes rank is silver medal the third rank athletes rank is Bron medal for the fourth and nth the for the fourth to the nth Place AET to their placement number IE X Place athlete rank is X so we have to put the plus the maximum score um element to the gold medal assign gold medal on their position and that second uh and the second maximum score uh to Silver metal and third score to third maximum score to bronze metal and the rest of them according to their uh rank so basically we have to just return the array answer of size n where answer I is a rank of ithlete where the first rank will get the gold medal second rank will get the silver medal and third rank will get the um bronze medal and the rest of them will get according to the and return and string AR of string with their rank as the ment so in this example one we have a score of AR score the element is 5 4 3 2 1 so we can clearly say the five is the first Str so we are going to give you um gold medal after that four is the second rank then silver medal three is the third rank then bronze medal and the two and one is four fifth rank so we are going to uh give it four and fifth uh as and as a string not a number not integer so in this example to as uh it is clear that 10 is the first rank so we are going to give him gold medal after that three is the last I think yes three the last so we are going to give him fifth eight is the third so we are going to give him Brown uh and N is the second so silver medal and four is the fourth so fourth uh four rank so that's how it is happening so to solve this V I have written a code here so as we have to return it in string array and we are uh we have been given parameters of uh of an integer score so first we are going to uh store all the elements of score in a new array so I created an array and uh score do clone and clone all the element of score on this array by using do clone after that I have sorted this new array so we will get the if we take elements from the last place we will get the first position and after that second position after the third position that's why and after that we are using hashmap and integer as a key and string as a value so we can put the element of score in string and what should be the value of that uh rank what is the rank of that uh element in string because we have to make it an string ARR after and name it map and initialize the map hashmap and I created an I've created a variable of interior type and assign the value one to it because the last place should be the first Rank and after that I run a loop and initialized with the last base of the array which is ar. length minus one because the index is started with zero so the length of the um the length of the array minus one should be the index of the last place and given give a value to it which is I should be always greater or equal to zero and until this value satis until this condition is satisfied the loop will run again and each time the loop runs the value of I will be decreased by one and inside the loop are given a condition by using if statement which is if rank equal to one equal one which means if rank will be one then we will put inside the map what will put which is the element of array which should be the largest number and gold medal to it as value because the largest number should get the gold value largest score should get the gold medal and after that I used if lcf statement which if rank equal to then we will put inside the map the element of uh the element of the array which should be the second largest score and assign the Val silver metal to it and after that I used another L if Loop and uh given a condition rank if rank equal three then we will put uh inside the map the element of score as the value and uh the element score as key and bronze metal as value of that score so this element should be the third largest score and after that we will put the uh element as the key and convert the rank of that element into integer by using integer do value of and put uh in the value of hashmap and each time the loop runs the rank will be increased by one so if the if I should be the last place so if we take rank one then this condition will run and the largest Val value will be given to uh hashmap and the value will be assigned gold medal to it because we have already sorted the array and we are uh taking the element from the last so the largest elements would be in the last and second largest in the second last and so on and after that I have created an array of string and uh the length of that array is score do length which is the same as the which is same as this length which uh which is the length of the uh parameter array so after that I have run another loop from I is equal to 0 to uh I should be always and given a condition I should be always smaller than score do length until the condition is satisfied the loop will run again and each time the loop runs the value of I will be increased by one and after that I have put all the uh all the elements um in this is the index of the array which is initially assigned with something else which will be updated by L.G score I so which will be updated by L.G score I so which will be updated by L.G score I so score I will be map. getet is used to take the value of that map of that element which is put inside the get bracket so it will give the value of the this element and store in into this array and after that we will return the array so let's run this first so as you can see it accepted our code and if we submit it got submitted and beat 78% of the user with submitted and beat 78% of the user with submitted and beat 78% of the user with Java so the time complexity of this code is linear and space complex it is also linear because the because of hashmap because we are putting the value in hasn key also so this is how I solve this question and the second question is zor operation in Array so we are given an integer n and an integer start define an array in Define array nums where nums I is equal to start + 2 nums where nums I is equal to start + 2 nums where nums I is equal to start + 2 into i 0 indexed and N is equal to nums do length and return the BET zor of all the elements in nums so in this question we have basically given an integer n and another integer start so we have to give the output of zor operation by uh as uh we have to start with uh zero and after that we have to increase the value of start by two until we have taken five elements as 0 2 4 6 8 which is five and we have to perform zor on each of the element and after that we have to return the result here so to solve this we have to first um as you can see we have to return an integer data type value and we have been given n integer of integer dat type and the start of inte type so first I created a variable R and put of integer dat type and put the star in it after that I have run a loop from I is equal to start + two because I have is equal to start + two because I have is equal to start + two because I have already put a start in RS that's why I have I am starting with start + two have I am starting with start + two have I am starting with start + two because the start is already in this that's why we don't need to use start because start is already inside the RS and put the condition is I should be smaller than num into n into 2 plus start so n into 2 plus start will give the uh exact element what we need uh as say here we have five so 5 into 2 10 + 10 + 0 which is 10 so I should be 10 + 10 + 0 which is 10 so I should be 10 + 10 + 0 which is 10 so I should be smaller than 10 which is which will take us to i8 that's what we need as 0 2 4 6 8 and we will increase the value of I by two each time the loop runs and the loop runs until this condition is satisfied and until this condition is true the loop will run again and after that we will use zor to RS uh so RS zor equal to I which will also be said as RS equal to RS zor I so first RS and zor will be calculated and then the value will be put inside RVs and after that when this Loop runs inss we will return the value of RS so let's run this code as you can see it accepted our code and if we submit it also gets submitted and beat 100% it also gets submitted and beat 100% it also gets submitted and beat 100% of the user with Java so the time complexity of this code is n and space complexity is constant so thank you this is it for this video and thank you for watching
XOR Operation in an Array
find-the-distance-value-between-two-arrays
You are given an integer `n` and an integer `start`. Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`. Return _the bitwise XOR of all elements of_ `nums`. **Example 1:** **Input:** n = 5, start = 0 **Output:** 8 **Explanation:** Array nums is equal to \[0, 2, 4, 6, 8\] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8. Where "^ " corresponds to bitwise XOR operator. **Example 2:** **Input:** n = 4, start = 3 **Output:** 8 **Explanation:** Array nums is equal to \[3, 5, 7, 9\] where (3 ^ 5 ^ 7 ^ 9) = 8. **Constraints:** * `1 <= n <= 1000` * `0 <= start <= 1000` * `n == nums.length`
Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn).
Array,Two Pointers,Binary Search,Sorting
Easy
null
111
yo what's up my little coders let's solve today delete called question 111 minimum depth of binary tree here's the example which they give if that's the case we just return to because the minimum depth is equal to 2 right so 1 plus 1 is equal to 2 and we return 2. um let's code it first of all let's check for the base case so if root is equal to now in this case the depth is just simply equal to zero that's why we just simply return zero now imagine the root is not equal to now however for example the left sub tree is the photo now if that's the case we cannot check the left sub tree anymore however we can check the right sub here right and we just simply return one plus we will co recursively this function again on the right subtree and same thing for the right sub g in case if right sub g is equal to now we just call this function recursively on the left subtree now and we do one plus so we will keep calculating we just you know go step by step and calculating the depths however then also we have another option if both left subtree and right subtree are both not equal to now in this case we want to actually return the minimum depth and we want to do it recursively reversing until the end both left subtrees and right subtrees so we do just return one must dot min and we consider the left and right subtrees and we do it recursively again makes sense right let's run to see if it works it does work um let's submit now perfect guys it was delete called question 111 please subscribe to this channel and remember lead code today keeps unemployment away so delete code and eat apples see you
Minimum Depth of Binary Tree
minimum-depth-of-binary-tree
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. **Note:** A leaf is a node with no children. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** 2 **Example 2:** **Input:** root = \[2,null,3,null,4,null,5,null,6\] **Output:** 5 **Constraints:** * The number of nodes in the tree is in the range `[0, 105]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
102,104
146
hello and welcome to another Elite code prom today we're going to be doing lru cash and so in this problem we're trying to design a data structure that follows the constraints of a least recently used cache and it's going to have a size it's going to have a get and a put where it get will get the value of the key if it exists otherwise negative one put will either update the value of the key or insert a key value pair and we need to make sure that we have the right capacity and they need to run into over one average capacity so what we're actually going to do for this is we're going to have a linked list for the cache and I'm going to kind of show you we're going to go through this example with a linked list so what we're going to do is we're going to have a head and a tail so it's going to be the head this is going to be the tail and we're going to be putting in nodes at the tail and evicting them at the head so the tail is going to be the you know most recently used and the head will be the least recently used so let's show you what that's going to look like so in our capacity here is two sorry capacity is two so first let's go through this example we're going to be putting in node one so it's going to have a key one value one we're going to always put in at the tail so we're going to say let's have a one and a one so let's do that right so key equals one value equals one we're going to make a node it's going to be a doubly linked list so it's going to look like this now we're going to put in a 2 and so when we put in a 2 remember we're always going to be inserting the kale and deleting at the head so when we're putting in a 2 what we actually need to do is we need to actually take this and move it over here so let me actually delete this I'm not going to show the um I'm not going to show the lines but I will show the actual you know node so hopefully this moves okay so but know that these are like connected and doubly linked lists okay so we have this one that we need to put in a two so let's do that so we need to put in Ka equals 2 value equals two okay now we access value one and so when you access value one these actually need to get swapped because now about the now value one was just used and so now every time you access something you need to go to the tail and so now well what are we going to have well we're gonna have to flip these nodes essentially right so let's do that so let's actually take this node Let's uh take this node move it over here maybe and let's take this node and move it over here now we can put this node and we can just move it I think whoops uh let's see here let's take it let's move it over here okay so now that this was the case here right so we returned one now it's the most recently used okay now we're putting in three our capacity is full so where are we evicting well we're obviously gonna have to be evicting from the front right we're evicting from the head so what we're going to do is we're going to evict from the head so this node is going to go away and now we're going to put in a three so let's actually redraw this again so we're gonna have a head tail now we're going to take this node and we're going to move it over here essentially so we're going to take this copy it and we're going to put it over here and now we put in a new node so we're going to put in a new node over here and that's going to be I'll change the color of that okay perfect so we're gonna make a new note over here and now this is going to be the three right so K3 value okay now what are we doing next we're getting a two so if we try to get a two there is no two so we need to return negative one okay now we need to put in four so what are we going to be evicting well we're going to be evicting this right so this is going to be evicted because that was the least recently used so we're going to be evicting that so let's do that let's evict this now we need to put in another value so let's actually give us some more space here so let's actually copy some of these down here so what we could do is we can actually copy this down here and then we're going to be getting rid of this node so let's get rid of this node we're going to take this node we're going to put it over here and we're going to delete it from here and now we're putting in a 4 essentially right so we're putting in a let's change the color of that so there we go so we're putting in 4 okay value four this is value three okay so we put in a 4. now we try to get a one we can't do it and then we try to get a 3 and we can do it but now that we got the three we need to put the three in the back because we just used it right so we need to swap these two essentially so we're going to do that so let's take this let's move it over here take this let's move it hours let's take this let's move it over here and then finally let's take this and let's put it over here and so now this is going to be our final list so you can see how you need to do these swaps so let's just go through every single operation and like what are the steps right and we're gonna have some helper functions so we're gonna have two helper functions here so we're gonna have one helper function it's going to be removed and what's that going to look like well let's take a look so if we have a head and a tail and some notes let's say we have a head and a tail we have some nodes so let's just say we have node one and two node three actually it's a little bigger no two no three this is the head this is the tail this is node 102 node three so remove is pretty straightforward we're actually going to store these nodes in a hash map and the hash map is gonna the key is going to be the key of the node so we're going to have a hash map where the key is going to be the key of the note and the value is going to be the note itself and so to remove a node it's pretty straightforward all we have to do is take the left and the right and we have to make them point to each other right so if you remove this node all we have to do is just make these two point to each other and that node is removed so that's how I remove this gonna work now let's look how an ad an insert is going to work insert is pretty straightforward as well and by the way so when we remove the node we're also going to remove it from the hash map right like we're going to have a hash map with every single node and then when we remove we need to remove it from the hashmap so an insert is going to work similarly right like let's say we have two nodes here and let's say we have the head and the tail again so let's say we have the head here with the tail here so inserting is pretty straightforward all we need to do is we need to get the tail and we need to get the note to the left of the tail and we're just going to insert right between them right so insert we're just going to insert straight into here and we're going to put in a node here and then we're going to add that into the hash map as well we're going to add the note into the hash mount so these two we're going to use over and over for our get and put and things like that and I'm going to show you how so we're actually going to figure out how we're going to do this get and the put right to make them Big O of one so for the get we need to check does the key exist so we're going to have a hash map with every key right so we can just check our hash map with keys and if the key does not exist we can just return negative one but if the key does exist so if you think about it like let me give you an example here so let's say we take this actually so let's say we take all of this and we're trying to do a get here and our nodes are labeled one two three and we're trying to get this node here so we can get it but remember when you do a get then that makes it most recently used so not only if you do a get you have to put it over here so let's think about how we could do that using our helper functions so a get is actually just a remove and then an insert right it's a combination of those if we remove and then we insert that's again right we remove this node and we put it in here that's what we wanted and then we return the value so again it's just a combination of a removing answer that's literally all it is and if the key doesn't exist we should return negative one that's pretty straightforward with our helper functions now let's look for our put what is that so if the key does not if the key does exist then so let's look at the cases right if the key does exist so if key then remove the value like remove the node essentially like let's go through this again right let's say we have our get or sorry our put so let's draw uh this like this let's just draw a head ale and let's draw three nodes so one two three so this is one two three so let's say we're trying to get two here and we're trying to update the value well to update the value you want to remove it and you want to put it here right because it's still most recently used so if it is there we're just going to remove it right we're removing and if it's not there we don't have to do anything then we have to check is our cash flow is cash full right so if the cash is full if there's too many nodes like let's say the capacity is three if there's too many nodes we have to remove a node so if the cache is full we remove where do we remove from the front right because lease recently used because the cache is full we remove a node and then finally we put in the node you know the new node over here so it's just a remove if the key exists if not do nothing if the cache is full remove right so remove from the front pretty straightforward and then finally put in node to the cache or to the yeah to the cash so let's look at our stuff one more time so we have a helper that will remove we will always be removing from the front right because the least recently used we're always removing from the front yeah we're pretty much always going to be moving from the front and to insert what do we have to do you could also remove from not the front like if you wanted to you could technically do that but we're usually going to be removing some part but regardless the remove is going to take a node and we're just going to take its left and Its Right point to each other essentially for the room so we're usually going to take the nodes at the front okay and then our insert or sorry we have our move we have an insert we'll always insert in the back and then finally our get is just a remove and an insert and our put is a removed if there is a node if not do nothing if the cache is full it's removed and then finally put in the new so now we have everything we need to actually write up the code so let's do that so we're going to first initialize the cache so remember we actually before we initialize the cache we need to since we're using a linked list we need to actually make a class for node right so we can just say node and then we can just initialize it so what is it what does it need remember the note's going to have the key the value the next and the previous and then we just say like self dot key equals key this is just pretty straightforward Constructor self.value straightforward Constructor self.value straightforward Constructor self.value equals value self.next who both next if it was self.next who both next if it was self.next who both next if it was provided if not make it none self.previous it was previous self.previous it was previous self.previous it was previous okay so for the init what do we have to do well we have to make a head in the tail we have to make them point to each other right like in the picture so let's do that the self.head equals new node it's going the self.head equals new node it's going the self.head equals new node it's going to have a key of whatever value 0 and it's not going to point to anything now we need the tail it's a new node selections to be node zero okay pretty straightforce needs to be over here all right now we need to make the tail Point To The Head and the head point to the Tails let's do that so self.pad.next the Tails let's do that so self.pad.next the Tails let's do that so self.pad.next equals self.tail equals self.tail equals self.tail himself.tail.previews equals self.head himself.tail.previews equals self.head himself.tail.previews equals self.head right that part's pretty straightforward then we need to have a capacity because we're going to be checking do we have is there is our cash flow or not so we're just going to make that equal to the capacity here and then finally this is going to be our dictionary of where all the nodes are stored where it's the key is going to be the key of the node and the value will be the node itself so that way we can remove it easily okay so now we need to write our helper function so let's do that so we're going to make a helper function over remove and we're going to make it helpful function of insert so remove cell node remember we're going to be removed from the front but essentially all we're doing is we're doing we're just making the next and the previous of the node point to each other so we're going to say let's just say let's take the previous of the node and say the next of the node it doesn't happen to point to each other right so previous dot next dot previous point to each other and that then now the node is removed we're going to handle we're actually removing it from the hash map in other places but and the same thing for the insert we're going to handle those in other places these recursive remove and inserts are just going to handle actually inserting it into the linked list because sometimes we're going to want to remove something and then put it back in another spot so we don't need to actually delete it from the hash map so for an insert pretty straightforter we're going to use a tail in the previous note of the tail so it's going to be previous next equals self.tail.grevious and then self.tail self.tail.grevious and then self.tail self.tail.grevious and then self.tail and we need to put it in between these two nodes right soft output tail previous and self.tail we need to put it previous and self.tail we need to put it previous and self.tail we need to put it right in between those so it's pretty straightforward so previous dot next and self.tail.previous equals node self.tail.previous equals node self.tail.previous equals node and then finally node.grevious and then finally node.grevious and then finally node.grevious no dot next equals the salt dot tail okay so this is actually XT hopefully I didn't make too many salami six other rest is going to be painted above that's okay so now in our get remember we're doing if the key does not exist we can just return negative one so if key not in self DOT locations where self-dollar location is going to have self-dollar location is going to have self-dollar location is going to have all the keys and the nodes just turn negative one and remember if it does exist it's just a simple remove and then an insert so we're going to say node equals self.locations key let's actually equals self.locations key let's actually equals self.locations key let's actually get the node let's remove the node let's insert the node so self-daughter move insert the node so self-daughter move insert the node so self-daughter move node itself.insert node to update it to the itself.insert node to update it to the itself.insert node to update it to the most recently used and finally we can return the value of the node okay so that part's done now we need to do the put so let's actually give us a bit more space here so for the put remember if the key is in there then we need to remove it right so if key in self-doubt locations self-doubt locations self-doubt locations we need to remove it so let's get the node self dot remove the node we're going to remove it from the hash Mount and now the rest of it is going to be the same code regardless of you know if the node was removed or not so we're going to remove it from the hash map here okay and now what do we do next well we need to check the capacities the capacity is too big we need to remove from the front to give ourselves some spits so self dot capacity how do we check if it's too big well we can just check for the length of self locations because self locations is going to be every single node so let's say self capacity is two nodes and the length of this is two nodes that means our cache is full so if our cache is full we need to be removing from the front right so that's pretty straightforward so what do we need to do here well we need to be removing from the front so we can call like node to remove what node are we removing well we're removing the node right after the head right so we're going to do self.head.next self.head.next self.head.next so actually just a small little air that I was talking about um so when we removed we're not always removing from the front because when we do these gaps we're actually removing from the middle right like if you get a note from the middle of the list when you're appending it to the end of the list you're actually moving from the middle so that's why our move doesn't necessarily move from the front this remove works for anywhere but now we are going to be removing movement in this case it's not just a small thing there and that's yourself dot remove we're going to be removing the node to remove right and now we need to actually pop it from the dictionary because it no longer exists so Paul I think you can use delete as well it's totally fine now to remove dot key so whatever the key of that is we're going to get rid of that dictionary other and we're going to get rid of the entire node now we need to create a new node regardless of if we had to pulp or not regardless of these two conditions so we're going to say node equals node key value and now our node is going to be good to insert because we checked if our cache was full already so now our cash is guaranteed to not be full so now we can put it into the dictionary so no dot key equals node and then we finally need to insert it right it's a self Dot and we have one final step and that's to pray that I didn't make any errors which I probably did so we'll see how that goes definitely not the smartest idea to be uh doing a linkless problem without having code done in like earlier but we'll hope for the best okay all right so now let's go and let's just check all our functions to make sure they're Big O one right so this remove is pretty straightforward we're just changing two pointers that's obviously bigger of one here same thing we're changing a couple pointers obviously bigger of one here if the note is not there that's big of one and then we're doing remove which is Big O of one and we're doing insert which is bigger one so that's the key we're reusing these functions and both of these are Big O of one and we're just getting it right away and we're moving we're we saved a step by using hashmap we no longer have to iterate through the entire link list which would be a big O of n so if you want a linked list but you need to get the items right away the way to do it would be a hash map and put the link list in them so you could also design a linked list like this where you could put the nodes in a hash map and then that would help you to get quicker deletions and insertions that would give you oh once deletions and insertions at the cost of using more space for the hash map so it's a trade-off thing okay now so with this trade-off thing okay now so with this trade-off thing okay now so with this get like I said is Big of one because we're just doing a removing an insert and now here we're also doing a remove Big O of one remove Big O one and an insert big old one and so all these are Big O of one and for our space is obviously going to be like whatever total nodes we have you know so like big oven however many total nodes we're actually storing in the list so we're essentially going to have them here and then we're also going to have the hash map point to them so yeah it's going to be a big O event all right so that's gonna be it for this problem actually hopefully you liked it and if you did please like the video subscribe to the channel and I will see you in the next one thanks for watching
LRU Cache
lru-cache
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`. * `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key. The functions `get` and `put` must each run in `O(1)` average time complexity. **Example 1:** **Input** \[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\] \[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\] **Output** \[null, null, null, 1, null, -1, null, -1, 3, 4\] **Explanation** LRUCache lRUCache = new LRUCache(2); lRUCache.put(1, 1); // cache is {1=1} lRUCache.put(2, 2); // cache is {1=1, 2=2} lRUCache.get(1); // return 1 lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} lRUCache.get(2); // returns -1 (not found) lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} lRUCache.get(1); // return -1 (not found) lRUCache.get(3); // return 3 lRUCache.get(4); // return 4 **Constraints:** * `1 <= capacity <= 3000` * `0 <= key <= 104` * `0 <= value <= 105` * At most `2 * 105` calls will be made to `get` and `put`.
null
Hash Table,Linked List,Design,Doubly-Linked List
Medium
460,588,604,1903
969
in this video we will look at pancake sorting algorithm so as the name says we have to do sorting we will be given a list of numbers and our task will be to sort them and this has been asked in facebook amazon microsoft and uber interviews so let's see an example so here we will be given one input array or list and the numbers here will be from one to its size so its size is four so numbers will be from one to four and all numbers are unique so if you have an array a of size let's say 5 then we have 1 2 3 4 5 so some permutation of this will be there in a and this is the output and we will see how to arrive at this output so in this problem what we have to do we are allowed to uh do one operation only and that's called flip and flip uh this is the original array a and if we flip let's say k then it means flip all the elements from beginning till kth index that is flip means reverse so for example we have 3 2 four one so here the first one is four that means flip till fourth element so fourth element is this one this output should be based on one best indexing uh but in the code we can think of it as index three so four is same as three index three because index starts from zero this is the expected format so this four means flip from beginning till fourth element so let's do the flipping so it's reversed so one comes here four comes at second place so read it in reverse direction one four two three this part is done next two that is first element second element so flip these two only so from beginning till here then from beginning till here so it becomes 4 1 2 3 remains as it is then it's 4 again so from beginning till 4 so it's 3 2 1 4 now 4 is at correct place next is 3 so 3 is this one so flip this part so it becomes 1 2 3 4 and now it's sorted so we will stop here and these are the flips that we performed 4 2 4 3. so let's see how we can solve it in general and here there is not a unique solution so what the condition is that any such list by flipping which we get a sorted array is valid but there is some condition that it should be less than 10 times its length so you are allowed to make at least at max 10 times its size so in this case 4 so you are allowed to make up to 40 flips and if that ordering of flips sorts the array then your solution will be accepted so let's see how to solve it so let's take a generic example first let's say we have an array of n elements so its numbers will be from 1 to n since it is given it will be some permutation of 1 to n if its size is n so what we will do we are allowed to make 10 times n flips that is if we flip it once and we get one of the elements at the right place then we are good to go in n flips we can do that or a few more than n not just n but almost twice then slightly less so let's see how uh so we will search for the last number so we know that numbers are from 1 to n this is guaranteed due to its size so we will look at where this nth number is so let's say n is here so note that index i so this finding will take owen time in this list so we took end time and we searched for n then uh what happens in flip let's say this is a bigger array and we flip from here to here so this part of the array remains unchanged so let's say our goal is to make this last element at its correct place then we will be bothered only about this remaining part so this thought is coming from how to decrease the problem size so initially the problem size is n elements uh we are trying to think how to make progress and then we are thinking what happens in flip so when we flip this part it has to start from beginning zero till that index this is the flip operation after that it's unchanged so what if i uh make the nth element put the nth element at its correct position then we will never be bothered about this one we can just focus on this part of the array n minus one similarly next step we will put n minus one element at correct place then we will not be bothered about this part only this part so we will be making progress in each step so how to put it here when we flip this last element comes it at the beginning so in order to move end to the last element or whatever is the first element it moves to the last index of the flip that part of the array where we flipped so only way to move in here is to first move into the first place and then flip this entire array then only it can come here nth element so this algorithm we will follow so first we will find where is nth element then we will flip this part of the array if it's at index i we will flip this part so in our result we will add i or if this index is from 0 we will add i plus 1. so this is now part of the result and after flipping what will happen n will come here and whatever elements are here they will also get flipped what whatever was the first element comes here and this part remains unchanged then we have to flip this complete array so that it comes here so we will flip n so after two flips n is here now as per our earlier plan our plan was to reduce the problem size so our problem size is reduced to n minus one in the next step we will find n minus one element that will take n minus one time we will only search in this part we will never be bothered about this so finding n will take n time in worst case then n minus one of the element n minus one time and again repeat the two times let's say n minus one element is here then first flip this part of the array and then flip the part of the array from beginning till n minus one as promised we will never go to this side so this will be our boundary uh but it may be possible that n minus one was already in the beginning so if index is in the beginning itself there is no point in flipping just one it will remain at that place only so unnecessarily why count the extra flips so if it's in the beginning no need to flip for the first time just flip the second part so there are two parts first bring this one here in the beginning and then flip the entire sub array with which we are concerned in the next step this will be gone and we will be concerned with this part of array so let's apply our this algorithm to the earlier example so it's three two four one so here n is 4 where is 4th element it's here so note this index it's 1 2 3 so it will be 0 one two but here we have to make the solution based on one based indexing starting from one so it's zero one two so it will be three and flip this part so it will be four two three and this is one next flip this entire part that is four and now it becomes uh four two three one next we will this part is done we are now bothered about this part only next we will find 3 n minus 1 so 3 is here so flip this part so it's 2 and now it becomes 3 1 and we flip just this part so this will remain as it is and next flip this entire part so it becomes 2 1 3 and now this part is done these two are at correct position three and four so fine for two is here so no need to flip with itself just flip this part that is two and it becomes one two three four and our algorithm works and uh in this maximum we will have two flips for putting a number at its correct place and in some good cases like in this case it was already in the beginning we will not flip so worst case we can have our 2 n minus 1 flips this is the worst case y n minus 1 because when we have done for n minus 1 times the first win one will already be at correct place if everything else is at correct place first one will also be at correct place so this is the worst case that is 2 n minus 2 which is well below 10 n which we are allowed to do so i hope this is clear run through one example again and it should be clear to you it's very simple and let's look at the time complexity here so searching for the nth element took n time then we had reduced the array size so then it will take n minus 1 time then n minus 2 time all the way up to 2 so 2 plus 3 plus 4 plus all the way up to n for simplicity let's add 1 also so it becomes n multiplied by n plus 1 by 2 that is of n square and space we have to uh return this list and it can have 2 n minus 2 elements so space is of the order of o of n and this space we anyway have to return something of the order of n so these are the time complexity so let's write the code for this if you have understood this writing so this code should be very simple so we do not know the result size beforehand otherwise we would have initialized it with that size so why we are starting from n minus 1 till 0 because first we will put the last element at its correct position and here this solution will not work the other way in many cases whatever whether you make progress from last to beginning or beginning to last both ways work but here this flip operation is defined such a way that you have to flip everything from beginning till that index so we are trying to solve the remaining part of the list so that we will be bothered about some prefix of that array so let's write the logic for searching so int j equal to 0 or if it's 1 so let's first write the logic for search j less than equal to i so as we discussed we will be concerned till ith index and not beyond that so we are making progress so if a j is equal to i plus 1 so this is from n minus 1 to 0 but actually numbers will be from a one to length and not length minus one to zero so we are adding plus one if we found that number then flip we will define shortly this flip function a j and then since we flipped it needs to be added to result j plus 1 because we are keeping indices i inj from 0 to some value but in the result we are expected to have one based indexing and break since we found that there is no point in searching for it further since there is unique occurrence so this is the first flip and it brings that ith number to the beginning next was to flip entire thing from beginning till i so next we will do flip a i and again whenever you flip you add to the result but there is one redundancy here uh let's say that i plus one was in the beginning of the array so we will flip one so flip one does not make any sense we are flipping the first index with itself so we can start this from one in that case this step will not execute it will just execute this part it's already in the beginning so just flip that complete prefix and after this so this should be written after this not within the now we have to write a simple flip function which should be very simple flip it should take the vector we are passing it by reference so we are swapping the first with the last and so on and they will converge to the middle and let's try so your answer may not exactly match with expected as we can have multiple solutions but it should be within 10 n and it should be valid flip order so let's submit and the solution is accepted and we are here but you can try a few times you should get better result so let's write it in java and the java solution is also accepted and here also we are it's three milliseconds so most of the solutions are concentrated here now finally let's do it in python 3. so we don't need to define flip we can do it in line but let's and the python solution is also accepted
Pancake Sorting
number-of-recent-calls
Given an array of integers `arr`, sort the array by performing a series of **pancake flips**. In one pancake flip we do the following steps: * Choose an integer `k` where `1 <= k <= arr.length`. * Reverse the sub-array `arr[0...k-1]` (**0-indexed**). For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`. Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct. **Example 1:** **Input:** arr = \[3,2,4,1\] **Output:** \[4,2,4,3\] **Explanation:** We perform 4 pancake flips, with k values 4, 2, 4, and 3. Starting state: arr = \[3, 2, 4, 1\] After 1st flip (k = 4): arr = \[1, 4, 2, 3\] After 2nd flip (k = 2): arr = \[4, 1, 2, 3\] After 3rd flip (k = 4): arr = \[3, 2, 1, 4\] After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted. **Example 2:** **Input:** arr = \[1,2,3\] **Output:** \[\] **Explanation:** The input is already sorted, so there is no need to flip anything. Note that other answers, such as \[3, 3\], would also be accepted. **Constraints:** * `1 <= arr.length <= 100` * `1 <= arr[i] <= arr.length` * All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`).
null
Design,Queue,Data Stream
Easy
null
1,863
welcome ladies and gentlemen boys and girls today we're going to solve another coolest question which is sum of all subjects x or totals okay so basically what the question is saying if you look at over here they're saying like the extraordinary of an array is defined as a bitwise xor okay of all its element or zero if the origin all right so for example xor table is the two five six so it's two x one five four x over six okay this one okay so what the question is saying if we can look at over here we have something like one comma three and we have to calculate give there give us total sum okay total sum of it's all subsets so what the sub subset of one comma because subset can be uh two and uh one and three okay so once i calculate them they come up six and that's what is our answer so that's what we have to written over here all right so let me just give you a little bit good explanation like how we want to solve this question so that's the same thing like what the question is saying whatever just i told you i have to give it subset and i have to calculate some so how do i solve this question so i will use a recursion method recursive method to solve this question all right guys so let me just give you an example like how to solve this question all right guys so what i will do uh let's say we have something like i will say i will take five four five one six okay so we have something like five one six all right guys so to solve this i will use the help of uh include and exclude so what is it like one time i will include uh the number in my array and the another time i will not include so whatever i mean let's say we have uh i'm doing like this okay so this is my exclude this is my include so once i'm including it then what will happen my five will come in my array list okay and if i'm not including it my am i just excluding it so it will come as an empty over here okay so again what i will do i will create include x2 so once i'm including it what will happen my one will come in my area is five comma one okay if i'm not including it then what will happen only five will come over here now in this one so i have to include an expo so what if i include this one then what will happen my one will come over here in my array list and this will it will empty over here okay similar thing will happen over here include exclude so once i'm including what will happen five one six will come over here and if i'm not including it then what will happen only five comma one will remain okay five comma one okay guys similarly in this one five so what will happen when i'm including it once i'm including my five comma six will come if i'm not including it then what will happen only my five will remain now in one so what will happen in one so if i'm including it then what will happen my one comma six will come all right guys if i'm not including it i'm excluding it that will happen only uh one will come oh yeah one will come okay so this one will become if i include this thing so that six will come if i not include if i'm excluded then my it will give my empty one okay empty and realistic okay so if you carefully look at over here what is happening we are going level by 11 so we are going level by level initially let's say uh this is my level zero i think this color is not busy i is this one is okay yeah to do my level zero this is my level one and this is my level two all right guys so what this level is saying like it is counting its index like we have to like uh we are going every time so like first time i will do include extrude so once i reach the limit then i will go for the another level okay so once my level re once my array limit reach then i will close my level okay guys so that's what i'm doing over here i hope this thing is clear if still not don't worry once i will write the code you will definitely gonna understand like what i'm doing okay so let me just erase it and start writing over code all right so what i will do i will first of all uh create one helper function okay so my helper function will help me to um i will call one function which that function helps me to calculate what once i'm including once i'm not including it okay the xor or uh array all right so i'll give my helper function and i will say in alpha nums and my level is zero initially and the current xor of that number initially will be zero okay and i will written it as one i will do all right guys so i hope this thing is clear okay now what i will do i will call that helper function so publicant helper so in nums and my initially level is zero this guys and uh my initially current xor will be zero as well as i mentioned upside if you look at over there all right now oh my mistake now what i will do i will create one include function i will say include so in my include i will call to my helper function okay and i'll say nums level plus one okay so my level will be increased one by one okay so it will go recursively okay and uh the another thing is i have to calculate their xor okay i have to calculate my current xor including my another number okay so what will happen so my current xor uh is power nums hello all right guys i hope this thing is clear and what i will do i will create when my explorer one as well so my extrude is helper numbs level will increase as well in index form it does not matter like we are because like we are not good enough the thing is like we have to increase the level okay and uh i will just simply call my current because we are not considering the another number so we are not considering any other another number so whatever we have we just calculate the export remaining on the whatever we have right we will just calculate the xor of that okay and finally i have to i will return their sum so some will be enter uh include plus explode okay guys now one more thing i will create one base condition my base condition will be uh if my level is equal to my nums don't length all right so what it means like once my array like let's say i have five one six so one once i will receive my complete one five one six and it's on the optimum level then i will simply return my x1 i will simply return my current x4 over there okay that's what i'm doing over here in my base condition all right guys i hope this thing is clear like this is a very simple question it's very simple question that's all the qualities let me just suddenly let's see if any compilation error over here and uh is it's going very well alright guys so i hope the scenes here like what i did let me just give you a q over investment so what i did i will create i will make a call to my helper function in which i'm giving my level and i'm giving my current x1 okay and another thing is like i'm creating one include an extruder as well in this one helper function okay so the include means will include the new element in the exponent will not include any another any other element all right and finally i will written my sum over here okay so that's all that like code is saying and let me just somebody doesn't let's see any uh compilation error and uh like yeah all the tests are passing and it's going hundred percent positive okay so guys i hope this question is crystic related to like how we are approaching this question so i just want to say like if you still have any doubt ladies and gentlemen just do let me know in the comment section and ladies and gentlemen thank you very much for watching this video if you still don't understand i will say try to watch this video again you will definitely want to understand and still any doubt then just do let me know in the comment section so ladies and gentlemen thank you for watching this video i will see you in the next one till then take care bye and i love you guys believe me i love you man bye
Sum of All Subset XOR Totals
sum-of-all-subset-xor-totals
The **XOR total** of an array is defined as the bitwise `XOR` of **all its elements**, or `0` if the array is **empty**. * For example, the **XOR total** of the array `[2,5,6]` is `2 XOR 5 XOR 6 = 1`. Given an array `nums`, return _the **sum** of all **XOR totals** for every **subset** of_ `nums`. **Note:** Subsets with the **same** elements should be counted **multiple** times. An array `a` is a **subset** of an array `b` if `a` can be obtained from `b` by deleting some (possibly zero) elements of `b`. **Example 1:** **Input:** nums = \[1,3\] **Output:** 6 **Explanation:** The 4 subsets of \[1,3\] are: - The empty subset has an XOR total of 0. - \[1\] has an XOR total of 1. - \[3\] has an XOR total of 3. - \[1,3\] has an XOR total of 1 XOR 3 = 2. 0 + 1 + 3 + 2 = 6 **Example 2:** **Input:** nums = \[5,1,6\] **Output:** 28 **Explanation:** The 8 subsets of \[5,1,6\] are: - The empty subset has an XOR total of 0. - \[5\] has an XOR total of 5. - \[1\] has an XOR total of 1. - \[6\] has an XOR total of 6. - \[5,1\] has an XOR total of 5 XOR 1 = 4. - \[5,6\] has an XOR total of 5 XOR 6 = 3. - \[1,6\] has an XOR total of 1 XOR 6 = 7. - \[5,1,6\] has an XOR total of 5 XOR 1 XOR 6 = 2. 0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28 **Example 3:** **Input:** nums = \[3,4,5,6,7,8\] **Output:** 480 **Explanation:** The sum of all XOR totals for every subset is 480. **Constraints:** * `1 <= nums.length <= 12` * `1 <= nums[i] <= 20`
null
null
Easy
null
104
when it comes to Binary trees more than a problem this is much more of a concept in itself so you're given a binary tree with a root right and you have to find me the maximum depth of a certain node right so this tree would have certain parts right from the root to all of the leaf nodes correct and you have to determine me what is the maximum depth of such a node correct so there are a lot of wave in which the same problem can be asked you could be asked okay how many levels are there in a binary tree you could be asked okay what is the height of a binary tree and similarly in this case you are being asked okay what is the maximum depth of a binary tree so in all of these problems the underlying concept will remain exactly the same and that is that you have to calculate the height of a binary tree that means how many levels are prevent correct because if you have n number of levels then that will be your maximum depth right if you have n levels that is your height of the binary tree right so we will be focusing on finding the height of the binary tree and that height will also be the maximum depth Hello friends welcome back to my channel first I will explain you the problem statement and we will look at some summative cases going forward we will look at the Brute Force solution and how you can approach this problem and then going forward we will try to optimize this solution as always we will also do a dry run of the code so that you understand how all of this actually works in action without further Ado let's get started let us first try to make sure that we understand what do you mean by the height of a binary tree simply means the maximum difference between the root node and all the leaf nodes of a binary tree so let us take apart if number one in our test case number one you have this node as the root node right and you have four leaf nodes in this tree correct so the height of a binary tree would be the maximum distance of all of these four nodes from the root so in this scenario let us try to find out these distances for the first Leaf node the distance would be 1 and then 2 right so this difference is 2. for node number two let us try to find out the distance this time the distance is again 2 right so in this particular scenario the distance of all of these four nodes is 2 correct so we can safely say that the height of this binary is equal to 2. now this is a very simple case let us take up our test case number two where our tree looks a little bit more complex right so in a tree number two let us first find out all of our Leaf nodes so this is a leaf node and this is a leaf node right now what you simply need to do is find out the distance from the root node to all of these Leaf nodes and get the maximum value so let us try doing it one by one for our first note the distance is 1 and then 2 right going over to our second Leaf node the difference is again 2 right but in this test case we have one more Leaf node and if you try to find out the distance that is one two three and then ultimately four so the difference of this Leaf node is 4. so given by the definition the height of a binary tree should be the maximum value right so in test case number two the height of a binary tree would be 4. now if you have understood this problem statement feel free to try it out on your own otherwise let us dive into the solution a good developer always strives to come up with a Brute Force solution first that is because a Brute Force solution can guarantee you that a solution to the problem exists so let us say you are given with this binary tree and I ask you to find its height what is the first thing that comes to your mind given by the definition of the height is the maximum difference between the root node and the leaf node right so one straight away method that should come into your mind if you can find out all the references between the root and the leaf nodes so what does that tell you can easily create a table where on the left side you can store all of your Leaf nodes and on the right you can write down all the distances from root so given your binary tree can you identify all of the leaf nodes two is a leaf node 6 is a leaf node 5 is a leaf node eight is a leaf node and then 10 is a leaf node right so you can write down all of these values in your table okay the next step now is to calculate the distances of each of these Leaf nodes from the root so you can start from the beginning for node number two the distance would be one and then 2 right so you can simply write down this distance in your table right going forward with our next Leaf node that is number six so that difference is 1 2 and then three so you can write down the distance 3 in your table now moving ahead with my node number five so the difference would be 1 and then 2. once again I will write down this distance moving ahead with node number eight the distance would be one then two and then three I would once again write down three in my table going ahead I have my node number 10 right so this difference would be one two three and then 4. correct so I write down this distance 4 in my table now what you can simply do is you can scan through this table and look at the maximum distance you can see that 4 is the maximum distance right and hence this is your answer or you can say that 4 is the height of this binary tree now this method works and it will give you correct answer every time but can you see the problem with this approach what happens if your tree is very huge what if you have a lot of leaf nodes will you go on to calculate the difference between each of them that would be very hectic right and it would take a lot of time so try to think of an efficient approach let's see how we can do that okay so let us try to take our same example once again and try to find an efficient solution when you're trying to find efficient solutions to problem think outside the box don't just jump on to the definition and try to come with a solution you have to find out the height of a binary tree right and from all the examples that we just saw the height of a binary tree just looks like the levels in a binary tree right if your deepest node is at the height 7 then you can also see that there are seven levels in the binary tree right for example when I would look at this tree I can say that root is at level 0 1 and 4 is at level 1 2 3 5 7 is at level two six eight nine is at level 3 and then ultimately 10 is at level 4 right so if You observe carefully what does this tell you the deepest level this deepest level is also the height of a binary tree right so can we somehow take advantage of a level or a traversal technique to find the height of a binary tree maybe yes by the way if you're new to level Auto traverses I would highly recommend you to check out my video on it so if you remember when we were using level order traverses we took the advantage and help of a q data structure right because that follow a first and first dot policy so what we were actually doing in our queue we took the first Element 11 and then we inverted it in our queue correct so this marks the end of level 1 correct next what happened is we inserted all the child nodes of the first level right so the child nodes of first level are 1 and 4 right so when I would insert the elements at this level in my queue would become like right and this marks the end of level 2. so far so good what of The Next Step what were the next elements that you added in your queue you added all the children of the previous level to your queue next right so the new children are two three five and seven right so I will add all of these elements in my queue and this is how you completed a level and this is how you marked the end of one more level once again going forward what you're gonna do is you will add all the children to your queue next so I will add my element 6 8 and 9. and once again this marks the end of a level I am left with my remaining element that is number 10 so I will add this 10 again to my queue now if you look at the queue closely you can see all these markers right these are just defining the number of levels that are present in your binary tree and you know that the height of a binary tree if the maximum number of levels right so to get your answer what you can give to is you can count these pointers they are four in total right and hence 4 is your answer so the height of this binary tree is 4. now let us try to do a dry run of the code and see how you can implement the solution on the left side of your screen you have the actual code to implement the solution and on the right I have the sample tree that we will try to find the height of oh and by the way the complete code and its test cases are available on my GitHub profile as well you can find the link in the description below so to start off the root of this binary tree is passed in as an input parameter to the function right next we create a queue that will store all of the elements while doing a level or a traversal right going forward what we do is we add the root element to the queue so this will add 3 to my queue right now correct next we say the number of levels equals to -1 that is just the starting equals to -1 that is just the starting equals to -1 that is just the starting point so I start off with my number of levels equals to minus 1. next I have a infinite while loop that will keep on running throughout until your tree ends completely first of all we maintain account at each level so the queue size will tell you how many nodes are at the current level currently you are at level 0 right and you have only one node right so as you can see the size of the queue is also one that means you have only one node at the first level so what does that tell you when will the tree end whenever this node count is zero that means your Q is completely empty or you don't have any nodes at this level that means your tree has ended right so we just add a check that if node count at level equals to 0 then you return the answer and this will tell you the total number of levels now since there are some elements in the queue so what we need to do is we need to keep on processing a tree we need to add all the child elements of this level to our queue so what do I do next I start a while loop again that will run until I have traveled all of the elements at that particular level I get the element from the queue so I will get this element 3. right now I need to check if this element has a left child and it have a right child then add it to the queue since 3 has both a left and the right what I will do is I will add 1 and 2 to my queue correct now since I have traversed this element 3 what I'm going to do is I will simply reduce the node count at level right because I have traversed this right so this will change this value to 0 once again and that means that I have completed this level and as soon as we complete a level what I do is I increment the count of number of levels so this will change the value of levels to 0 because I have just covered level number 0 right now moving ahead what do I do my while loop runs again right and this time I will again find out the number of nodes at a particular level this time I am at my next level right and you can see two nodes over here and as you can see the queue size is also two so this will change the node counted level to 2. once again we won't enter this if Loop and we will once again start a while loop to add all the children of this level into my queue you can see that one does not have any children right so this will just pop away from the queue next you have the element two now two have a child that is four right so I will add 4 to my queue and this 2 will go away once you have traversed this level the node counted level will again become 0 and you have once again traversed an entire level and as soon as you have traveled a level the value of number of level increases by 1 and the number of levels change up to 1. once again this Loop will run you can see that we have reached our next level you see only one value right and even your queue have only one value so this keeps things consistent and once again your node count at level if one again once again this Loop will run you can see that 4 does not have any children right so it gets popped from the queue and no new elements are added but what you do is since you have completed this level you will increment the number of levels right so the value of number of levels changes to 2 correct now when the while loop runs again there are no elements in the queue right and this is the time when this if condition will get executed you don't have any new nodes and hence you can simply return the number of levels and this will return your answer that is 2. so you can say that the height of this binary tree is 2. the time complexity of this solution is order of n where n is the number of nodes in the binary tree because you are traversing through each of them and the space complexity of this solution is also order of n that is because you are maintaining a q that can have all the elements of the tree I hope I was able to simplify the problem and its solution for you as per my final thoughts I believe now you can see how the height of the binary tree will also be the maximum depth of the binary tree correct and this brings up another important point that is the level order travel free technique I cannot emphasize enough how important this is because when you are doing a level order traversal first of all it behaves in an iterative fashion correct so it becomes easier to visualize and debug what is actually happening and 11 or traversal make sure that you are traversing all the notes and you will always guarantee that okay you are traversing a node and this makes things so much easier you will be able to understand what is the time complexity you will be able to understand what is the space complexity and that is what makes the level or a traversal technique very important so what I want you to do is comment section below tell me any other problems where the level order traversal technique has been very helpful also tell me if you found some other variations of the same problem finding the number of levels in a binary tree finding the height of a binary tree what else tell me everything in the comment section below and I would love to discuss all of them with you will be also glad to know that a text wave explanation to this content is available on the website you on the website you on the website you can find the link in the description below I have a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also let me know what you want to learn next until then see ya
Maximum Depth of Binary Tree
maximum-depth-of-binary-tree
Given the `root` of a binary tree, return _its maximum depth_. A binary tree's **maximum depth** is the number of nodes along the longest path from the root node down to the farthest leaf node. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** 3 **Example 2:** **Input:** root = \[1,null,2\] **Output:** 2 **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-100 <= Node.val <= 100`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
110,111,774,1492
292
everyone this is programmer Mitch hope you're enjoying your last hour today with daylight savings day we're gonna do leak code number 292 which is MIM game it's got 147 likes 567 dislikes this will be a short one is kind of a blink and you miss if you're prepping for interview questions with this twitch stream I don't think you'll see too many questions like NIM game anymore it's kind of a trick question and it's hard to say like a lot of questions okay it's like every question that's a trick question in an interview setting well this one is especially so but let lets let's hop right into it you are playing then the following NIM game with your friend there's a heap of stones on the table each time one of you takes turns to remove one or two three stones so one two or three stones the one removes the last stone will be the winner you will take the first turn to remove the stones so you do take the first turn both of you are very clever and have optimal strategies for the game write a function to determine whether you can win the game given the number of stones in the heap for example there are four stones of the heap then you will never win the game is it kind of give a big old hint here for the answer no matter one two or three since you removed the last one will always be removed by your friend so for a question like this it's kind of interesting to think about okay what possible scenarios do you win so if you start with one stone that's a win automatically right because I just remove the one stone and then I win it two stones also when just from the two threes also when I just removed the three before as they mentioned here you will never win the game no matter one two or three stones you removed the last time walls doing apply your friend all right so if I would move one stone though the pen will move three if I move two stones the pendulum moves too if I remove three stones when the friends will move one and always wins there's always a loss so how does this extend to as you continue past the four well what's five six seven eight so with five I can put my friend in the losing situation no matter what right because I can remove one stone now he always loses for hey pulsating thanks for stopping him today he always then he gets the four and then we know that whoever gets four automatically loses right because then he'll have to remove one two three and then I can win that's a win if it's six I can also remove down to four right because I take away two same conditions he has to remove one three and I automatically when seven is the same way now eight hi lavender JMK thanks for stopping in today with eight stones my automatically guaranteed a lost yes I am because I had to move one two three and then my friend is as five six or seven and put me in the four situation so if you can kind of see this pattern you'll see that it extends out like this so basically if it's divisible by four you will automatically lose so right effects determine whether you can win the game so it's the opposite of that right so basically all we have to do is return if what we're given the number n if it's the visible wife for does not equal to zero right in that case we win the game so let's go ahead and see if that's the case we had run and run this earlier and we saw that it was accepted and indeed to set it again here today this is not like a super interesting out doing the question we got through it in about three minutes but it just kind of goes to show you kind of want to repeat the question back to people provide examples and then think about an approach and oftentimes with questions like this the answer will kind of jump out at you and then you can kind of just go ahead and code it out there but this is programmer Mitch this is league code number 290 tune in game I do practice programming questions every week usually not this short at 5:30 p.m. est hope to not this short at 5:30 p.m. est hope to not this short at 5:30 p.m. est hope to see you next week
Nim Game
nim-game
You are playing the following Nim Game with your friend: * Initially, there is a heap of stones on the table. * You and your friend will alternate taking turns, and **you go first**. * On each turn, the person whose turn it is will remove 1 to 3 stones from the heap. * The one who removes the last stone is the winner. Given `n`, the number of stones in the heap, return `true` _if you can win the game assuming both you and your friend play optimally, otherwise return_ `false`. **Example 1:** **Input:** n = 4 **Output:** false **Explanation:** These are the possible outcomes: 1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins. 2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins. 3. You remove 3 stones. Your friend removes the last stone. Your friend wins. In all outcomes, your friend wins. **Example 2:** **Input:** n = 1 **Output:** true **Example 3:** **Input:** n = 2 **Output:** true **Constraints:** * `1 <= n <= 231 - 1`
If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?
Math,Brainteaser,Game Theory
Easy
294
211
Hello everyone welcome to my channel with Mike, so today we are going to see question number five of our data structure design playlist, medium level using an already used template, we have made a question from scratch, copy paste the code from the template and do it with this. A little bit will be solved, just the notification will be based on the question, okay, add question and search term, data structure is such that you can search further data, okay, there are data structures, do you know their special thing, what is the template, okay, template is only like this. I am not saying that 100% will be solved but 8290 100% will be solved but 8290 100% will be solved but 8290 % questions are created. If you % questions are created. If you % questions are created. If you understand the template well then it is okay. Just understand the template and you are okay. I will give you an example. You will remember the graph. My playlist is going on. I told you that the maximum question of the graph was made only after understanding how the graph is implemented. Right, if you see my playlist, I do it in a very temperate manner, every time in every question of the graph, similarly. What do I do in the question? I copy and paste the DSO template and then solve the question. What do I do? I copy and paste the template. What is the benefit of this? What is the benefit of what you understood? It was good. There is something new in every video. You will not be able to know the thing, you will be able to do it from the templates similarly, it has been tried, it has been fixed, similar to this, now let us see the input output in this question and understand what the question is, it is very simple, it is to say that like this Make a data structure and show it, mother, here is the data structure in which you can add words like Bed Snake, the given word has been added, Dada, it has been added, okay and also search for the word in it, Sukun is saying search for bed. Do what is a bed? If this is a bed then the answer will be true. Okay, what is just one extra thing added to it? They can also give something like this to search. If you are looking at this, look carefully. There may also be a dot here. It is saying that you can take any character from A to C, if you fail by yourself, then like if you take mother, then what will happen, it will become bed and bed is in my data structure, then I will return the answer true, ok. And like here also there is a double dot, so it is possible that my answer will be true, it is ok for that too, so they have just done this extra trick, rest of the things, if you pay attention, will be solved by just try, this question is ok and why try? The most important question that comes to mind is how to try? Look, whenever you pay attention to dog, here the post is to search character, like here when you were allowed to search bed, then it is okay. That's fine, you can search the whole string, be it timer or bee tree or seater, after that, whatever is back, is it ad, then you search that ad, generally in such questions where character or character has to be matched. You have to search, always think in the bigger picture of try, it is okay, it can be made in other ways as I told you, it will take more hard work for you, but tree it is de bed status structure, you have to solve this question, one more thing must be remembered that There are very limited questions of TRAI, so make five or six questions of TRAI, otherwise you can predict in each question of each tree that people will read this question of TRAI. If you read any question, if it is made of TRAI, then you will definitely spot it. People, this time and this is tested because similar thing happened with me. Starting after watching, other questions will definitely be made from TRAI because I will have to find the character brother, character. So now about TRAI, I had told you earlier in the video that I am a simple thing about TRAI. There is one note, okay, try note, okay, now there are two things I want to keep in the road in try, first, what is this and the word 'off', first, what is this and the word 'off', first, what is this and the word 'off', you will remember that, watch the previous video of this playlist, okay, everything will be clear, true. If so, there is not a single word on this note. Secondly, what will happen is that it will have a child named Hey of size 26 which will have pointers to further and try notes. If I want to search a word in the tree, its function and in add try I will find a word. It is okay to add, both these functions will be copied and I will tell you how to solve the dot. Before that, I am telling you again that I will copy paste the code of search and the code of add. It is okay from the previous question. So watch the previous video once, now the extra thing I have said in it is that it can also have a dot, see how to solve it, that too is simple and can be solved by searching, see if I understand with an example, then see this. Let us understand from the example that let's start with mother, we have the entry , this is also made, okay, so the word at the end of this is not finished, that is, no, it is there, otherwise, we will make it, okay, similarly, something has happened here. Let's keep it like this, if this diagram was inserted then it becomes B, this is okay till now it is clear, after that let's take mother whom Okay then I am near the root, if not like this then it was written by making S. Same thing will happen, now let's come to this, if please search whatever is there, it is something like A, let me search in it is standing here, okay, and which character do I have first, okay do you have A, okay keep this. Now we have kept A here, now what else has gone back, we will kill tomorrow, where I will search whom, I will search T and S, I will search again and I will say that T and S are just to be searched because B was found in the dot A. I had put T and now if I want to search further then I will search from the record again tomorrow. So I will send it to the crawl in a similar way. If I get T inside and below, then I will burn the return. Okay, if I put it at the top, I will go back. ] Okay, keep I here, so keep I, do T, A is here, what is there after that, S is here, A is here, we have seen both the characters, that is, our loop will be at the end, so let us just see this. Where is the collar now, what is there to be put here, where it is, we returned back to B, A, C was not found, my A was found on the same day, so we explored again on A, we found B, then T and S. Copy. Just this extra check will be pasted, which will be in the dot's form, now again while coding, we will tell the climber line, the important thing is to understand the code line by line, okay, so whatever the story is, it is okay, we will convert it in the court, some extra. Will not say ok and yes will copy paste, we will already make it from template only, this question is nothing bill be new ok, if we will do that then watch the previous video of yesterday, if we solve try then see its code which is start. Let's do Lit-Cut, we used to like this question, it Lit-Cut, we used to like this question, it Lit-Cut, we used to like this question, it is very good and what I said, we will already create it from the template, it is okay, so let's do one less, go to the try repo in our tree playlist, yesterday I tried implement it, okay, this is what I did. What did you do here So this is the best template, now that you understand the data structure will be solved, now I have to go to the search. Okay, so I will copy paste the entire search but now remember what I said. The dot people will record the search only tomorrow also, but how will the dot people do the record only tomorrow? It is obvious that you will have to send that where is the crawler present now? Where is the crawler present now? After that, the remaining words are like mother. Okay, the word will be here, how many children have you got? Okay, now on search, if the word comes here, then I will search YouTube tomorrow. Okay, brother, let's start from the root and we have to search this word. Okay, now search YouTube. But let's go, okay search, I am just copying and pasting, there is a little change, nothing else, okay, here we take the root, if it becomes equal to my dot, then we have to separate something extra, but it should also be of dollars. Jai Maa on Children, you can do zero, I am everyone's children of J. Okay, now I am present on I, so if I character is my dot, then the child after I is born to him, but if he is found on search, then I return. You will do it, okay, I will tell you, let's take out the index, do it like this Do it like this, it means it is good, there will be floods in the future, this is equal, you are true, if it is like this, then you will return, otherwise return the result. It will happen that if this equal is null, then burn the return, okay, you can write it smartly like this, remove it, put a note here, you can also do it again like this Return Knowledge is okay, mention me in the comment area. I will give you what is the time and space complexity. Don't worry about it. The most important thing was that you already know the template. When I made the question of implement tree, I have copied and pasted the template which I had given. It is important that Ruse the code i.e. important that Ruse the code i.e. important that Ruse the code i.e. you should have kept in mind, you should have remembered, this implementation is fine.
Design Add and Search Words Data Structure
design-add-and-search-words-data-structure
Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the `WordDictionary` class: * `WordDictionary()` Initializes the object. * `void addWord(word)` Adds `word` to the data structure, it can be matched later. * `bool search(word)` Returns `true` if there is any string in the data structure that matches `word` or `false` otherwise. `word` may contain dots `'.'` where dots can be matched with any letter. **Example:** **Input** \[ "WordDictionary ", "addWord ", "addWord ", "addWord ", "search ", "search ", "search ", "search "\] \[\[\],\[ "bad "\],\[ "dad "\],\[ "mad "\],\[ "pad "\],\[ "bad "\],\[ ".ad "\],\[ "b.. "\]\] **Output** \[null,null,null,null,false,true,true,true\] **Explanation** WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord( "bad "); wordDictionary.addWord( "dad "); wordDictionary.addWord( "mad "); wordDictionary.search( "pad "); // return False wordDictionary.search( "bad "); // return True wordDictionary.search( ".ad "); // return True wordDictionary.search( "b.. "); // return True **Constraints:** * `1 <= word.length <= 25` * `word` in `addWord` consists of lowercase English letters. * `word` in `search` consist of `'.'` or lowercase English letters. * There will be at most `2` dots in `word` for `search` queries. * At most `104` calls will be made to `addWord` and `search`.
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
String,Depth-First Search,Design,Trie
Medium
208,746
997
hey everybody this is Larry this is uh day 23 of delete code daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's poem and also uh yeah oh see the reason why I always sometimes click on here you are new to the channel is that there's uh you know this upper left thing where I wish you first to AC if you click on it you got 10 coins yay so I sometimes check oh no but yeah um I'm probably gonna do an extra question so one that I haven't done before because we've done this one or I've done this one anyway so definitely hit the Subscribe button and don't bonus question from with me if you like it is easy hope y'all have a great beginning of a week and kind of start off strong today's problem is 9.97 find off strong today's problem is 9.97 find off strong today's problem is 9.97 find the town judge let me put the mic a little bit closer just in case that wasn't loud enough hope that sounds a little bit better I don't know why it was back anyway okay so there's one to end people um they're rumored that one of these people is the town judge what does that even mean it could be a murder but like why do you try to find a judge I don't know okay so everyone trusts the judge and the judge trusts nobody okay so then I guess we just have to kind of uh count right so um yeah I mean this is just like a graph problem thing or I mean you don't even have to think about it in graph whether like you can just kind of think about it um you know right so okay so um so we have two things like one is uh trust someone maybe times n and I like big ends and then maybe um yeah and I'm just trusted by or something like that and it just zero times end right um I don't know I'm just rereading the question if you're wondering about like exactly what creates negative one um that's basically why I was just wondering whether like if these things are violated um does it return negative one or is it just that um yeah is it negative one or you know what's the situation right so that's basically what I was trying to look at also try to see the length of the trust I think that's fine okay maybe this is fine we'll see I'm not quite sure but okay uh yeah and then now for you we and Trust so then foreign okay so then trust someone of you as you go to church because they trust someone and then trust it by maybe that's wrong it's increment by one right and then now we just have to find um Okay so for I in range of n if trust someone of I is not true so you know they don't trust anybody and trusted by other people of I is equal to n minus one then we return I otherwise we just return negative one maybe that should be good enough I don't know if I'm understanding the problem correctly uh oh this is one indexed so I have to kind of make some modification um and then this is plus one okay let's give a quick submit maybe I've oh gosh I did not misinterpret it but if it's a very awkward question because only because sometimes and maybe this is me being a defensive amount because I feel like I've been making a lot of silly mistakes lately but um that's just whether that like yeah if five people trust no one then like you know I don't know this is very occupying but I guess as I said so let me know what you think don't really have much to go over here you just kind of simulate what they tell you and do counting right so it's very basic bookkeeping I'm gonna do a bonus question after this one that I haven't done before so stay tuned for that um that's what I have for this one though so let me know what you think oh let me go over the complexity real quick this is just linear time then your space hopefully I don't have to explain it that much um this is going to be all of ye if you will which is the length of trust this both of these are all n and yeah uh okay that's all I have with this one let me know what you think and stay good stay healthy it's a good mental health uh I'll see you later and take care bye have a great rest of the week bye
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,649
hi guys welcome to algorithms made easy today we will see the question create sorted array through instructions given integer array instructions you are asked to create a sorted array from the elements in it you start with an empty container and for each element from left and right in instructions insert that number into nums array the cost of each insertion is minimum of the following two things first is the number of elements currently in nums that are strictly less than the current number or the number of elements currently num that are strictly greater than the current number if you take an example and try to insert 3 into this array we can see that there are two numbers one and two that are smaller than three and one number that is five which is larger than three so the cost of insertion would be minimum of two and one which comes out to be one so return the total cost to insert all the elements from instruction into nums since the answer may be large return a modulo of 10 raise to 9 plus 7 let's see this first example graphically and then it will make more sense so let's take this input and here we are taking a nums array that is of length greater than the maximum number that is present in our input that is i have taken this up to 7 we can take it up to 6 and so starting with a blank array since there is no number the count of each element would be 0. as we encounter 1 the cost would be minimum of all the counts from left of 1 and all the counts from right of one so here both the sides we have count as zero so here we'll get zero as our answer if we try to insert five we can say that count of five would be minimum of summation of this part and summation of this part which would give us minimum of 1 and 0 which would be 0. similarly if we find that for 6 it would again come out to be 0 as it right we have sum of 0 and for 2 we'll get the cost as minimum of 1 and 2 which would be 1. so here the minimums for all of them are as 0 and 1 and thus the total cost would be the summation of all these minimums which would give us 1 so this is how we need to solve this problem as you can see here we need to find the sum of counts before and after so we can say that we need some kind of prefix or suffix sum so that's how we are going to solve this so we will need a prefix sum but here if we find the prefix sum at every step of insertion it would make our time complexity higher as we need to find the sum all the way from the start till the element and all the way from element plus one till the end so that's not an efficient way the most efficient way of finding the prefix sum would be by using a fenwick tree or a binary index tree this tree is mainly used for the purpose of finding the perfect sum in log n time so let's see how the spending tree works let's say we have this array and these are the indexes so each index will store a partial prefix sum from some index i to j if we take these indexes index 1 will store the sum from 1 to 1 index 2 will store the sum from 1 to 2. index 3 will store the sum from 3 to 3 and so on so how do you find the starting range of these indexes the starting range of this indexes is derived just by removing the last set bit from the number or the index and adding 1 to it so if we take 5 and we remove the last set bit which is this one we get 4 and 4 plus 1 is 5. similarly if you take index 4 removing the last set bit makes it 0 and 0 plus 1 is 1 so the range would be 1 to 4 this is how we derive the range so the main task over here would be finding the last set bit and updating the indexes or getting the next index finding the last set with can be done by using the formula x and minus x is nothing but two's complement of x which is one's complement or not of x plus one if we take this example of one zero we get two's complement as zero one zero by using this and if we do an and with the number it gives us zero one zero so here we can see that this is actually the last set bit if we were to remove the last set bit we would do x minus this last set bit so to find the prefix sum till an index i we would need to add some at each eye by removing the one last set bit till the number becomes zero here if we see the example of sixth index it would be sum at the index six plus somatic index four which is obtained by removing last set bit from this binary representation of 6 and adding the sum at this 0 which would be inverting the last set bit from 4. so if we take this in consideration with help of a range it would give us the range of five to six plus one to four so if you see it is a range from one till six so that's how you calculate the prefix sum so if you see that here we did not have to go from all the indexes from 1 to 6 but we just needed the sum of these three indexes and this reduces our time to o of login so this was all about finding the sum now comes the part to update this tree or update the array so for that while we are adding some value to a index i we also need to add the value at all the indexes that are affected for example if you are going to add some value at index 2 you would also need to add it at index 4 because that is also taking the range that includes 2 in it how we would be doing that is we need to first increment this index to go to our next index and then we'll find the last set bit of this index and add that set bit into the number so if we incremented 2 we would get 3 and its last set bit is 0 1 if we had this 0 1 into 0 1 we get 4 thus we need to add the same value that we have added at index 2 to also index 4. we keep doing this until we are in the range of our array length so if after 4 we add this last set bit we get 8 but 8 is out of our range so we stop to summarize this we have two different functions that we would need one is the sum and second is the update for sum we would need to add sum plus value at index x and we need to modify the index such that we remove the last set bit from the index and add the value of that particular index in the sum again for update we have some similar logic but here we first increment the index and then we add the value at that particular index and update index to index plus the last set bit so that's all about the theory part now let's go ahead and create this fenwick tree and solve our question so the first thing we need to do is create a friendly class that would give us a fan victory in here we'll take an integer array and have a constructor this constructor will give the length and we'll initialize our array after this is done we need two methods one is to find the sum and other is to update the count so for finding the sum we need the range of the sum from begin to n so let's write a method for it and in here we'll return sum for n plus 1 minus some till beginning and now we need to define this one more method this method will give us the sum till the index i so we start from the end and we see why i is greater than 0 we do sum equal to sum plus and let's declare a sum variable and our index becomes i minus i n minus of i at the end return sum next thing we need is the update count method so in here we'll take an index and the value that we need to add so first it would be i plus and then while this i is in range we do area of i equal to plus val and index equal to index plus i n minus i so that's all about update and sum now we need to write the main logic to call these methods from here so we take first take max equal to 0 and we'll find the length that we can pass to this constructor so this will give us the maximum number that we have in our instructions array now we pass this max plus 2 in this constructor 1 from this plus 2 is so that we can start from index 1 and the other one is to accommodate this n plus 1. now we'll take a for loop and in this for loop let's take this current variable we'll have two values one would be the lower end and one would be the higher end so the lower one would be from range of 0 to current minus 1 and higher would be current plus 1 till max now what we need is we need a result variable and this result would be result plus min of lower and higher once we have this we also need to update the count of this current element so we do and add 1 for this current variable in its count here we are also said that we need to do a modulo so while adding results we also do result mod 10 raise to 9 plus 7 finally we return the result so that's all about the question so this gives us a perfect result let's try to submit this code and it got submitted the time complexity for this algorithm would be o of n log n and the space complexity would be o of max plus 2 which would be o of max thanks for watching the video guys see you in the next one
Create Sorted Array through Instructions
maximum-number-of-non-overlapping-subarrays-with-sum-equals-target
Given an integer array `instructions`, you are asked to create a sorted array from the elements in `instructions`. You start with an empty container `nums`. For each element from **left to right** in `instructions`, insert it into `nums`. The **cost** of each insertion is the **minimum** of the following: * The number of elements currently in `nums` that are **strictly less than** `instructions[i]`. * The number of elements currently in `nums` that are **strictly greater than** `instructions[i]`. For example, if inserting element `3` into `nums = [1,2,3,5]`, the **cost** of insertion is `min(2, 1)` (elements `1` and `2` are less than `3`, element `5` is greater than `3`) and `nums` will become `[1,2,3,3,5]`. Return _the **total cost** to insert all elements from_ `instructions` _into_ `nums`. Since the answer may be large, return it **modulo** `109 + 7` **Example 1:** **Input:** instructions = \[1,5,6,2\] **Output:** 1 **Explanation:** Begin with nums = \[\]. Insert 1 with cost min(0, 0) = 0, now nums = \[1\]. Insert 5 with cost min(1, 0) = 0, now nums = \[1,5\]. Insert 6 with cost min(2, 0) = 0, now nums = \[1,5,6\]. Insert 2 with cost min(1, 2) = 1, now nums = \[1,2,5,6\]. The total cost is 0 + 0 + 0 + 1 = 1. **Example 2:** **Input:** instructions = \[1,2,3,6,5,4\] **Output:** 3 **Explanation:** Begin with nums = \[\]. Insert 1 with cost min(0, 0) = 0, now nums = \[1\]. Insert 2 with cost min(1, 0) = 0, now nums = \[1,2\]. Insert 3 with cost min(2, 0) = 0, now nums = \[1,2,3\]. Insert 6 with cost min(3, 0) = 0, now nums = \[1,2,3,6\]. Insert 5 with cost min(3, 1) = 1, now nums = \[1,2,3,5,6\]. Insert 4 with cost min(3, 2) = 2, now nums = \[1,2,3,4,5,6\]. The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3. **Example 3:** **Input:** instructions = \[1,3,3,3,2,4,2,1,2\] **Output:** 4 **Explanation:** Begin with nums = \[\]. Insert 1 with cost min(0, 0) = 0, now nums = \[1\]. Insert 3 with cost min(1, 0) = 0, now nums = \[1,3\]. Insert 3 with cost min(1, 0) = 0, now nums = \[1,3,3\]. Insert 3 with cost min(1, 0) = 0, now nums = \[1,3,3,3\]. Insert 2 with cost min(1, 3) = 1, now nums = \[1,2,3,3,3\]. Insert 4 with cost min(5, 0) = 0, now nums = \[1,2,3,3,3,4\]. ​​​​​​​Insert 2 with cost min(1, 4) = 1, now nums = \[1,2,2,3,3,3,4\]. ​​​​​​​Insert 1 with cost min(0, 6) = 0, now nums = \[1,1,2,2,3,3,3,4\]. ​​​​​​​Insert 2 with cost min(2, 4) = 2, now nums = \[1,1,2,2,2,3,3,3,4\]. The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4. **Constraints:** * `1 <= instructions.length <= 105` * `1 <= instructions[i] <= 105`
Keep track of prefix sums to quickly look up what subarray that sums "target" can be formed at each step of scanning the input array. It can be proved that greedily forming valid subarrays as soon as one is found is optimal.
Array,Hash Table,Greedy,Prefix Sum
Medium
null
142
hi everyone welcome back to the channel and today we install the group daily challenge problem number 142 linked list cycle two so it's a pretty straightforward problem so what half we do is we have to basically find out the node at which the cycling linked list starts from okay so what I'm going to do is I'm going to use a very simple approach called uh higher and tortoise approach so in this what we do we basically use two pointers and we can also call that uh you know slow and fast pointer approach as well in which this row pointer at each step will move to only a single node okay but the fast pointer will move two nodes it uh at any given step so what will happen in this case is if there will be a cycle in the linked list both these tools will see each again at least twice okay so that's exactly what we are going to look at um as soon as you know uh these both pointers uh sees each other again what I'll do is I'll set my reset my fast pointer to head and from then on I'll just uh start moving that one step at a time okay so like you know let's go to a dry run on this example for example we initiated our student password from the current head which is at three okay so we have our slow and fast pointer at 3. now the slow Point uh goes to two but the first pointer is at zero okay in the next step a slow pointer will move to zero pass pointer is at two now because there was a cycle so next is two in the next step the slow pointer will move to minus four okay and fast pointer will also jump to minus row and they beat again okay so when this happens like when we see each other again what I'll do I'll reset my fast pointer so my first pointer is at three now and this two pointer is it minus four okay um now we have to uh you know increment both these pointer one step at a time okay until they see each other again okay so now I'll move my slope pointer One Step I'll go to two first one to move a single step and then meet at two so if you see two was the origin of our cycle uh right similarly you can follow the exact same steps in example number two as well so let's move to the solution and I'll explain what exactly we will be doing in the coding part okay so first things first I want to assign my two pointers right slow and fast and they'll initialize it but I really should initialize it that head right now while pass and fast dot next until we have these two values I want to run in this group otherwise I just want to return okay so until we have uh you know valid uh linked list what I'll do I'll move my slope under a single step each time okay so it will do the job right and the password will move two steps each tank so ta now what we have to check is if by any chance my slow and fast are at the same node if this happens what we were supposed to do we were supposed to uh reset our password and now until I see on or until they meet again I want to run into a loop I want to run this D like uh the condition I will write below into a loop and what we wanted to do we wanted to increment both the counters both the pointers with a single step right so yeah this is it like this is the total solution for the problem let's check out the test cases I just hope I didn't miss anything let's see ah sorry I for what to return the pointer like so yeah this is it so basically uh we are returning the node at which the Loop started let's check out the other testing as well um awesome so the solution are accepted and we perform decent I would say like if you check the distribution we have outperformed 35.4 percent of the submitted solution 35.4 percent of the submitted solution 35.4 percent of the submitted solution so yeah thanks again guys for watching out the video and stay tuned for the current noise don't forget to subscribe to the channel thank you
Linked List Cycle II
linked-list-cycle-ii
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**. **Do not modify** the linked list. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** tail connects to node index 1 **Explanation:** There is a cycle in the linked list, where tail connects to the second node. **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** tail connects to node index 0 **Explanation:** There is a cycle in the linked list, where tail connects to the first node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** no cycle **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Medium
141,287
389
hi guys now I'm going to solve the liquid problem find the difference uh it is an easy problem and we can solve this problem by using number of ways so this is the problem description uh in this programming description they have given like they are given two strings one string is s and the other string is e and the string T contains executive one character more than the string s and the letters in t can be shuffles in any order basically the string T contains a same exact capitals of s this one extra character and the characteristic can be shuffled in any order what we have to do is we have to find out the one extra character um if we take a and if we look at this example we see that a is present here in positions so it is not the answer V is also present C is also present D is also present e is not present in s so e is the extra capital now in this example we see that the student s is empty but T contains y so Y is the extra character let us take example and see suppose it says a b c and suppose the student is AC B now we see that a is present here and also present here okay and B is present here these are the present here this B is also present here it is here C is also present here but e is not present in both the strings so I'm sorry e is not present in our first string so is the answer so we can solve this using multiple ways the first approach is by using sorting how can we solve this by using something suppose outstring s is a d e f and the string T is a B e f d now what I'll do is I'll sort both these things then it will be like a it will be in the same order and this will be like a b d e F now what I'll do is I'll compare each and every character of the string and if I find a mismatch then I will return that character a is equals to J so this is present in both directions so it is from the answer now I'll compare D with B but these two are not the same so this will be the extracted because DF is presenting here so this is the extra detective and we will return this one so in this way we can solve this uh this problem by using sort T what is the time complexity for sorting this will be order of energy login where n is the length of the string for sorting this it will be again order of and login to complexity would be so the interviewer like asked you to optimize this because you know I Distributing too much amount of time for such a small problem uh what you can do is you can use hashing uh now let's discuss about passion like uh interaction we can uh should we need to use hash set or hashware should we use hash set or Outlet now you might look at this example and see I can use hash set like for example is equals to ABCD equal to a b c d g what you may think is uh assure all these values in each set and I'll compare whether these characters are present in the sector node and if the character is not present and I will return that card like it's in Brighton once uh I'll add each and every character into that based on presence now we will cover this string and you check if this character present is present in this set or suppose the name of the secret a is present in the cell so this is not the answer V is also present in the index water answer C is also present D is also present e is not present so here's the answer you might think that the solution will revoke but the solution will not go the solution will not work when there are duplicates uh let's take an example like s equals to a B e it's easy is a b now what you will do is you'll create a set and do you keep on adding these elements into the same yeah so you will add a on the second character since it does not allow duplicates you will not store the additionally now you will come to B and you will add B so you will come to 20 from you will and D Lewis you see a is it so it is not the answer this here is also present in let's say so this is also not the answer B is also present D is also present but there is an extra a here but you're counting an entire string and you haven't found the answer so in this case when there are duplicates in the string the hashtag will not work so that's why we'll use hash map the same example is equals to A a b d equals to a b d now we will take a hash map take a hashment and the hash map contains the healthcare contains sorry this is a hashback this hash map will contain e comma e-commer frequency e-commer frequency e-commer frequency is nothing but number of times the character has occurred in the Stream like uh initially you start from here and you'll uh a is not present in the map so you will add a issue 1. and we'll come here and you see a is already present so you will not add Additionally you will just increase the frequency for two you will come to B and B is not present in the hash map so you will add the which one you will come to D and D is not present in the hashtag we will add d this string and you find out the extra character now you'll come here a is present in the hash map so what you will do is you uh you will reduce the frequency bye I'm sorry the frequency of I'm sorry for this the frequency of a will become 1. foreign and we can further notice the solution the approach 3 is adding by adding each and every character suppose there is string like a b c d and T is like a b c d let's assume a value is one P values 2 is 3 and D is 4. now what you'll do is we have at least one plus we value is 2 plus 3 plus d value is 4 so the sum will be l and you will also pronounce this on level is one and the value is 2 and C value is I'm sorry B value is 2 C value is 3 and the value is 4 so that's the sum will be one now what we'll do is you will remove this sum what is 2 it is B so the answer is B this is from 97 it's SQL the ASCII values B is 90. is 99 degrees 100 different get added you will get the same answer in this way but I have explained to using small values so that you can get the approach now this is the most efficient solution that we are going to talk in this solution you are going to use heads of property Etc uh before seeing the solution you have to know the probability of xor you know that there are bits right zero one if it's work the same as you'll get 0 only and you will if you exalt 0 with any value you get that value only one if you xor 0 with any value you will get that value only if you accept same values you will get 0. uh in case of characters what you can do is if you xor a with a you'll get zero if you get so b x square a with zero you get a fixed or B with zero you'll get B by using these two properties you can solve this problem suppose the S is like a b c b is like foreign now after you do this you know you see a X or k will get tensing b h sub B will get canceled c x over c will get canceled D X or D will get canceled and the remaining will be C that's the answer uh now I'm going to explain the code you know uh I assume this the string s is ABCD understanding T is this now what I have did is I took xs0 since the Excel property does not work for characters we have to convert them into integers when you convert characters into integers they will convert into ASCII values the ASCII value of a is 97 B is 98 C is 99 gives 100 like that it will go in the next step the character CH will be B 0 x or 97 X or 98 and in the next step exercise 99 and in The Next Step D value will be xor 100 all right we'll add in the same xor for this string as well so xor is 97 xor B is 28 Etc again B is 98 against our c is 99 xor base 100 this hundred will cancel 99 and the remaining will be 98. now we have to convert 98 into character what is the character of 98 B so B is the answer so if you look here B is the extra capital so thank you for watching the video
Find the Difference
find-the-difference
You are given two strings `s` and `t`. String `t` is generated by random shuffling string `s` and then add one more letter at a random position. Return the letter that was added to `t`. **Example 1:** **Input:** s = "abcd ", t = "abcde " **Output:** "e " **Explanation:** 'e' is the letter that was added. **Example 2:** **Input:** s = " ", t = "y " **Output:** "y " **Constraints:** * `0 <= s.length <= 1000` * `t.length == s.length + 1` * `s` and `t` consist of lowercase English letters.
null
Hash Table,String,Bit Manipulation,Sorting
Easy
136
292
hello everyone so in this video let us talk about a problem from lead code the problem name is name game so let's start so you're playing a game name that's your name game with your friend now initially there is a heap of stone in this game on the table now you and your friend will alternatively take turns and you go first now in your turn you can take any number from one till three any three stones and remove it from the heap okay you can just assume that there are like n numbers in the heap you can take one stone two stone threesome from the top of the heap and you can remove them now you like then the next player will do the same thing he has three options either he can remove the first like one stone twos to another three stone and similarly they can keep on going like this until the games end when the last stone like whoever removes the last stone will actually win the game that's overall problem now how you just have to tell that whether you will win the game if you play it smartly or you will not win that's the whole problem now so this is some sort of a game theory problem uh in which like if there are multiple players or like maybe two players which are playing a game then that particular problems comes under a game theory problem so in game three problem generally try to find out solution for at least like four or five cases okay let's say that the heap like the stone of heap have four stones three stones two stones one stone ten stones just for five six examples just find out and then you start getting out some pattern and that's the world case for this problem so let's try to figure out some patterns for this problem let's say that you have uh one stone okay you have only one stone in the heap if there is one stone and you are going first so you will win the game okay so i will just also mark it out so let's say n is equal to 1 so this is n whose value equal to 1 then you will win which is like uh you will win over let's w then if n equal to 2 which means that there are two stones then because it's your first chance like you always go first so if you're going to do you can just take out both the stones because the game statement states that you can take out one stone two stone or three stones and if you take out both of the stones you will always be taking out the last one as well so you will win so in this case also you will win you know with that three stones as well you will also win but if there are four stones let's say one stone two stone three so first one now if you take out the first one the other person will take out the next three stones if you take out let's say that the first two stones the other person will take out the last two stones if you take out the top three stones the person last person like the next person will take on the last one so in all the three scenarios whatever you try to choose in the first chance the other player will try to like oversmart you and obviously will win and thus you will lose in this chance like if the number of stones is four you will definitely lose in any of the way you will possibly so in this case you will like fail you can decide on m or like let's say loose let's say define now you have five stones if you have five stones now let's say take an example of that so one two three now your actual main strategy is that to take out the last one let's say that if you in the five stone game you just only take the first stone off it's your strategy you just take out the first one out the other person will have three choices the other person can take one stone if the other person can take one stone you will take the next three stones in the next chance and you will win if the other person will take two stones you will now win because you can take out two stones other person can take three stones other you will win also so it means that in this all the scenarios if you take out the first two in the first chance because your first chance you can play it optimizately you can take it in any way so you will take out only once and in the next chance the other player will do whatever number of stone he will pick he will definitely lose in the next chance so you will always win in this so the main actual logic for game three problem is to try to like twist the game according to your logic so that you will win okay or like whoever played you want to make the person win that person that's the overall logic so you have to see that whether there is at like there is any path okay which will lead down to your answer so that the other player will definitely win whatever that person will do you just have to bring that person down to a point in which that person will do anything and that person will definitely lose okay that is the case in which you will definitely win and you just have to find out those conditions now similarly if you do it for six you will win you can try it out say when you will win so you will try to see any pattern that if you sleep like three wins then there is a loss like in like when there is a like this four then if you just do that for eight you will see that it is again a loss and then there are three wins a loss three wins a lot so you will definitely see a pattern that you are only losing when a number n is a multiple of four so if n is a multiple of four which means that n mod four is equal to zero then you will definitely lose else you will be in all the conditions so you will just directly observe it here as well else you will definitely see that you will always win so these are such a problem in which you have to just find out by observation only try to draw out some examples and try to see uh what is the actual condition that is fitting in this particular that's our logic so the codes now build like boils down to a very simple code if n is mod 4 is equal to 0 which means that it's a multiple of 4 answer is false that in this scenario you will lose and in any other scenario you will win oh that's over the logic and code so it's an o of one because you're just doing one operation for fun time vulnerability for volume and that's the world logic and code for this problem thank you for the video till the end i will see you in the next one till i keep quoting and bye
Nim Game
nim-game
You are playing the following Nim Game with your friend: * Initially, there is a heap of stones on the table. * You and your friend will alternate taking turns, and **you go first**. * On each turn, the person whose turn it is will remove 1 to 3 stones from the heap. * The one who removes the last stone is the winner. Given `n`, the number of stones in the heap, return `true` _if you can win the game assuming both you and your friend play optimally, otherwise return_ `false`. **Example 1:** **Input:** n = 4 **Output:** false **Explanation:** These are the possible outcomes: 1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins. 2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins. 3. You remove 3 stones. Your friend removes the last stone. Your friend wins. In all outcomes, your friend wins. **Example 2:** **Input:** n = 1 **Output:** true **Example 3:** **Input:** n = 2 **Output:** true **Constraints:** * `1 <= n <= 231 - 1`
If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?
Math,Brainteaser,Game Theory
Easy
294
847
hello everyone today we're going to be solving a programming question called the shortest path visiting unknowns this is a hard question and basically this question wants us to find the shortest path to visit all of the notes in a graph so over here I have an unweighted and undirected graph with the nodes 0 1 2 &amp; 3 and the shortest the nodes 0 1 2 &amp; 3 and the shortest the nodes 0 1 2 &amp; 3 and the shortest path here is from 1 to 0 then from 0 to 2 then from 2 back to 0 and from 0 to 3 the shortest path includes 4 steps and it is solved using the smart breadth-first search the idea of the breadth-first search the idea of the breadth-first search the idea of the smart breadth-first search is to push smart breadth-first search is to push smart breadth-first search is to push all of the nodes to the queue and then perform a breadth-first search on every perform a breadth-first search on every perform a breadth-first search on every node simultaneously and while we are doing that we have to store the steps of the visited nodes with a 32-bit in the visited nodes with a 32-bit in the visited nodes with a 32-bit in representation for bit masking for example in here we have 4 nodes 0 1 2 &amp; example in here we have 4 nodes 0 1 2 &amp; example in here we have 4 nodes 0 1 2 &amp; 3 and let's say that the nodes 1 &amp; 2 are 3 and let's say that the nodes 1 &amp; 2 are 3 and let's say that the nodes 1 &amp; 2 are visited then the 32-bit and visited then the 32-bit and visited then the 32-bit and representation of the visited nodes would be 0 1 and the last bit is to represent the node 1 and the penultimate bit is to represent node 2 and so on okay and the reason why we cannot use the traditional breadth first search is because in this problem we can visit nodes and edges more than once therefore if we use the traditional breadth-first if we use the traditional breadth-first if we use the traditional breadth-first search we are going to encounter cycles or we will get stuck so to avoid getting stuck and to avoid cycles we are going to use the smart breadth-first search to use the smart breadth-first search to use the smart breadth-first search where we will conduct breadth-first where we will conduct breadth-first where we will conduct breadth-first search simultaneously on all notes and then use the bit masking for tracking all of the visited nodes and here we have the code in Python that implements the smart breadth-first search approach first we will store the length of the graph into a variable so that we can use it without having to recompute it in the future then we set the goal to be 1 bits for n times because that will mean that all of the nodes in the graph are visited now we're going to initialize the Q and the Q is going to have the length of the graph and it's going to store a topple with the current node and then the bit mask representation of all of the visitant nodes while in the current node and after that we'll store the steps the number of steps is going to be 0 in the beginning and we're also going to store the current node and current paths inside of the steps so that we can search for it in the future and then we're going to perform our breadth-first we're going to perform our breadth-first we're going to perform our breadth-first search taking into account the current paths and the current notes and if the current path is equal to the goal meaning if there is four ones if we are basing it off our example graph then we will just return the current steps because that will be the number of steps that was needed in order to reach that goal and otherwise we'll loop through the child knows and then we'll perform the breadth-first search while taking the breadth-first search while taking the breadth-first search while taking into account the bit messed and we'll update those bitmask in this way and after we perform this breadth-first search approach we will breadth-first search approach we will breadth-first search approach we will eventually get to the goal and return the current steps a good thing about this algorithm is that each notes visited path is maintained so that we can check and see if this path was already taken before or not that way we can avoid cycles and also avoid getting stuck now I hope you enjoyed this algorithm please let me know if you have any questions or comments in the comments down below please like and subscribe if you like this video and see you in the next tutorial bye
Shortest Path Visiting All Nodes
shortest-path-visiting-all-nodes
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge. Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges. **Example 1:** **Input:** graph = \[\[1,2,3\],\[0\],\[0\],\[0\]\] **Output:** 4 **Explanation:** One possible path is \[1,0,2,0,3\] **Example 2:** **Input:** graph = \[\[1\],\[0,2,4\],\[1,3,4\],\[2\],\[1,2\]\] **Output:** 4 **Explanation:** One possible path is \[0,1,4,2,3\] **Constraints:** * `n == graph.length` * `1 <= n <= 12` * `0 <= graph[i].length < n` * `graph[i]` does not contain `i`. * If `graph[a]` contains `b`, then `graph[b]` contains `a`. * The input graph is always connected.
null
null
Hard
null
528
hi all welcome back to cracking the fang interviews today we are going to be looking at lead code number 528 which is random pick with weight this is a very important problem and you can think of this problem as a random number generator which is very commonly used in software engineering and this problem again is popular and it's been asked at microsoft google and also amazon interviews let's jump right into the problem so here we are given an array of positive integers w uh and each position in the array wi describes the weight of the ith index and again the that is zero index so what this means is we have an array with indexes 0 1 and 2 there is a weight value which is a positive value you can think of this as 2 1 and 3 just for an example and what the question wants us to do is we need to call the function pick index so we're going to be calling a function called pick index which randomly returns an integer so it's a random number generator essentially and it's going to return an integer in the range of one of the indexes so the candidates of a random number generator are the indexes 0 1 and 2 and we've been given weights for each of these so as an example if w was 1 and 3 the probability of picking index 0 would be 1 by 4 again this arrays adds up to 4 and the probability of picking the index 1 would be 3 by 4 which is 0.75 and 0.25 respectively which is 0.75 and 0.25 respectively which is 0.75 and 0.25 respectively so let's uh try to understand this with an example uh and here is a snippet from lead forward i'll put the link to the problem in the description below the first thing that we get in is w the array w and again these are the weights uh then we call this function picket index which we are supposed to write later and every time we call pick index uh we return a random number so if we have the numbers 0 and 1 in this case with probability of picking them as 0.25 and probability of picking them as 0.25 and probability of picking them as 0.25 and 0.75 0.75 0.75 if pick index is called we'd return 1 with a probability of 0.75 we'd return 1 with a probability of 0.75 we'd return 1 with a probability of 0.75 and 0 with 0.25 and 0 with 0.25 and 0 with 0.25 as you can see in this example whenever pick index is called one is returned the majority of times essentially three-fourths of the time essentially three-fourths of the time essentially three-fourths of the time and we still see 0 which is approximately one fourth and again this is a random number generator is what we are trying to develop here so let's try to understand how we can come up with an approach to solve this problem and i'll start working through the fundamentals first before we dive into code um so let's quickly look at what's been given and how we can get where we want to so we've been given this array w which has two numbers one and three and this is these are our candidates zero and one so if you just think of these numbers as um which are weights but as uh distance right can we do something along that angle is the first thing i want to emphasize on what i mean by that is let's just draw an axis for example in x-axis and again x is a for example in x-axis and again x is a for example in x-axis and again x is a distance and you're at index 0 i would say the origin of the axis and at distance 1 um this is the window for the candidate 0 which is the index and so what i mean by that is if you have a finite distance in this line and you toss a coin uh where does the coin land essentially could tell you what candidate to generate so if uh the coin lands between zero and one your big candidate zero if the coin lands somewhere between one and um some other number you'd pick the candidate 1 in this case this is how you can come up with a simple random number generator and what we are going to have to do here is be cumulative in terms of a distance so if you're at you start at zero you take the first weight add that to zero you'll end up at one now you're at one you take the second weight add that to one you'll be at index three and now let's just try to understand this better or let's try a few examples so i toss a coin right when i say a coin i mean i just come up with a random number uh between this range now which i've established for myself again a quick typo here this should be four not one because we are doing cumulative sums so if i come up with um with a random floating point number for example it's ah i call pick index i come up with a number and i have 1.3 number and i have 1.3 number and i have 1.3 i am in this range and i pick one if i pick another number between 0 and 4 for example 3.2 again it can be floating point of 3.2 again it can be floating point of 3.2 again it can be floating point of um or just an integer that doesn't matter it you're going to be somewhere here you'd still pick this range because you lie there but you for example you know call pick index again and you end up with the number uh 0.8 you'd be able to pick 0.8 you'd be able to pick 0.8 you'd be able to pick index zero the random number as 0 so this is a concept i'm going to use to design this weighted random number generator if that makes sense right now and what i'm essentially doing is using distance as um weights rather than just treating weights as proportions so what i did for that just a quick recap is essentially broke down the weights in terms of distances so if you have higher weight you have more distance and you're still generating uniformly between this range so you'd end up picking one of the windows lying in one of these windows which would correspond to a random number which you can generate with your program so ah let us look at code for this and again let's talk a little bit about time complexity before i actually dive into the code the way we could simply implement this is ah generate a random number um and i'm gonna call that complexity of one and then um we know the value for example 1.3 and we go about example 1.3 and we go about example 1.3 and we go about linearly so we know our you know our limits to the uh distance windows that we have come up with and we start subtracting so uh the first window ends that one i'd subtract 1.3 from one i still have i'd subtract 1.3 from one i still have i'd subtract 1.3 from one i still have 0.3 0.3 0.3 then i take this forward with the next margin value which is 4 minus 0.3 next margin value which is 4 minus 0.3 next margin value which is 4 minus 0.3 which would be around 3.7 which would be around 3.7 which would be around 3.7 so as you can see we came up with a positive difference the what that tells us is 0.3 can be us is 0.3 can be us is 0.3 can be accommodated within this window so you essentially pick the number one so if we implement the logic this way we'd have to go through all um you know all of the boundaries meaning one value for each index that we are that is a candidate for random number generation so the complexity of that would be often and this is a valid approach now the question is can we do better and to answer that question i want to emphasize on using cumulative sums so we came up with these values 0 1 and four and again if i just look at the edges of my windows i have one and four and as you can see this is always going to be in sorted order because we are doing cumulative sum and as soon as we hit that window which sort of satisfies our some constraint meaning we get a positive value we can say okay this is where this is the candidate we generate so one in this case so given this isn't sorted order the first thing that comes to my mind is binary search so what i'm thinking of right now is a linear problem a linear search problem can be converted into binary search if a array a when i say a is sorted so that's how i thought of binary search and i'd um use that for this problem again linear is a good method but if we use binary search we can reduce the time complexity further which would be the optimal solution for this problem though of login all right now let's just look at the code and take a walk through so this is a snippet of the code from read code that i've written the first thing we do is um essentially figure out the length of the given uh w uh use this to come up with a cumulative sum array this is nothing but the distance array that i talked about earlier which has its margins and we populate the cumulative sum array by adding the previous boundary with the new weight so that allows us to deal in terms of distances along an axis so this is the weight and this is the distance all right so now let's dive deep into the pick index the first thing we do is we generate a random number and we multiply that with the last value and cumulative sum what this does is we are essentially generating a number between 0 and this last value which i'm just gonna call uh capital c for now and i've also written the linear search uh code here we'll go through that first so we understand how we can optimize this from offend to of login the first thing we do is we go through it and we uh start subtracting our the number we have generated so if we are uh if we have these three windows and our random number lies somewhere here we what we do is we essentially go through each of these margins and subtract them so the moment x turns 0 or negative it means it's been consumed by a window and we output the index so that's how we implement linear search for this question um and let's look into the smarter way now we will use standard binary search we set the indexes of searching which is the first and last index and we calculate the mid um and what we do is we trade while start is less than n and again this is standard iterative binary search uh something i'm doing here is uh being smart about it and calculating bit again i'll touch upon this in a bit but it's essentially the same calculation as before the reason we have to do that is um once you get into the iteration um you're able to um sort of revaluate your mid as it changes dynamically all right so if we find the uh cumulative sum to be x meaning if i generate a random number and i'm gonna take an example so this is the edges 0 1 and 3 and the value is 1 i just pick this index and output it will be 0 and this is index 1 but in this case as i said i'll pick one so it return the index if the cumulative sum is less than x i move my start pointer to the left so i move my start pointer from here to here the mid and if that's not the case i move it to mid and not mid minus one that's an important point to note for this implementation the reason for that is if we are at if we have these weights one and three and uh we wanna uh we essentially one you know and let me just add another one which would be four and my end is here my mid is here my star start is here so if we are at these index 0 1 and 2 um and i figure that 3 is you know not satisfying the condition it is less than the number i'm looking for sorry it is greater than the number i am looking for uh which the random number in this example i can consider is 1.2 consider is 1.2 consider is 1.2 so even if that is the case 3 is greater than this and i want to search it so one point two can now hypothetically belong to one and three but i still wanna check for one right um it could be pos i don't have access to one right now i am i'm at three it could be three could be an upper bound window so can be the uh the other window the lower windows so what i'm gonna do is uh set end to mid and not make it mid minus one so what that gives me is i can still come back to 3 as the answer and generate 1 rather than go to 0 which is not the right answer right because in terms of distances one ah does not encompass one point two so if i were to draw this for you quickly um i am at zero my first cumulative distance is one the other one is three one point two is here so i still need to look at three as my upper bound window rather than just confine my search space to uh the left or the lower indexes that's why uh this is important to note that end is mid and once i get out of this loop the condition the only time that would happen is uh start equals end the loop would terminate because this would no longer hold i have to recalculate my mid because once the index is changed mid is not reevaluated since it's in the while loop so i recalculate mid and i return that as an index awesome thank you for watching cracking the fang interviews if you like the video please like share subscribe to the channel and stay tuned for more exclusive
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
57
hey guys welcome back uh today we're going to be looking at insert interval which is a medium difficulty problem um so let's just look at the description you're given an array of non-overlapping you're given an array of non-overlapping you're given an array of non-overlapping intervals called intervals where intervals at i is equal to the start at i and end at i so it's equal to an array of size uh 2. and so it represents the start and end of that interval and intervals is sorted in ascending order okay given the first number of the inner array you're also given an interval called new interval and it's given a start and end value and repre and that represents the start and end of another interval and so our goal is we're going to insert the new interval uh in intervals such that intervals is sorted in ascending order by start at i and intervals does not have any overlapping intervals merge overlapping intervals if necessary so we're going to return intervals or an array whatever after the insertion okay so if we look at this example right here we have 1 and 3 and 6 and 9 we are going to insert two and five okay and so let's just go ahead and look at um let's go ahead and look at this ex or um a similar example we're going to look at it over here so this is the second example all right so this is our intervals array and then this is the new interval that we want to insert into this array and so our intuition is to uh first we're going to keep an eye on the um first value here okay uh right here um one of the first index the zeroth index and we're going to see if that is less i'm sorry the first uh index and not the zeroth index so we're going to look at this 2 and we're going to see if it's less than this 4. and if it's if this 2 is less than this 4 it doesn't overlap with this and so what we could do is we could go ahead and create a new array okay and in this new array if they are not overlapping with this four eight we're going to stick them in the array so here we're just going to stick one and two in the array and then we're going to go to the next one so we want to see if um this value right here is uh is less than um this value right here and it's not okay so we need a different condition so what we want to do is we then want to check to see if this value right here is a less than or equal to this value right here and if it is we want to merge these together okay so we're going to we don't know how big this merges because this merge could stretch across multiple elements and so what we want to do is keep a running tally so we're going to keep a running tally called low val and high vowel and so um low val is going to be we're going to set it at new interval at 0. so it's going to start at 4 and the high val is gonna start at eight all right and so what we wanna do each time we see something that merges is we wanna say well what is the minimum amount between our low val that we currently have stored and intervals at index at zero okay so intervals that index at zero would be this thing okay um because this is the one that's overlapping what is the lowest value here and we see that three is indeed lower than four so we're going to take this four and it becomes a three and then we're going to take the maximum between this value and high val okay and so 5 and 8 is the higher value and so that stays the same and then we're going to go to the next one and we're going to say well is this value right here less than or equal to this value right here and it is less than or equal to this value right here so we're going to do the same step we're going to say well what is the lowest value between 6 and 3 well 3 is the lowest value so that stays the same and then what is the low the highest value between seven and eight is the highest value so that stays the same okay and then we go to the next one is this value right here less than or equal to our high value okay or i guess it is our high value but it should it's really this right here but that is our high value at the moment okay and so it is it's less than or equal to and so it is equal to and so what we're going to do is we're going to take the low value between 3 and 8. and 3 is the lowest value and then we're going to take the highest value between the current high value which is 8 and 10 and so this becomes 10 and so our merged interval is 3 and ten all right and so we'll go to we'll do this one more time we're going to say well is 12 uh less than or equal to uh 10 and it is not okay so at this point we have found our merged interval and we want to insert that into our new array okay so this is going to be 3 comma 10. and then we continue on the next uh value or the next uh condition or loop is we're going to be checking um the rest of the values so while index that we have created um is less than the length of this interval so any uh thing after this point we just want to add to our array okay and so we see the 12 16 there so we're just going to add that to our array and then we're going to return this new array okay so that is basically the algorithm that we're going to be using to follow this so we're going to go ahead and just go ahead and get started so we want to create a new array well you know arrays have fixed lengths and we don't know how large our new array is going to be so what we're going to do is we're going to just create an array list and so we're just going to save list uh and so this is going to be a type int and we're going to call this merged okay and then we're going to create that index because we're going to be using while loop so we want to keep track of this index so we're just going to say index is equal to 0. we have that low and high value that we were talking about so we're going to say low vowel is equal to new interval at zero so the smallest number of new intervals and then end high vowel is going to be a new interval at 1 which is the highest value of new interval and then we just start our while loops okay so we know that the first condition was while intervals at um our current index which is zero if the largest number of that is less than the smallest number of new interval we're just going to add it to our merged so but we have a different another condition here so we want this to also happen only while index is less than intervals dot length okay uh because otherwise you know we could still try this and we might get index out of bounds or something like that okay so and then we're going to try our condition that we were talking about in our example so i index and one is less than new interval at zero okay so that's our while loop and we said that if this is true what we want to do is just keep on adding the intervals that this that fit this description so we're going to add intervals at index and then we're going to advance the index by saying plus all right okay fantastic so it this condition no longer holds true and so when this condition no longer holds true we're going to still check this condition right here all right so we're just going to say okay and intervals at index at 0 is less than or equal to new interval at 1. all right and if this is true we're going to do exactly what i said we're going to take our low value and get the minimum between our current low val and the value at index at 0. so the low value of our current item that we're looking at so intervals that index at zero okay and so that's going to get the min and then we're going to say hi val is equal to math.max and we're going to take the high valve uh we're going gonna take intervals at index at one and so we're gonna compare the two highest values between the two elements and we're going to get the highest value and keep that value and then here we're just going to say index plus and then once this is no longer true we have the merged element and so what we're going to do is we're going to say merged dot add and we're going to say new ent and we're going to say low vowel and high vowel okay and so that's going to add that right there and then we have the last condition so we're going to say while our index is less than intervals at index plus we're just um not intervals dot length i'm sorry we're just going to add the rest so we're just going to say merged dot add okay and then at the end we're just going to return that as a new array this is our return type right here we have a problem we have been using an arraylist and so we need to convert this arraylist back into an end array and so we're just going to say uh return merge.2 merge.2 merge.2 array um so size okay and so this returns our um our 2d array okay so let's go ahead and see uh if this is gonna pass i always have um seems like always have some syntax errors but this time we do not and so let's go ahead and submit okay so faster than 70 uh percent and uh so memory is good too all right so um right here if we're talking about big o notation as far as time complexity it is uh big o of n because we're just looping through uh this once okay and um here um let's see here if we go to the description um okay so we do create a new array to store our values and so the uh memory complexity is of n as well okay so um that is going to be the big o notation uh for uh time and um memory and uh otherwise um you know that is it so if this was useful to you uh go ahead and like and uh subscribe um otherwise i will see you in the next one and i believe we'll be doing a merge interval um as well uh so um look forward to that and i will see you then
Insert Interval
insert-interval
You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the `ith` interval and `intervals` is sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval. Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary). Return `intervals` _after the insertion_. **Example 1:** **Input:** intervals = \[\[1,3\],\[6,9\]\], newInterval = \[2,5\] **Output:** \[\[1,5\],\[6,9\]\] **Example 2:** **Input:** intervals = \[\[1,2\],\[3,5\],\[6,7\],\[8,10\],\[12,16\]\], newInterval = \[4,8\] **Output:** \[\[1,2\],\[3,10\],\[12,16\]\] **Explanation:** Because the new interval \[4,8\] overlaps with \[3,5\],\[6,7\],\[8,10\]. **Constraints:** * `0 <= intervals.length <= 104` * `intervals[i].length == 2` * `0 <= starti <= endi <= 105` * `intervals` is sorted by `starti` in **ascending** order. * `newInterval.length == 2` * `0 <= start <= end <= 105`
null
Array
Medium
56,715
1,928
hey everybody this is larry this is me going with q4 of the week of dubai weekly contest 56 minimum cost to reach destination in time so uh i feel really sad about this one because i knew how to do it and i tried in different ways but i was just being dumb to be honest um i really shot down this way earlier i had six wrong answers because i was playing around with different ways of solving it but the short answer is that i just did it in the wrong dimension um so this is going to be a is the shortest path problem and a daisies problem and one thing to keep in mind about the shortest path is that it is a greedy problem right with the shortest path it is greedy in that you know so you're trying to when you reach a node or some sort of node um when you reach it is already going to be the best uh time or well it's gonna be best in whatever you're optimizing so i made a mistake here in that i actually tried to optimize by cost first and that was just really bad you could watch me stop it live during the contest next um after my explanation but basically the key thing to note is that you don't want to do loops right because if you do loops you're going to get around forever maybe the first thing to notice is that max time is a thousand so you can't do things based on max time uh based on the notion of max time and n where n is the number of nodes as long as you don't keep on doing sub loops and fill everything up the other thing to know is that edges is also a thousand um so you're able to do this in good time as long as you don't keep on revisiting the same note multiple times um or same if you don't reuse the same edges in a loopy kind of way you should be able to be fast enough because keep in mind that this isn't each edge on each note this total number of edges so and i really should have been able to do this much faster but i am just not in a good shape i suppose um but yeah but basically with dijra you're trying to use heap and that's basically here and i'll go with the basic idea of dijkstra first and then we'll go over the after the change that we need for this one but basically here um in our notes it's going to be actually time and instead of just our nodes you know usually when you do digest you have a node and here you're trying to optimize or previously you would optimize for some time but here our node is actually node and time as a new node you go no prime say right so basically because wha what does this mean that means that at any given time we want to at every node and time pair we want to minimize the number of costs so that's basically the idea here um this is in the beginning this is straightforward uh passing of the input we converted to an edge list um we set some infinity we set the best again this our best now is it's just dijkstra but best of um i j is equal to the minimum min cause of null i at instance j right instant time j okay and here the idea is that we are going to push we want to minimize the time and here this is where i made the mistake during my contest is that i actually did the frontier with respect to cost so we're trying to figure out the cost but actually what you want to do is have to frontier the time because then now you have an invariant and what that means is that at this given time we also store the lowest cost of the node of every original graphs node and because what that means is that when we process we when we process this we um so this looks so the rest of this is going to be standard dice drill i'm not going to go over it too deeply um but because this is nicer just you know if you are having issues at this part definitely um definitely practice other dijkstra's problem so i'm going to talk about instead um the optim the change you need to make for this district's problem which is that okay so because we're looking at the time component the time dimension and that means that because now we're optimizing by time is going to be strictly increasing right and because time is strictly increasing that means that if the cost is higher than the previous best cost that we have then that means that we are already that means that it costs more time and more money right if that has more time and more money then it's never going to be the answer so that's basically why we have this optimization here and also this optimization here and this is the only change from the standard dijkstra to make it fast enough um is because if this gives us a higher cost and we know that the time is going to be a higher time just because we know that all the time is going forward um that's basically it um yeah and that's basically the idea behind this problem um basically you're trying to eliminate you're trying to branch out all the things that are never going to give you the best answer and that's basically what i did here um that's all i have for this one you could kind of see me sloppily solve this during the contest i eventually did get it but it did cost me q3 because i should be able to get q3 it is what it is let me know what you think and yeah give me some love and i was you could watch me sell for live during the contest next oh yeah just to add a quick uh thing is that actually for this one you can sort by cost as well but you have to basically just make sure that your time if you're doing the cost frontier um you just make sure that your time component doesn't um doesn't go beyond that so it'll look basically the same ex because basically what you the only thing that you're trying to eliminate is something that is both costs more and takes more time so as long as you're able to eliminate that it becomes doable i should have been able to do this during the contest but i think i was just watching it too much trying to think of cute way it is what it is anyway thanks for your support i'll see you later okay let's skip ahead real quick i don't know a lot of people seems that we've gotten this one so should be able to get this one quickly hopefully ideally 25 people so maybe not that many people um minimum cost what's up what am i saying okay so it costs both edges and minutes so then it is the question of is there can we binary search on any of these summation of the passing fees and the cost is on this t so max time is 30 minutes whatever try to approach dijkstra dice draw on time and cost does that make sense time is a thousand and this time it goes 1000 means that what's max time is he goes to a thousand so that's the biggest one is it yeah i think so i think just a million notes that's going to be really expensive though for dijkstra but people have gotten it pretty quickly so maybe that is roughly right i don't know okay um what is n xy2 multiple edges between two nodes we would thousand edges each so that's gonna be too slow we do it the dumb way maybe you cannot do true in the dumb way can you do dynamic programming maybe but it's still the same cause it's still too expensive to go to because it's like n cube or something and square state and cube things can we reduce that dynamic programming by time and the crap could get intense though uh mid-cost doesn't make sense either mid-cost doesn't make sense either mid-cost doesn't make sense either because summation of passing fees so okay hmm so it's okay that point is too slow anyway still given this graph even binary search is too slow i don't know it's how would you do it whether you have many cause of a path i'm missing something weird i don't think i'm missing anything weird but oh i am missing something weird the number of total edges is only a thousand i am dumb okay so what does that mean for me then we press e okay i am dumb then okay fine i missed that i thought each note could be a thousand so then okay oh i am dumb okay five uh so dumb time costs x which is zero okay so all right cos time node minimize the cost okay um hey guys just in case well actually i think it crosses the sauce so that's okay foreign yes idea is greater than the current cost plus and he plus oh man and t is less than equal to max time then we do this and then we do t that's the cost that's the time and that's the node okay you also want to do okay if x is equal to n minus one then t continue okay there's also one more for the dice true if that's of x to t is greater than cars continue okay well that's not good okay so it does some stuff let's go from zero to one and okay hmm why am i not right 25 on note 3 isn't that where we're going to go now we're going to go no whatever 10 what oh that's the cost this is that way this is 30. hmm still not right but 2626 okay i mean it's something it's not the right thing but so guys i just look at one of these why am i all the way up to 300 cars well because of all the time i guess so this should check at the eleven oh whoops if i meant to mend it the other way oops see there it is still 26 wait what um it's why is this not at 11. oh whoops i am dumb okay i don't know i mean it might time out but at least hopefully it's more correct um let's see also i feel like to be honest if this was not python i have no doubt that this would be fast enough so i might need to rewrite in a different language um because basically yeah that's a little bit sad maybe i'm wrong on that to be honest let's think about the analysis first real quick well we have a million nodes i think we're looping we don't want the loop is the answer but hmm just checking that it compiles okay i think a million should even know actually is that true yeah maybe should be okay i know let's make 25 why not okay still good on the compiling it's been a while i haven't done c plus first in a while so it's been a while i guess it doesn't really matter when minimizing my timer or whatever okay still good just thinking for a second i hope that's right i actually don't know hmm i always forget the tuple syntax do this so it's a pier so ah this is so stupid and i don't even know if this works to be honest so oh whoops okay so that looks good let's give it a summit might still time out but hopefully it's slightly faster well seems like it times off earlier even that is actually kind of sad so it should be just a million times again but maybe i do more than i see if one the thing is that we look at each edge more than once that's my problem ah this is just one of those contests where i don't know how to do anything yeah now that i think about it doesn't really make sense the way that i did it but how do we make sure that we don't do sub loops my problem right here now is that i do get into loops i have to do one more optimization somehow and i do a binary search on a cost so the cost is going to be at almost a million and then it just becomes simple dijkstra let's try that half an hour left okay hmm let's do in python just in case that doesn't make sense because at the verse you just do the max cost which is what we're doing here now anyway so that's why i didn't do the first place but how do i this is like my worst contest in a while thing is you want to be able to get to certain place at a later time and also if that's a mint cost right how do you eliminate that one hmm is it because if you want to come in later but has a higher cost how do you do that how do you prevent yourself from doing that how do you get how do you choose to check that it doesn't get dominated so that is the question all right okay so we just want to make sure that we don't go in loops right maybe we could at least keep remove the most obvious one i mean that seems fast enough but what if i don't have this thingy if i don't have it's still this is faster maybe slightly a bit but there's still so many different cycles hmm okay i don't know this is in terms of cause all right and the latest of why it's faster but i don't know if this is right let's give it a yellow it's like four times faster but okay so i get a wrong answer on this one i wasn't sure about but i also have no idea how to do it how do you prevent self loops that's the question doesn't even seem that much faster it just seems random if i could prevent soft loops then it should be good but i'm trying to find a dominating one if it gets dominated then what happens it's okay um i do oh no this is greater than well that's not good hmm is this one i mean it's a little bit faster but it's not really that much faster to be honest let's give it a go because i have no idea no other things to do but i think i just need to think about this in a different way and it's not even right okay fine i thought there it might not be right it's a little bit greedy but why am i getting this well a lot of people got in this one but i can't do it this i think if i could handle the looping situation i could fix it but i can't do it and why am i so bad at this my graph here is really weak nowadays i mean the dp solution is the same right because they could just all be once and then that would be a mess going back and forth oh it's sorting by time right yeah oh not sorting by time does that matter don't imagine it matters but maybe now there's a different property if we sort by time then okay i am dumb okay so if we swap by time then the cost will have to be lower right tcx what am i getting this shouldn't matter t is 36. i mean that's true that's how it bounced but wouldn't this be bounded huh did i mess something up so it goes over why oh wait i lost my earlier test case unfortunately but now that means that if the cost lois all right okay i mean i thought that we can do this i mean obviously i think if i just remove this it still works but is it fast enough i only have seven minutes i might as well yellow submit but i don't know i wish i kept test case and so 1158 or something it's too slow it seems like because now we have more time and more whatever does that solve it um uh i am dum-dum okay uh i am dum-dum okay uh i am dum-dum okay that was yeah thanks for watching thanks for support hit the like button if you subscribe or enjoy me on discord let me know what you think about this contest and this problem and this explanation i will see you later stay good stay healthy stay cool and good mental health bye
Minimum Cost to Reach Destination in Time
number-of-orders-in-the-backlog
There is a country of `n` cities numbered from `0` to `n - 1` where **all the cities are connected** by bi-directional roads. The roads are represented as a 2D integer array `edges` where `edges[i] = [xi, yi, timei]` denotes a road between cities `xi` and `yi` that takes `timei` minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself. Each time you pass through a city, you must pay a passing fee. This is represented as a **0-indexed** integer array `passingFees` of length `n` where `passingFees[j]` is the amount of dollars you must pay when you pass through city `j`. In the beginning, you are at city `0` and want to reach city `n - 1` in `maxTime` **minutes or less**. The **cost** of your journey is the **summation of passing fees** for each city that you passed through at some moment of your journey (**including** the source and destination cities). Given `maxTime`, `edges`, and `passingFees`, return _the **minimum cost** to complete your journey, or_ `-1` _if you cannot complete it within_ `maxTime` _minutes_. **Example 1:** **Input:** maxTime = 30, edges = \[\[0,1,10\],\[1,2,10\],\[2,5,10\],\[0,3,1\],\[3,4,10\],\[4,5,15\]\], passingFees = \[5,1,2,20,20,3\] **Output:** 11 **Explanation:** The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees. **Example 2:** **Input:** maxTime = 29, edges = \[\[0,1,10\],\[1,2,10\],\[2,5,10\],\[0,3,1\],\[3,4,10\],\[4,5,15\]\], passingFees = \[5,1,2,20,20,3\] **Output:** 48 **Explanation:** The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees. You cannot take path 0 -> 1 -> 2 -> 5 since it would take too long. **Example 3:** **Input:** maxTime = 25, edges = \[\[0,1,10\],\[1,2,10\],\[2,5,10\],\[0,3,1\],\[3,4,10\],\[4,5,15\]\], passingFees = \[5,1,2,20,20,3\] **Output:** -1 **Explanation:** There is no way to reach city 5 from city 0 within 25 minutes. **Constraints:** * `1 <= maxTime <= 1000` * `n == passingFees.length` * `2 <= n <= 1000` * `n - 1 <= edges.length <= 1000` * `0 <= xi, yi <= n - 1` * `1 <= timei <= 1000` * `1 <= passingFees[j] <= 1000` * The graph may contain multiple edges between two nodes. * The graph does not contain self loops.
Store the backlog buy and sell orders in two heaps, the buy orders in a max heap by price and the sell orders in a min heap by price. Store the orders in batches and update the fields according to new incoming orders. Each batch should only take 1 "slot" in the heap.
Array,Heap (Priority Queue),Simulation
Medium
null
341
hey everybody this is Larry this is day 20th of the Friday well it is a Friday but the leco Friday daily challenge hit the like what Friday what am I talking about uh but yeah October 20th uh Leo daily challenge on the Friday uh I'm a little bit uh tired uh I say that a lot but uh my internet's a little bit slow today hm or just my computer's a little bit slow uh but yeah I just got to Hong Kong I didn't sleep well at all I have a 7:00 a.m. flight uh well at all I have a 7:00 a.m. flight uh well at all I have a 7:00 a.m. flight uh and 7: a.m. is just like awkward cuz I and 7: a.m. is just like awkward cuz I and 7: a.m. is just like awkward cuz I don't know I just can't get enough sleep so yeah uh anyway here I am now hopefully you know still alive and all these thingss but let's talk at today let's take a look at today's problem if I'm I don't know my apologies for the qu of today we'll see how that goes follow me on Instagram you want to see what I'm up to you know it is a day delay because I've been just I don't know uh 341 FR nested list iterator okay that's so is it just that you have a uh what was that if you have an iterator and then you okay uh I guess that's what it sounds like so yeah um okay so yeah so the way to do these things is just I mean the Technic two ways to do it right one is using an explicit stack and one is using an implicit stack which is you know recursion and the way that I think I would do this normally and by mean normally as in not in an iterated kind of way um is by yeah just a recursion right basically what you're doing is essentially a deer search of the list or nested list right um but of course for this particular problem we're given um what are we giving we you know we're doing it one at a time so we will do an impit stack oh yeah an excit stack sorry so let's get started uh I don't think I have anything more to add to that uh background hopefully my computer is a little bit you know not acting weird uh yeah all right so yeah sub. stack right and then maybe sub. F uh next is go to um yeah none right I don't know that's quite the right way to do it cuz I think what I want to do is just get one item first and then store that right so yeah let me see uh maybe I have a function called like self. update next or something like this right um and of course um how do I want to set up the current thing well uh self. is equal to um how do I say this yeah I mean I think maybe it's just impress It On The Stack because then now uh let's say we have sub that update next oops right what do we want well um we want to just put everything on the stack so uh well we definitely need to kind of keep a reference to the list but uh and maybe I lied on the stack maybe the stack would be Nest the list and then index zero or something like this right so that would be the first item right so then now we can look at the uh so top is equal to S stack of1 uh if it has zero items then you know then we're done I suppose so let's do so. stack is equal to zero uh solve. next is equal to none and we return I think otherwise so then we have this right we have uh top I this is the top of the stack we have the top list and then the top Index right so then now we take a look at it right so um while uh how do I check oh the nest integer has these things that's what I wanted to do right so while um top list of top index is uh is integer or not integer obviously if this is a list then we want to do sub. stack. aen we want to go into this list so that means that this is top list. get list and then zero for the first item right and then at the end of this uh and then of course we update this again and then at the end of this then that means that uh toess is an integer right so or the top this top index is an integer uh so then now we can just set sol. next is equal to top list top Index right and uh and we want to pop and or technically we want to just update the index but I think the way to do that is pop so I think it technically doesn't change but okay fine so we do pop right and then now we append back um top list uh top index plus one right so we also that means that we have to do something like um yeah so we read so we add a finger here right but um maybe if top we only do this if top index is less than the length of top list so then it's almost like a pop before in a pen so if we go out then we pop right that should be right except for I don't I have to when you do a pop like when you do an expressive pop you want to increment the uh index of the thing that below so maybe something like maybe I do something this is so awkward uh okay so we pop right and then we update okay and then now and this is Technic actually I got it well this is this plus one obviously because we're incrementing otherwise so what happens otherwise it goes over so then we leave it popped but then that means that we have to um do the same thing again which is to say um in we want to do something like this right and then we kind of uh look at the top item again and then and yeah so then we add this to a w Loop and we have to make it a smaller but I have to kind of you know be careful about it so maybe um okay oh actually this pop doesn't exist because we already popped here so then now we look at this and then now while top x + one is greater than top x + one is greater than top x + one is greater than or uh is greater than or equal to length of top list then we pop and then we do this again I suppose this is really awkward though I feel like I'm kind of repeating myself in a few places so that's why it feels a little bit weird but um cuz this one is technically an update that's why but I don't know I guess we'll see so yeah we next we do a you know return element is you go self. next and then we return uh or after we do it update next and then has next it just return um self down next is none uh or it's not none I guess right all right let's give it a one not um what does that mean uh H I have to do get value or get enter instead of just the thing uh what's the self done next oh yeah get they get integer in object not Coro what are we supposed to return no that looks right uh in object not cor that I mean that means that so self. next should be an integer what am I supposed to return h so I have a very awkward setup so I'm like lying on the bed in a really weird angle um U I'm trying to understand what the thing is in well or like um I thought next so it is and I have no idea what the issue is to be honest all right let uh let's Okay um okay I think update next should just set this to next uh to none and then if it doesn't do anything but um H don't understand what I'm doing wrong here it is a little bit unclear it's a little unclear what decoring or how decoring it in a way such that I'm returning an inder for them de call but this is the Constructor right it's very confusing I don't know I'm going to add some print statement I suppose uh I have no idea uh what the error is really and it's doing it on one uh one element so that's kind of bad okay so you have an integ equal to one right so IND not corable do I get to the end before not corable yep uh so after does it set the next prop property uh okay so it gets set the next property and the stack is popped has none has next so if it's not none then it is true right H so it doesn't do this what is going on does it called next at all has next is this returning true am I like just confused so it is not none so that's true so has next with am I just confusing it okay so then why it doesn't not call next here I'm so confused maybe there's a syntax thing like it's that's what it said right like what I don't so like I feel like I'm missing some weird context thing or is it's not even coin this I think that's the problem I'm so confused I feel like I'm missing like a syntax thing but I mean next is returning an INT this is returning a bull this does not return anything and neither does this what uh what am I doing wrong like I don't even think I'm algorithmically doing something wrong per se I am just trying to figure out what is it think like this is such a crappy error message uh is saying that I is it says returning an in for some reason well that doesn't even make sense right I don't think I have to do that right is that a thing yeah that's what I thought but I just wasn't sure like I forgotten some languages or something so this next is set up so I don't even know did I miss reading something oh confused why this isn't even at least get C once right this returns true and then it doesn't do anything uh I'm so confused and I am so tired this I don't even why tell me why okay so the force is right I guess but why is this war is this returning a none or something no it's just not even calling it uh let's just return five for some reason let that fix it no I'm so confused am I returning none in or am I using the wrong one or something is oh I see that is subtle uh yeah and I might have to where's my one get list and then get integer where's my get integer no that's my get integer where's my get list I must use get list right oh here it is so why is it still giving me an that was a bad bug though but what is this thing I don't know what the ER is and it's probably something stupid I just don't understand the just want to send ever it's not even going here and printing this that's the part I don't understand am I know what the error message is I don't know how is it because they don't really give us like how they call it right so this is on the driver code and I don't even know what the driver means right um I guess we could if we really want we can go to the thing and then try to see um like the playground or whatever but um kind of lazy to be honest but okay so if I don't call update next that's fine somehow so maybe there is just some like weird thing about the code let's just remove chunks of it to see what happens okay so that's good that something okay so maybe I did have some silly mistake so this is the top of the stack oh is the length of top list not white or something like is that not a thing I don't know uh no it still says one index is going to be whatever but oh I see but that should do anything like or like it should give me a different error is what I meant to say I also thought that like we printed stuff after this right so like it terminates so that stack okay that's not very useful so the stack is empty which is fine and the next is one which is also fine oh I am dumb I probably made this mistake the same time last time I used the same rilow thing uh I feel like I've done this before I don't know if it was with this problem uh cuz then now this next is the function so it is very uh confusing I am not as smart boy I feel like I've done this before I don't know if it's the past version of this problem uh so okay all right I mean it may still be wrong for other cases but um oh list top list is could be a list true oh because I get the top list thing this is a little bit confusing uh add top list now it gets the list object doesn't have so uh okay at least now we're actually debugging the code because I was just confused um I it turns out that I waso overloading the next function which is why I was causing it which is a very uh I don't know I mean I don't even know it's a good bug it's just confusing but um that's the magic part of python that's a little bit sad but okay so then now maybe my logic is a little bit off so we started with the nested list right which is a in a way of nested integer so this will be a list of nested integers so then now let's say we have an A List so if the top thing is not that oh I see I have to do this that's also a typo I suppose or just like a mental lapse all let's see shouldn't take that long don't know what's up am I like in some weird thing even a time out limited exceeder would have been timed out by now and I am passing out oh do I print too much stuff no I mean do I print a lot yes maybe but it would also be like outp put Li yeah that's why I thought okay let's R it again maybe that was the reason or I don't know but I feel like that would have or should have terminated a lot earlier but maybe there is an infinite Loop here somewhere I mean this keeps on popping so what other Loops are there so this thing right so while this is not an integer we get to the list and then we get the list of that so then now it is uh so the stack should only contain lists is that true give me a second uh is there a weird thing where we keep on going forever well there only two wild Loops right so it's either this and this cannot go on forever because you just keep popping so it has to be this but okay so if it's not an integer it's a list we put push it on the stack okay right and then if it is an in we just set it to the item we pop or just DUS an update ideally I think we can actually um I think this kind of I mean I know that this is a little bit of a duplication code but I feel like that's more understandable because this is part of an update and this pop is actually um you know uh this is keep popping right so then now we can do something like uh right and then El brick something like that it's a little bit uh cleaner but that's not the T issue anyway so or like the infinite Loop issue that should be here but I don't know what I'm doing wrong oh this is this example is pretty bad so oh like it's pretty like basic so it's not like I do anything that crazy um okay so basically if this is a list then now it goes to the top list again and then am I doing something weird did I even get through one uh one thing so self. stack has a list uh this is kind of hard to pass let's actually put something I mean it's definitely obviously doing some kind of infinite Loop thing but uh I don't know what I'm doing this index of range oh uh okay so we look at the top of the stack we pop and then we up I think this is kind of weird I think we can also do the update here as well so wait uh okay so look at the top of the stack if this is too big then we pop and then we go to the next one um oh I guess this is continue I don't need to do this here that's why it a little weird otherwise uh it doesn't even need a continue cuz that's just what it does um otherwise it is smaller so then we get update and break so then s. stack. aen top list top index plus one and then we're done right all let's give a spin uh why what is going on what why is my indentation over okay there we go um I think well let's see if this works for us um a pen text okay obviously this is a thingy though that's little weird but well weird that it passed the other thing but uh okay that just means we are infinite looping somewhere still okay why what makes this of the two elements I try the other one and it seems okay so um oh this has to be popped as well that's why um and it's kind of a little bit awkward that I kind of separated them out but uh but because one is kind of um trying to go back and this is an update I think that's why oops that's why like I kind of have it as a duplicate code um it's duplicate but in a way like it's duplicate in the looking um but it's not it's a different operation right like you can imagine maybe the cener way to actually to do is like update top of the stack or something like this and then they'll update it in and you'll have it in a one thing instead uh okay I missed the really silly case of nothing uh so what does that mean so okay fine if uh top index is less than link of top list and this and then now yeah if top of index is greater than link of top list I guess this thing does it but then like yeah we only update to the next item with has case Ian man this is a medium and it is in concept but I am definitely struggling with a lot of uh stuff uh there a lot of silliness to be honest um okay let's give us AIT oh no I'm just being sloppy to be frank but okay so yeah have a list wait let's see I don't even have my hand on the keyboard oh it's next item that's why I was like what is going on there what is printing okay so next item is none after the first thing the stack has a bunch of things what was it oh CU we have this empty case okay so now it goes up here so it goes up here and then do I find it does not set the next item because we don't set the next item before um this is a way weird uh this is a very weird Edge case a list of zero items um H man this is a hard one at least for me um hm okay so what is the invariant that which we have here uh every time I thought I think about just doing a quick one this is always a mess uh but so then we after this was that I thought that it would be top list the top index is going to be an integer but technically I guess it's not true it could just be um well nothing it because it's a list of zero items which is kind of like a crappy thing um maybe I can do something like update next and then uh return I don't know even if it works I feel like uh that's terrible uh to be honest yeah I mean it didn't but how do I do it right how do I kind of um okay so it's bigger then we want to keep going and that's what this thing does in theory right uh so then here what is the state is that next item but the stack has this list and then now it's going to the second item um how do I skip or like how do I call it again right uh maybe uh Mt is equal to True right that means that we got an empty element for some reason which is very sad is that even true is this an empty element or rather is that always only one Mt is left I no let's play around with if empty then we do another update I refuse to do the fren thing but uh okay fine I mean it works for this case but is it really true let's give us a minute maybe this I there going to be oh I really thought that there's some Edge case that I probably would miss but uh yeah I don't know what did I do last time oh I did the crazy yield eh I mean yeah that's fine but uh and then I did the stack thing again with adjust next and move point to I guess that's basically what I did but uh why is that how is that right or how does it skip the zero case I mean this idea is the same so basically it is saying that so it just next has a move pointer thing I guess it just checks to uh expressly where it is z I don't know what to tell your friends uh I am going to pass out uh this is linear time linear space each item gets popped once and yeah and Pen once I don't know what to tell y so I'm really tired sorry friends hope that's what I have for today let me know what you think stay good stay healthy mental health I'll see you later and take care byebye
Flatten Nested List Iterator
flatten-nested-list-iterator
You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. Implement the `NestedIterator` class: * `NestedIterator(List nestedList)` Initializes the iterator with the nested list `nestedList`. * `int next()` Returns the next integer in the nested list. * `boolean hasNext()` Returns `true` if there are still some integers in the nested list and `false` otherwise. Your code will be tested with the following pseudocode: initialize iterator with nestedList res = \[\] while iterator.hasNext() append iterator.next() to the end of res return res If `res` matches the expected flattened list, then your code will be judged as correct. **Example 1:** **Input:** nestedList = \[\[1,1\],2,\[1,1\]\] **Output:** \[1,1,2,1,1\] **Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,1,2,1,1\]. **Example 2:** **Input:** nestedList = \[1,\[4,\[6\]\]\] **Output:** \[1,4,6\] **Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,4,6\]. **Constraints:** * `1 <= nestedList.length <= 500` * The values of the integers in the nested list is in the range `[-106, 106]`.
null
Stack,Tree,Depth-First Search,Design,Queue,Iterator
Medium
251,281,385,565
137
okay so hello everyone this is L here and let us see the second question of our bit manipulation list today's question name is single number two and what's the difference from the last question we have done here is that each and every element here is repeating twice except one so we need to return that single element which is repeating exactly once and need to return it so as you see in this first case there are this there is two which is repeating twice and there is one element that is three which is repeating once that is why three is the answer similarly in this case 99 is the single element that is repeating once and that is why 99 is the answer rest all the elements that is zero and once are repeating twice so what are the possible approaches to solve this question so first method is definitely we can use a hash map right uh to count the occurrence of each and every element so that will give you time and space complexity of O of N and O of n is space since we're using a hashmap now what is the method two so method two is regarding uh the bitwise thing so what is the intution we need to open the numbers as a 30 32 bit system and then we need to observe that what can we do uh in the terms of question is asking so let us see the first example so let us write in terms of bit first of all so two can be written as one zero and three can be written as 1 one and similarly the last element is also two so it would be written as 1 and zero right now what it's saying that every element is repeating twice so that means the bits will also be repeated twice correct so what I need to do is I need to add the number of ones here in each and every position of the bit so this is your last bit this will be your second last bit right if I calculate the number of ones because zero eventually will have no weight is in your answer so let's calculate the number of ones here so number of ones is one number of one here is four right now what is said again go back to the question observe what I saying they are saying that the every number is repeated twice and there is only one number which is repeated exactly once so definitely the number which you have got here it if I do a modulo 3 I get a one right so that means that there is only one bit which is different and rest all the bits are same right similarly in this case as well if I do a modul 3 here and why I'm doing a modul 3 because they have said it has repeated twice so again Four modul 3 will give you one again and here one again right so that means that you have a number which is repeated exactly once is this number and what is the decimal equivalent for this binary representation is three right similarly in the case of another case as well you are now open to dry run for some other cases as well you will get the same uh dryon so now let us do a reverse engineering now let us see that let us say the elements all elements have been repeated twice so let us say uh two and two is given in your array suppose the array was like this right so how this logic will make ensure that there is no element repeated ones now what is the count of ones here it is zero what is the count of ones here at the second last bit position for each and every number it is three now if I do a modular three for both of the counts what is again it is zero and it is zero so that means every element was appeared Thrice if there was one element which has appeared exactly once then definitely this particular bits have been reversed to one right now how we can code this particular solution so uh let me give you a walk through for the code so first we'll have an in result which will store our answer then we'll have a for Loop going from IOS to less than 32 right then what we did we have to run a for Loop for each and every element and we need to check for each position what is the count of one right now how this thing is ensuring the nums of J okay so let's say you have a number two and I want to see that this bit is one or not right so what I'm doing and operator with the one right and since rest of the things are zero here so every will every uh it will boil down to zero and this bit this would will be referent here right similarly let's say you have some another one Zer again right and what is the how we can express it in terms of bitwise so this is nothing but one left shift zero right and this zero has been again replaced with the generic uh variable we are using in the for Loop that is J so that's what say here again for the second time for I for J equals to one it will run and for this two what will happen one will come here and rest everything would be zero and I will do and operator right and again zero and one so definitely this bit has been refrained that it was actually one or not and what is the what how we can express this in terms of bitwise it is nothing but one uh left shift one and one is again expressed in terms of J here correct so that's what happening and when whenever we are getting a set bit we are doing answer Plus+ and at last we are checking answer Plus+ and at last we are checking answer Plus+ and at last we are checking after the after uh checking for all the bit all let's say all the bit at one position and then to the second last position similarly for third last until whatever the position we have right so we are expressing this terms of 32-bit system expressing this terms of 32-bit system expressing this terms of 32-bit system and that's then the last we are checking if the set bit count if it is greater than one now if the set bit count if modulo 3 is if equals then definitely there was an element which has appeared once so you took the weightage of that particular bit right now how are we taking the bit again so this is I know okay so where do I explain this how is this line running right so I know when I do an and operator of two with again one left shift J with J was equals to one I know there's a set bit here and just everything is zero now how to get the weightage of this thing again I will say that my actual answer result plus equal to 1 plus shift I so what is the weightage here weightage was 2 power one right and this is and we are getting this ith weightage from here this for Loop right I hope that explains the solution and the dry and the intuition as well everything so yeah let's just send this uh explanation and get back to the coding section so that's the code we have done in Java and let me show the C+ code AS in Java and let me show the C+ code AS in Java and let me show the C+ code AS okay so that's the code on the right hand side we have the code in Java let us hit the S button for this code so what is the time and space complexity it is 32 cross n ignoring the constant it would be o ofn and what is the space complexity we are not using any additional space instead of just some variables there is a result here it would be o of one and yes so that is successfully submitted let us end this video let us meet again in the next question of a bit man playlist till then keep learning keep going goodbye and take care
Single Number II
single-number-ii
Given an integer array `nums` where every element appears **three times** except for one, which appears **exactly once**. _Find the single element and return it_. You must implement a solution with a linear runtime complexity and use only constant extra space. **Example 1:** **Input:** nums = \[2,2,3,2\] **Output:** 3 **Example 2:** **Input:** nums = \[0,1,0,1,0,1,99\] **Output:** 99 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-231 <= nums[i] <= 231 - 1` * Each element in `nums` appears exactly **three times** except for one element which appears **once**.
null
Array,Bit Manipulation
Medium
136,260
1,335
Hi gas welcome and welcome back to my channel so today our problem is minimum difficulty office schedule so what is given to us in this problem statement what do we have to do here we have to schedule a list of jobs in these days ok and jobs depend here The date is main, if you want to work on a direct job, then what you have to do is that before that you have to finish all the darkness, okay and you have to perform every day and list of tasks. Suppose you have two days to perform the task. Okay, we have given more tasks, what do you do, you perform all the tasks in one day, if you do n't have any task for the next day, then don't do this, we have to list the tasks, give it, we have to perform it, okay, what do we find? What we have to do is to find the minimum difficulty of the schedule. How will we find it? Suppose you reduce the number of jobs you do on a given day. The one with maximum difficulty will be the difficulty of the day. So, what will be the difficulty of the number of days you reduce? If you do that then what will be your difficulty of job schedule? So what you have to do is to find the minimum. Ok if it is possible then if not then you will turn -1. So let us understand this problem not then you will turn -1. So let us understand this problem not then you will turn -1. So let us understand this problem through an example and then we will see how to solve it. Okay, I think, I have taken it from both of them, okay, I will write it down, no problem, so look here, your second example, what do I do with it, I make it serious, the second example is yours, it has your 999, okay, then difficulty. First let's see how we can find it. Okay, suppose you have given these three tasks first and reduce which one is the most difficult out of six, then six will be the difficulty of this one and what will be the difficulty in the first one which will be the maximum which will be three. This is 6 + 3, what will maximum which will be three. This is 6 + 3, what will maximum which will be three. This is 6 + 3, what will become nine, what will become of you, what will be the nine of your schedule, your difficulty is okay, so this is what we have to do, we have to find the minimum, how possible is the minimum, find that, okay, so that is how we You can do it, see, it can happen here because you have to do it in two days, right, if you do only six on this day, then what will be its difficulty, it will be six and what will happen on the second day, it will be five, so what has happened, yours is 11. Okay, suppose you have performed these two tasks first and then performed these chart ducks. Okay, so what will be the difficulty here, your pay will be six and here the pay will be four, the maximum is 10. Suppose you have performed these three tasks, here also you will have six. These three will be and these three will be 3. What is it? Nine, if you do these four first then these four first, then the difficulty here will be six and these two will be two, it will be 8. It is suggested that you do these five together. So here the difficulty will be six and on this day you have only one van, its van will be 7, so you have seen all the possible ways, right because you have to make sure that you perform something, okay, so keep in mind to do it. What has to be done, when you perform this task, then the task here should also be performed, so we have to look in this way, otherwise we have seen all the possible ways, in a way you can say, you have to see everything, okay. So this is it, I asked all of these, what will be the minimum, what will be your intake, then what will be your answer here, it will be 7, how will we find that, we will see later, let us also look at another example, see what is yours here, what is your job. Is there three and give is four and what is given in our problem statement is that you have to perform some task or the other, if you have to perform a task then you will give it one, you will give it, will there be any task left for it? It will not be left because we only have three, so in this condition, our answer is not possible, so what will we do - if we not possible, so what will we do - if we not possible, so what will we do - if we return 1, then what will be the condition here, what will be our condition that whenever we give less size n i.e., then it will be give less size n i.e., then it will be give less size n i.e., then it will be in the condition. -1 Dan, we will do it, okay, now let us come to in the condition. -1 Dan, we will do it, okay, now let us come to in the condition. -1 Dan, we will do it, okay, now let us come to which problem, how will we solve it, see what we have to do here, what we have to do in a way, what we have to do is to divide, okay, so you also have to keep in mind that we dance the task. It is not like that you have done everything in one day. If you have not kept a taxi for the second day, then if you are asked from here, then you can put the cut in the first, you can put it in the second, you can put it here also. You can apply it here also, you can apply it here also because it is d2, so this much can be done, you can do this, you can apply it here also, but you can apply it here, does it mean that you have done this in one day? I have done all this, so we don't have to do that, at least what we have to do is to leave it for another day, isn't it, you have to keep doing this, then how can we solve this problem, you give us the code. Let me show you the part, then I will explain to you how to do it here. Okay, so see, I will try to understand you through the code because what should we do here, all the possible ways have been given. So, see what we have done here. First of all we have found our what and what dog job difficulty size and as soon as we give our n less then we will return -1 ok and here on we will return -1 ok and here on we will return -1 ok and here on solve which your request is just a function we will call what you have definitely put in it and Which is your size, its 0 means this is your index, i and di, which is yours, this is de, okay and here we have first checked like our n &lt; di, we will first checked like our n &lt; di, we will first checked like our n &lt; di, we will return -1, okay now we are here. If you return -1, okay now we are here. If you return -1, okay now we are here. If you come then give, if you have a van, you have only one day, then on that day, what will be your base condition, what will be the condition, now I understand that you have six here, this is five, four is three, you have a van, it is okay if your Had the van been given, it is ok, if the van had been given then you would have given which of these. What is your answer? You have to perform all the tasks in a single day. So, what is the maximum among these? If this had happened then what would be your answer? Six would have been okay, this would have been the supposition, you have d2 ok and what tasks have you performed? One day left task, you will have to perform it on the second day, so whichever one is maximum among these will be its problem. This is what you are doing. We will find the one whose job is maximum among these. Right suppose you have performed this task has been performed till now, if you have performed this tax, it means that the task before this must have been performed. Okay, this is what it means because in our statement, we also have to keep in mind that if you have performed this task, okay, it means that you have done one here, then if you are left with this van, then only this. If you have a van left, then you have to perform the side tax on the condition of the remaining van. Out of that, who will be the maximum, yours and him, if he has the difficulty of the day, then what will be the maximum among these three, it will be three, right? If you have performed the taxes till this point, it means that you have already done the previous ones also, so where do you see the difficulty, you have to see the right in both of these, that is why we have put the base condition here, if d1 is I, where I have reached. Okay, this means that before I, we have done all the tasks. Okay, so what will we do, we will find the element which is maximum among them. What is the beginning of the update plus I in which update means your plus I? What happens is that you are looking at it from the index till the end, you are looking at the maximum of them, so this is your base condition. Okay, now what will we do here, what should we make of this result, we are going to filter later, right, so that is your maximum. What will happen is it will be filtered right and given the current we took it me because we have to see what is your maximum element in the current scenario so far so out of that you are going to find the maximum so what are you doing okay Why, later on we have to find the maximum, so this will be your filter. Okay, now look at what we have done here, we have done a Ford loop here, starting from GI and it is going till K-N-D. What's the plus and it is going till K-N-D. What's the plus and it is going till K-N-D. What's the plus why did we do this here we have called the recursive call in this see why did we do this see you always have to keep in mind that every single give you have to perform tax right so if you have given If you are there, then till now how much can you perform the maximum tax. You can perform the maximum tax till this point, after that you can do the van. It's ok on the next day. You can perform the maximum tax till this point, right? You can do this till now, what can't you do because you have to keep it for the next day too, di, because your agar di agar will be greater than van, it is for the condition, isn't this the rest of the things, whatever is the condition, tell me after this. We have kept our base condition for the van, if there is someone greater then it is sure that you will have to keep it for those days also. The task is fine, you will have to keep the tax for the next days also, so what is the maximum you can do. Here you can perform so many tasks. If this was your three, then how far can you perform the task. What can you do? Perform taxes from six to three, then one task for the next day. One task for the next day. Two vans, six five four three, what do you do the form in one day and keep you for the next day, you write the van for the next day, so what will we do here, whatever we index our Jio support initial. So yours will start from zero and how far will it go till N - D and how far will it go till N - D and how far will it go till N - D index. What is the size of N? So N is the size. So here your di is tu hai and if it is six then it will go till four index i.e. it is six then it will go till four index i.e. it is six then it will go till four index i.e. 0 1 2 3 4 2. Till we are taking the van, taking the right, cutting here, so in this condition, it can go up to maximum up to four, and when this is your D3, then in that condition, you can go up to three, cut up to three, one and the next. You will keep one for the day 8x tax for the next day so here's what's going on look at n6 is the three is six minus three induction zero van tu three this happened na so what we have here is what's going on in the for loop what have we done Here start from the GI from which you are getting the element, we have to see the maximum of them, okay then we will take the current, max, we will take the current, this and the job given, okay, we will see that, we have taken these, now what will we store in the result, minimum. You will store your previous result which you would have got, this is your Ekadashi call, right, now whatever you have got in the result already and what you are doing now, the current plus solve the job given here which is your ad, this and that. Here, instead of I, you are doing K plus Van because look here, you look like this is your cut, so you will see first this, then these two people, what is the maximum in these two, when these three people, then what is there in these three. The maximum is when one of these four people is there, which is the maximum among these four people? Who is the maximum among these five people, so we are taking the maximum in the current given and we have to see every possible way to add it, so what will we do today's plus. You will take the van and because you are doing it in one day, you will have to do the right - 1. You will have to do at - 1. You will have to do at - 1. You will have to do at least mines van from the previous one that is left, right because you have just done it in one day. You have reduced the given - 1 will have to be done, okay, here you You have reduced the given - 1 will have to be done, okay, here you You have reduced the given - 1 will have to be done, okay, here you do it, you will get the result and you will return the result. Okay, so this was yours, it is in research function, so it will give you the tally. Okay, so what do we do, memorize it. If we do it, then what do we do in the mess? Let's see what are the changing variables. So here you will see that changing is yours and given. In a way you can say I and given, so how far can your maximum go? It can be whatever from van to 300 so what can we do here we have taken a dp like it can go up to index then we will have to take 361 size and here it can go up to d10 so we can take 11 It will be required because if it is in the index, then when can it be given 10, when now there are 11 people, then this is what you did, set it in DP - 1, the size of the did, set it in DP - 1, the size of the did, set it in DP - 1, the size of the DP, then with the mines van, did you slice it, okay? Now what will you do after slicing, people check here, what have you found for this particular I and for di? What if it is not a mines van because you had taken out from the mines van if it is not a mines van date Mins, some value has been stored there, so that is done, now you will return it there and vice versa, what will you do, you will find, where will you store the result you find, dp i and di pe, particular di k for this particular i. You will store the result for this and finally return it. I hope you have understood. If you liked the video then please like, share and subscribe. Thank you.
Minimum Difficulty of a Job Schedule
maximum-candies-allocated-to-k-children
You want to schedule a list of jobs in `d` days. Jobs are dependent (i.e To work on the `ith` job, you have to finish all the jobs `j` where `0 <= j < i`). You have to finish **at least** one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the `d` days. The difficulty of a day is the maximum difficulty of a job done on that day. You are given an integer array `jobDifficulty` and an integer `d`. The difficulty of the `ith` job is `jobDifficulty[i]`. Return _the minimum difficulty of a job schedule_. If you cannot find a schedule for the jobs return `-1`. **Example 1:** **Input:** jobDifficulty = \[6,5,4,3,2,1\], d = 2 **Output:** 7 **Explanation:** First day you can finish the first 5 jobs, total difficulty = 6. Second day you can finish the last job, total difficulty = 1. The difficulty of the schedule = 6 + 1 = 7 **Example 2:** **Input:** jobDifficulty = \[9,9,9\], d = 4 **Output:** -1 **Explanation:** If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs. **Example 3:** **Input:** jobDifficulty = \[1,1,1\], d = 3 **Output:** 3 **Explanation:** The schedule is one job per day. total difficulty will be 3. **Constraints:** * `1 <= jobDifficulty.length <= 300` * `0 <= jobDifficulty[i] <= 1000` * `1 <= d <= 10`
For a fixed number of candies c, how can you check if each child can get c candies? Use binary search to find the maximum c as the answer.
Array,Binary Search
Medium
907,1886,2000,2027,2188,2294
886
Hello guys welcome back to take division in this video you will see the possible by partition problem wishes from list in day 27th challenge so let's not look at the problem statement the problem years but gives pain number five would like to positive way into Groups of a person like and not gone into liquidation like it is equal to that is not the people number at the same truth only possible to everyone in two groups in this is the problem not to give me the meaning of element subscribe like qu ODI live score and dislikes 400g goal is to find it is possible to partition and cigarette people into true that no two person in set head teacher picture basically want to divide incompatible people into two saudi set you handset v9 acids one head 30 different 60040 different Set to heads 4040 different 600 800 cash withdrawal incompatible person basically divided into two you can divide incompatible shyam veer 1212 basically in the sense but you can not be removed from the site quote indore set vikas to already as 40's note to in this Set We Know You Can Take About This One Important Set During Already Have Three And Also For Drawing This Paris Also Give In This Will Not Be Possible 2.1 Come Into In This Will Not Be Possible 2.1 Come Into In This Will Not Be Possible 2.1 Come Into Different Set Of Different Situations You Are Not Able To Cash Withdraw Per Cent 2012 Returns Problem so let's see how can we you to the first 102 more subscribe elements subscribe and where can you should be 420 467 468 471 so basically search in which state vice president so you can see but one is present in hate you dare 1422 set we 920 820 Soft You need to find in which state vice president so does not present in the sign in which was present for his present in the 2002 should set you will not be able to all players in two different shades their written letters in the voice of Hair 12120 1919 Presents You Should We Will Also Search For Saturn Which Presidencies All Present In The 2012 And Present In You Will Not Be Able To Divide The Amazing Different A Few Can Solve This Brother Ujjain To Maps And Sites By Using Some Conditioner Statement Sudhir Very Simple But latest not look at the classical approach for solving this problem Solve Acid Approach Will Be Using White Graph Mitra Govind Solution Will See How Can They Reduce To The Solution So Let's Jim Dahej Pairs In This Case One Head-to-Head 317 So How Can Be Case One Head-to-Head 317 So How Can Be Case One Head-to-Head 317 So How Can Be Divided Into Two Independent Subscribe 100 Feet This Thank You To Two To The Set V0 2069 You 020 Deposit Asset v4 Will Be Present In Here You And Will Be Line From Tomorrow Job Hits 530 Already Present In You Will Present In The year will appear line from 3254 hits 59 then it is already presented in you and five is presented with a railway line from 4 to 5 now you can see hidden cost of the players and where able to successfully divide all the compatible persons in two different states Will Return Subscribe Divided Into The Point And Independent And Subscribe Our YouTube Channel Give Way To Give One Tarf And As Well So 180 Okay 9 Of Way President Boys And Already Present In The Sense Will Have To Draw As Between One 90 Switch Between And Subscribe Our 6700 between two cash withdrawal nh-5 will not be a cash withdrawal nh-5 will not be a cash withdrawal nh-5 will not be a problem can be converted into subscribe giver of what you can do you subscribe jhal efijy bypassed graph min will always be possible to divide incompatible person into two parts ok handed over understood the idea Behind the second and third now let us look at the next point by point graph can only have a clue cycle ok so in this case Latest Jun 28 2013 Head to Head and its one subscribe The Amazing different sections and css3 Dhanwantri Video 's End Tours 2009 Se divided into two difference between two 's End Tours 2009 Se divided into two difference between two 's End Tours 2009 Se divided into two difference between two teachers in all over so successfully divided incompatible person in two different states will have to return to here no you can see the graph which is drawn reserving cycle member javed length cycle this is 1st 2nd 3rd and 4th number of Cases 98100 323 324 325 Want to see the in the sense with oo quinoa between two words in set 90 for end length cycle in this graph will see to be amazed at cycle will only be possible is the present age between two Teachers In Set The Knowledge Graph But What Is Not Behaving In The Present In All The Way To Make Cycle Se 143 Subscribe Go To The Point From This Thank You Will Go To 8 9 This Is Not To Win But You Can Only Move Vigilance Ne After Looking And The White Part Graph How Can We Use The Properties Which Below To Solve This Problem Verification Se List From And After This Can Be Done Immediately After Taking Admission List Want To Know It Will Always Be Possible To Be Compatible Se To Too All So Much For This Problem Solved Will Be Only Two Colors To Like This Is Fifty Years Only Two Colors Solitaire Zoom Bed Will Be Using Red And Green So Let's You Will Be Starting From This Is Not Want And They Want To find weather this is not length cycle and everyone like you can see and decisive and so will color this is not with red color 9.00 red color green beans with red color 9.00 red color green beans with red color 9.00 red color green beans green with green 9999999999999999999999 half not for this is not be seen after covering all the best rock Band will always be in the cycle no latest look at this online cycle no latest from this is not one and videotape is red color 98100 Subscribe and 3000 to 4000 100MB not able to clear all the not having Different Colors Channel Subscribe Now To Ka Plant Notes Late And Welcome To Know That Decision And Length Cycle Sudhir Very Good Approach For Fighting With Cycle This And Length And Even After Knowing This Approach Which Can Solve This Problem Using BF This Is The example of this is the graphical representation of the example subscribe and subscribe the Channel subscribe Face Will Not Want To Know Veer Is The Meaning Of Colors Which Will Keep Quite Old Quality Winkler 100 Index K Sincere Setting Note Top Color Note One Initially with it's a color one ok and will also oppose this novel in and why listen latest developments I know this will give water and will not wish to see what is the color 999999999999999999999 different color is which is the color of the current notes will have to Give Dollars A Year Before Signing Till Color Use This Simply - The Current Cars To 1000 Does Not Know Who Will Withdraw All Currency Notes Of This Process Will Just Want To Do And What Is The Color Of The To Color 1000 Subscribe And Not Having Different Colored in Which is the Current That Current is Winkler Zero and One is Winkler One Should Be Both Are Different Dates for This is Well No Veer Special Guest Is Note Color Viplav - Current Note Color Viplav - Current Note Color Viplav - Current Color 900099 Color and Subscribe Now to Receive New Updates 9 2012 Subscribe to Channel Now To 9 We Will Not Go To Message Send Tweet Know The Color Of Tourism Font Color Is Vansh And From This Two Three Lines About Having Different Colors For This Is It Is Gold Prices Will Not Be Wicked Flirts With no e will give oo turns red color 04 00 d0 99999999999999999999 so and current color is one should be both are different switzerland 121 195 color 500 current color is lineage that valid notes will 5.5 color is lineage that valid notes will 5.5 color is lineage that valid notes will 5.5 2009 notes23 color for different from this Has not been crossed all the limits of the President's Rule subscribe Video in two different sectors in this process just single component enough Vinod Aggarwal can be multipoint as well as four wheel user look to check all the notes circular otherwise will be fan subscribe into effect From this one to three four wheeler but istri 98100 vighna color present in the calling effective one to three four wheeler subscribe and subscirbe topic daenote saugandh notes will have discovered the four wheeler user bluetooth key channel radhe-radhe cancel multi corner problem number to the Time Complexity of Class 8th Edition List From This Way You Can Withdraw There Everyday You Can See Him To Give It Is Page Number Of People As Well As The Like Share Subscribe And WhatsApp The Matrix Key Me Na Dar That I Will Apply Desvoil there first for rupees for checking gift all the component singh raghavendra covered swift will cover multipoint ke din agar aap noida the current node will bf solid otherwise office color put face of the calling benefit returns value false singh it is not aware That Will Also Written This Will Not Be Divided Into Two 9 This Is The Function Subscribe And Subscribe Also Those Persons And They Will Achieve That Is Giver Color One Not Take Interest In Lord Will Have To Process All The Notes In That Point So Will Processes Tak Hi Simti Will Take You To Front Of You And Will Travel Officer Different Elements And Finally Minute Experts To And Current Element And Deserving The Same Color This Indicate Pain If Your Notes Also Biotite Develop Addison Notes Of Having Same Color Day It Will Be Having And Voltage Length And Dead Game Cycle Okay And Half Cycle Se Zara Will Never Be Appointed President Element Is Not Done Will Give Water Color And They Will Put Into All The Way Will Keep You In Order To Avoid After Facing All The That Will Return True Because after crossing all the notes that was no ambiguity against or rule danveer want to see the white part of this will only be single point for avoiding this is the solution in different languages ​​and everyone can languages ​​and everyone can languages ​​and everyone can benefit from like share and subscribe video
Possible Bipartition
score-of-parentheses
We want to split a group of `n` people (labeled from `1` to `n`) into two groups of **any size**. Each person may dislike some other people, and they should not go into the same group. Given the integer `n` and the array `dislikes` where `dislikes[i] = [ai, bi]` indicates that the person labeled `ai` does not like the person labeled `bi`, return `true` _if it is possible to split everyone into two groups in this way_. **Example 1:** **Input:** n = 4, dislikes = \[\[1,2\],\[1,3\],\[2,4\]\] **Output:** true **Explanation:** The first group has \[1,4\], and the second group has \[2,3\]. **Example 2:** **Input:** n = 3, dislikes = \[\[1,2\],\[1,3\],\[2,3\]\] **Output:** false **Explanation:** We need at least 3 groups to divide them. We cannot put them in two groups. **Constraints:** * `1 <= n <= 2000` * `0 <= dislikes.length <= 104` * `dislikes[i].length == 2` * `1 <= ai < bi <= n` * All the pairs of `dislikes` are **unique**.
null
String,Stack
Medium
null
329
hey guys it's iran with another coding interview tutorial and this time we have longest increasing pass in a matrix it is able to delete code hard but as far as hard questions go it's more on the lighter side but if you couldn't solve this yourself don't worry it's a type of solutions that you only have to see once so after you've watched this video you'll be able to solve this type of questions very easily so let's get straight into the problem description we're given an m over n integer matrix and we want to return the length of the longest increasing path in the matrix from each cell you can go in one of four directions you can go left right up or down you may not move diagonally or move outside of the boundaries so if you look at the example we're given this input matrix and the correct output for this matrix is four and that is because the longest increasing pass is this one and it contains four cells so i think the problem description is pretty clear uh let's move on to the solution so actually i want to solve a simpler problem first let's say we already know where the longest increasing path starts so we're given this matrix and we are also given a starting point and the question becomes what is the length of the longest increasing pass that starts at this position so remember we can go in one of four directions we can go left up right or down and in this case um only three of those directions are valid because the down direction is outside the boundaries of the matrix and of these three valid directions only one is increasing right because only three is larger than two now because there is only one direction we can go in uh the longest increasing parts that starts at this position is really just this cell plus the longest increasing pass that starts at this position so now what we want to know is what is the length of the longest increasing path that starts here right now from this position we have three valid increasing directions so this cell can link to the longest increasing pass that starts here or to the one that starts here go to the one that starts here so which one are we going to choose well obviously we're going to choose the longest one so hopefully you can already kind of feel the recursion formula starting to form here and what we're basically saying is that the longest increasing part that starts at position i j is one for the current position plus the maximum between the longest increasing pass that starts at each of the four directions and of course only valid increasing directions are considered so if we go back to our example we now need to find the maximum between the paths in these three directions the longest increasing pass that starts at this position has length one that is because there is nowhere to go from this cell it is surrounded by smaller values the length is 1 because it only contains the cell itself same goes for this cell it is surrounded by smaller or equal values so there is nowhere to go and the length is 1. from this cell we can go in one direction we can go here and then from d6 we again have nowhere to go so the length is one and now that we have reached the point where we have nowhere left to go we can start to roll back so if we stopped at this position we want to roll back one step and now we are here and the longest increasing pass that starts at this position is one for the current cell plus one for the maximum between all of the valid increasing directions so two we roll back one step again and now we are here and the longest increasing possible this cell is again one for the current cell plus two for the maximum between all valid increasing directions so three and finally we go back one last step and we are here and the longest increasing pass that starts here is one for the current cell plus three for the uh only valid increase in pass which is four and this is the answer for this uh question now let's get back to our original problem where we don't know the starting point now before we continue with this i have a little side note here at this point you might be thinking to yourself well this looks a lot like dynamic programming and it does but not exactly in simple dynamic programming we would know in advance where to start and the order of dependencies we would have to know in advance which cells have no valid increase in directions because these are the cells that have no dependencies so we can start from there and move backwards into the cells that connect to them then we move backwards again and so on it is possible to go that route if you perform topological sorting first in my opinion this is complete overkill it is way too complicated even though it is a correct answer uh what we're going to do is a lot simpler so let's forget about dynamic programming what we're going to do is give each cell a chance to be the starting point we find the longest increasing parts that start at that point and then we take the maximum out of all of the points and now we have one final issue we need to solve and the issue is many duplicate computations for example when we reach this cell we're going to compute the longest increasing pass that starts here but then when we reach this cell we're going to need this value again because it's part of its path and then when we reach this cell we're going to need this value again because it's again part of its path so as you can see it adds up and uh the most natural and best solution for this is just to cache the results so once we computed this value once we're going to just put it in a matrix and when we need this value again we're just going to pull it from the matrix and we're not going to compute it all over again that's going to save us a lot of time it takes us from an exponential time complexity to a linear one so it is a very important part of this solution it's also a very common optimization technique so it's good to keep that in mind because it can help you with a lot of other questions so now coding this is going to be the easy part so let's do that now okay so let's start by getting the number of rows and calls i always do this check never hurts and we want to create another matrix just like the original one for the cache and now for the loop that iterates over each cell and gives each cell a chance to be the starting point and we're going to need another variable for the max path so max path is going to be the maximum between the previous max path and the maximum increasing past that starts at this position so we're going to do that with a function so let's call it longest ink path and we'll need to give it the matrix and the current position and we're also going to need to give it the cash but let's just keep the cash here and also the rows and calls because i don't want to have to pass it to every function so just for convenience i think that will work and then we want to return this value now let's implement this function as i said this function is going to return the maximum increasing pulse that starts at a certain position so it's going to accept the matrix and current positions so first thing we want to do is we want to check if we already have this value in the cache so if we have it we can just return it i mean we can just return the value that we have in cache we don't have to compute anything and then if we don't then we need to iterate over each of the four directions so let's do it this way so the first one is the top direction and then this is the left one and this one is down and this one is right so we need to have a value here for the max direction path and take the coordinates for the current direction now before we go in each direction we want to check if the direction is valid and if it's increasing so the way we do that is first of all we check that it's valid and that it's increasing so the max the matrix at i j is less than the matrix at dear i doj and then if this is true we want to update the maximum direction path to be the maximum between the previous max direction part and the path of the current direction now that we have the maximum path out of all of the four directions we want to add one for the current cell and we want to cache the results now let's just return this value and i think we're good let's try it oh we didn't implement this valid function so let's do that real quick okay so let's try to submit this so that is a success so we are done with this part and a few words about the time complexity it's going to be linear as i said it's linear to the size of the matrix so o of m times n and it's because when we cache the result for each uh for each cell we never compute them again so in total we only do a constant amount of operations for each cell so that's a linear time complexity okay so that is it for this video i hope you enjoyed it if you did please give it a thumbs up and if you have any requests for other questions that you want me to cover put them in the comments section and i will try to make this happen so thanks for watching and i will see you next time
Longest Increasing Path in a Matrix
longest-increasing-path-in-a-matrix
Given an `m x n` integers `matrix`, return _the length of the longest increasing path in_ `matrix`. From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the boundary** (i.e., wrap-around is not allowed). **Example 1:** **Input:** matrix = \[\[9,9,4\],\[6,6,8\],\[2,1,1\]\] **Output:** 4 **Explanation:** The longest increasing path is `[1, 2, 6, 9]`. **Example 2:** **Input:** matrix = \[\[3,4,5\],\[3,2,6\],\[2,2,1\]\] **Output:** 4 **Explanation:** The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed. **Example 3:** **Input:** matrix = \[\[1\]\] **Output:** 1 **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 200` * `0 <= matrix[i][j] <= 231 - 1`
null
Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Topological Sort,Memoization
Hard
null
706
hey everybody this is Larry this is day four probably of the Lego daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's problem and I don't know why my computer's loading so slow maybe I have to C some windows I don't know who knows how technology Works know why this is loading okay still all right uh yeah uh today's problem is okay no extra coins today's problem is 706 design hash map what is this so design a hash map okay it's that's one uh I don't really have much to add to this one to be frank because I uh and you know if you're watching this for the first time I apologize uh I am going to be very lazy today just because I don't know like I think we I've done this like three or four times on lead code uh oh okay only twice but I think the last time I did this which was I guess a year and a half ago now which time twice but like I think I've went pretty detailed on that one with respect to a lot of things that you can look up but also to be honest everything I said was probably from uh an intro to algo class where they talk about all the things that you have to consider in a very short way and also things that you can look up specifically either on Wikipedia or algist or something like this uh and just kind of get like everything you need to know about this I'm a little bit lazy so I'm not going to rehash everything uh definitely maybe check out some of the old videos or just other videos that I didn't do uh which is fine and fair you know use everything I'm not the only person in the world who uh has some idea I mean I don't even know if I have a good idea but that's besides the point um anyway uh yeah so I think how do I want to do it today there a couple of things we can do right um oh you have to update the value so we don't have to um yeah I mean uh well 10 to the six so we can even if we want to be really lazy we could just make a 10 to the six um yeah I'm just going to be lazy and then we'll just see what happens right so maybe I want to say uh Max is equal to 10 to 6 uh plus five or something I don't know so self. look up is youal to did oh wait of course I was going to write this but I was like go wait that's that kills the point um and then put is what do we return for put I was avoid. lookup of key I don't know I'm just very lazy today so I apologize I'll see y'all tomorrow uh you know um yeah I mean I don't know I'll see you tomorrow if uh I'm not just very un inspired for this one uh that said uh you know I'm typing this I guess um my random update is that uh I did a uh a squad one RM test today and maybe that's why I'm a little bit lazy and tired but I uh got to 320 which is what is that H I've always forget that I have a 145 kilos I forget that I have a lot of you know non-americans that use lot of you know non-americans that use lot of you know non-americans that use reasonable SI units so anyway uh yeah so I am it's good I don't know that's all I have though so yeah uh let me know what you think I don't I'm not like I said I'm lazy for this I mean it's half lazy half frustrated that this is a silly problem so um and that I've done a few times so it's just I don't know I don't think I have anything to add so yeah uh that's all I have for today let me know what you think let's hope for a more interesting problem tomorrow and we'll do it together uh yeah stay good stay healthy to a mental health I'll see yall later and take care bye-bye
Design HashMap
design-hashmap
Design a HashMap without using any built-in hash table libraries. Implement the `MyHashMap` class: * `MyHashMap()` initializes the object with an empty map. * `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`. * `int get(int key)` returns the `value` to which the specified `key` is mapped, or `-1` if this map contains no mapping for the `key`. * `void remove(key)` removes the `key` and its corresponding `value` if the map contains the mapping for the `key`. **Example 1:** **Input** \[ "MyHashMap ", "put ", "put ", "get ", "get ", "put ", "get ", "remove ", "get "\] \[\[\], \[1, 1\], \[2, 2\], \[1\], \[3\], \[2, 1\], \[2\], \[2\], \[2\]\] **Output** \[null, null, null, 1, -1, null, 1, null, -1\] **Explanation** MyHashMap myHashMap = new MyHashMap(); myHashMap.put(1, 1); // The map is now \[\[1,1\]\] myHashMap.put(2, 2); // The map is now \[\[1,1\], \[2,2\]\] myHashMap.get(1); // return 1, The map is now \[\[1,1\], \[2,2\]\] myHashMap.get(3); // return -1 (i.e., not found), The map is now \[\[1,1\], \[2,2\]\] myHashMap.put(2, 1); // The map is now \[\[1,1\], \[2,1\]\] (i.e., update the existing value) myHashMap.get(2); // return 1, The map is now \[\[1,1\], \[2,1\]\] myHashMap.remove(2); // remove the mapping for 2, The map is now \[\[1,1\]\] myHashMap.get(2); // return -1 (i.e., not found), The map is now \[\[1,1\]\] **Constraints:** * `0 <= key, value <= 106` * At most `104` calls will be made to `put`, `get`, and `remove`.
null
null
Easy
null
55
Hi gas welcome and welcome back to my channel so today our problem is jump game so what have you given us in this problem statement, here we have been given a name by the name and here you have been told that man lo or you No, it is on the first index. Okay, your position is on the first index and whatever value is there in the index, you can take that maximum jump. Okay, so here you have to find whether you can reach the last index or not. If you can reach, then do animals. If you can't reach, then you have to do this train, then what do we do? First, let us understand through the example whether our problem is ours, then we will see how we can solve it. Okay, so here you look here. What are you giving me? Hey, I am giving you okay. And what is yours in the first position? 2 3 1 4 Okay, this is your first position. If you say second or third, then it definitely starts with you, then you are here first. The meaning of index is the meaning of first position. Now your maximum jump from here is this much, that is, if you are there, how much can you jump, you can jump van, you can also do it is okay if you jump from here. So where will you park the van, you are here ok, you have reached here and now how much can you jump from here, can you jump the van, so when you jump the van, you will park here, so how much can you do by jumping the van. You can and you will reach here. You can reach here in the last place. Now let us check whether we can reach by van or not by van. If we come here from here, then we will come here for the exam. From here we can take three jumps. If we take three jumps, we will still reach here. If we take a jump, we will come here. From here we can take a van jump. If we take a van jump from here, then we will reach here. From here, we will come here. From there, van, what can we do with these two steps, we can reach from here, right, so what will be the return here, will be true. Now let us also look at the second example, what is three here, you are van zero four, this is 01234. Ok, how many steps can you take from here, maximum, you can take three from here, three means now you can take 1, you can also take three, right, if you take a van, then you will stop here. How many steps can you take from here, you can take steps, if there are one step, people will jump here, if you people will jump here, but if you have reached here, then you have zero steps from here, that is, you cannot jump from here, that is, you We can't reach the last one. Okay, let's take a van jump. If we take a van jump from here, we will reach here again. Again, we can't go from here. If we take a van jump from here, we would have taken it from three. 1 2 3 Then here. We will go to A and from here we cannot come here because there is zero step here, that is, if we take any jump, we cannot reach from here, so what will happen if we fall, then this example is three one zero four okay its Position Zero Van Tu Three Four How many jumps can you take from here If you can take three jumps then three You can also take the van If you take three then you will come here If you people can't reach then you will come here Tu pe and van from here Then people will not be able to reach here. Okay, if you come here by taking a van jump, then from here you can take three jumps, you can also take three, you can also take a van, then people will not be able to reach here. So you will not be able to reach but three people 1 2 3 will reach here i.e. if you will reach here i.e. if you will reach here i.e. if you can reach here then there will be 10 rows here, okay look at the only change in these two, you are here, there are three here, ok now we are in this problem. Look how will we solve this, what will we do here, what will we do, solve it, what will we do here, from the end, we will see whether we can reach the first index or not, why will we do this, let me tell you, we will take main or we will not. Right here right here we are in this position we are already we will try to get from here to here okay so here you are you have to see whether you can get from here to here can you get from here to here So, if you were here to come from here, then you would have taken a van step from here and from the van step you would have gone here. Okay, man, this is your last position, isn't your last position also on the fourth index, okay on this. Do you want to see from here? If your index is here then can you come from here to here? Is that how you are on the third step and can take one step i.e. are on the third step and can take one step i.e. are on the third step and can take one step i.e. 3 + 1 if we do then these four keys are equal. What is happening is 3 + 1 if we do then these four keys are equal. What is happening is 3 + 1 if we do then these four keys are equal. What is happening is right, even if we were greater than fourth, what can we do? We can come here right because we know that if you were here, we could take the step, we can take the van and you can also take If there were three here, we can also take the van, you can also take the three, that is, if the sum of these two is greater than your last position, it will also be equal, then it means that we can reach from here to here, okay. We found out that from here we can reach here. Okay, now what do we do? We put our last position here because we found out that we can reach here from here but we have to see from here. If we want to see from zero, then our target will be, can we reach from here, what is our last position at this position, if we are free, then can we reach here from this step, meaning from here. Can you reach here? Okay, if you see then what will you have to do for this? You will have to see the sum of these two, 2 + 1 i.e. 2 + 1, have to see the sum of these two, 2 + 1 i.e. 2 + 1, have to see the sum of these two, 2 + 1 i.e. 2 + 1, your is greater than equals to three also. If the key of the last question is any, then it means that We can do many things, if there were four here, that is, we can take one step, we can take two steps, okay, so this will also tell us that we can reach here, okay, so now you know that from here You can reach here, you can reach here from here also, then your second target will be, then can we reach here from here, is it okay, so the last question is what do we do, we make it true so that is our target, now you Can we reach there by van or not? Otherwise, how many steps can we take on van? We can take three steps, that is, if we do van index plus three steps, then it will be ≥ 2, that is, steps, then it will be ≥ 2, that is, steps, then it will be ≥ 2, that is, from here, if we If you can take 3 steps, you can also take one step. You can also take three steps. If you take one step, we will reach you, that is, what is the last question, so we can reach from here to here. OK, so it is known that you can reach here from here, now your target is, can you reach here from here, can you reach this index from here? OK, so what will you have to do for this, the combination of these two. That is, the sum of 0 + 2 is your equals tu That is, the sum of 0 + 2 is your equals tu That is, the sum of 0 + 2 is your equals tu van hai kya han hai, it means from here we have tu step, we have van and tu, we can take both, so if we add van, we will take van step, then we can reach here only. If it is right then it means we will know that we can go from here to here and from here to here, then we know that the return on here will be true, this don When will it be true? When will you know that your last position has reached 0? You leave from here and we have reached here. Your last question has reached zero. Then you will return true. Okay, so now we will give another example. Let's give, does this reduce yours? For this, here you know that Dan Falls is going to happen, so okay, here too, let us see, I will remove this, see, now what will we do here, we will process it, we will see that Are we on the last position? Can we reach from second last or not? Okay, so what is our target, from here to Indore, here we are, we will take care of where is our last position, are we on fourth, can we reach from here to here. Okay 3 + 0, Okay 3 + 0, Okay 3 + 0, this is your greater give, equals tu four, it is not ok, we can't reach here from here, no problem, if we can't reach from here, then are we here, now our last position is right here, what are we here? From here we were getting to know that we can reach here from here, so now our target was whether we can reach here from here, is it okay but you should know that you can reach here from here. Okay, so no problem, so let's check from here that we can reach here. So, here we will do 2+1, is it &gt;= 4, what do 2+1, is it &gt;= 4, what do 2+1, is it &gt;= 4, what not, even from here we can't reach here. If we can then no problem, let's see from here that we can reach here from here, can't we reach from here too, that 1 + 2 is greater, give equals, that 1 + 2 is greater, give equals, that 1 + 2 is greater, give equals, you are four, what is not, we can't reach, can we? What can we reach from here? What ca n't we reach? Because if we do 0 + 3, then how much greater will this also we do 0 + 3, then how much greater will this also we do 0 + 3, then how much greater will this also be? Equals will not be four, that is, if we cannot reach here, what will happen here? Our last question will remain here, we will remain at 0 only. If you don't find it, then the pattern will fall here. Look, both of these are in test type, what to change, here there is three, here there is also three, here you are here, I have made it three, one zero four, now for this we see this. Here we know that there will be 10 of you here, so is he reducing it or not? Now take me, where is your last position here, where is your fourth place, these two are not happening, we are from here. Can't reach here Okay can we reach from here Can you plus van This is also not becoming four It is not getting even greater Ca n't reach Can we reach from here Will Han OnePlus 3 So this is four It will be done i.e. this is your equal, you are So this is four It will be done i.e. this is your equal, you are So this is four It will be done i.e. this is your equal, you are four, from here you people jump directly, take three steps and you will reach here. Okay, we can reach here. Now our last question is where will it be? The last question will come here. Now we are tight, can we reach here from here? If you do 0 + 3 can we reach here from here? If you do 0 + 3 can we reach here from here? If you do 0 + 3 then you can take three steps from here i.e. if you can take 3 steps then you can take one from here i.e. if you can take 3 steps then you can take one from here i.e. if you can take 3 steps then you can take one step then you can reach here i.e. You can reach the last i.e. You can reach the last i.e. You can reach the last question, again your point will be here i.e. it will become zero, that is, when it becomes zero, that is, you will i.e. it will become zero, that is, when it becomes zero, that is, you will i.e. it will become zero, that is, when it becomes zero, that is, you will understand that we can come from here to here and the return row will be OK, so let me show you the code for this, the code is also quite enough. AG is yours here, what is your index, so what will we do with the last position, we will update it at the end, okay, the loop we will take here, we will take from n - 1 to loop we will take here, we will take from n - 1 to loop we will take here, we will take from n - 1 to zero, okay, we will see, I am namas I, what is it, what is greater, give equals. Is it the last position? If yes, then what to do? Update the last position with I. If this process is done, if the last position has gone to zero, that is, in the last page, if you have equals, you have become zero, then it means that If we have reached the last position then it will give true. If it is not equal then it will give false, that is, we have not reached the last position. Okay, so I hope you have understood. If you liked this video, then please like, share and subscribe. please do thank you
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
1,887
Hello everyone welcome to my channel Kodasari with me, so today we are going to do video number 68 of our playlist. It is marked medium but it is very easy, it was made very quickly, I too had this question and I am sure you guys will also make it. Lead code number 18 87 Okay the name of the question is Reduction Operations to Make the Array Elements Equal Okay the question is let's see what you are trying to say in the company I will update as soon as I know it Okay in get up given an integer are Names, you must have given the integer. You know what the goal is, you have to equalize all the elements, okay, and for that I have told you how to equalize. To complete one operation is okay. You will have to do these three steps, then this. It will be called an operation when you do these three steps, then what is in the first step is that you have to find the largest number, you are fine, after that you have to find the next largest number which is strictly smaller than the largest, it is fine, let us assume that its value is the next largest number. After reduce numbers come to the next largest means remember the value of the numbers i. which was the largest, my ok make it equal to the next largest, return the number of operations it took to make all the elements equal, let's see the example here 513 Okay, which is the largest number, there is five in it, which is the second largest, which is smaller than five, strictly smaller, who is the first, three, then what will we do, we will make the largest equal to the second largest, see what will become, oh it will become 3 1 3 One operation is done, after that the same thing has to be done again, which is the largest number, which is the second largest number, if your one is one then look, make three equal to the second largest number, okay then this. Made equal to one and you notice that there were three two, one was here, so the one with smaller index will be picked first. Okay, and it's value is b. If there are multiple elements with the largest value pick the smallest. Index is ok now see if I chose small index or chose this one but no I noticed that it doesn't matter which one you choose because you have to count the operation right what difference does it make whether you choose small index or big index ok I have selected this and look at it, I have made it equal to the second largest. My two operations are done. Now again let's come to the third option A operation. Still see if all the elements are equal, otherwise let's find the largest number. Brother, three is the second largest. Which number is one? Okay, so make the largest equal to the second largest. Make three equal to one. So we have made this three equal to one. How much operation did it take? Three operations, that is why. Our answer is three. Look at all of them. The elements became equal. Okay, so I am repeating it to you again. Now when I remember, I had reduced 513 to 313 in the first operation. After that, the largest number which I had to find, I am seeing two largest numbers, one this and one. It says in the question that I have to choose the one with the smallest index but it doesn't matter to me which index I choose, I always have to convert the largest one to single lars, whether I do this or that, it doesn't matter. This time I will do this, okay, made it equal to one more operation was done, after that chose this three and made it equal to one operation was done, the answer is three, it is still fine, so it does not matter that the smallest index. Selecting the largest index, this thing became clear to me after some time. Okay, now brother, let's come to the intricacies of how to solve it. See, I will tell you my thought process when I read in the question that I have to find the largest. Okay, then second. If I have to find out the largest one, then my mind first ran that brother, sorting is definitely necessary, what is the reason for that, if I sort it, look, let's say that I have sorted it, then one will come, three will come, five will come. Pay attention to one thing, I know that the largest will be here in the right most index because I have sorted it in ascending order but the second largest will be just next to it, okay if yes, if it is equal then it will be a different thing, let's say there are three. Then it became a different matter, both of them are already equal, okay but not equal, so look, this is the largest and the second largest will be just next to it, then I will not have to search twice, once I will know that okay, this is the largest and This will be the second largest, the next one is fine, so that's why I thought that brother, sorting is definitely possible, so my first step was to sort the names, it's fine, 1 3 5 Now let's see how my mind worked, look here I What did I do, I know 100% look here I What did I do, I know 100% look here I What did I do, I know 100% that brother 01 2 which is n = 3 so the right that brother 01 2 which is n = 3 so the right that brother 01 2 which is n = 3 so the right most index will be the largest number, now okay so what did I do, I came to the right most index, the index number is here, I saw that Okay, if this is the largest f, then the one with second largest and i - 1 largest f, then the one with second largest and i - 1 largest f, then the one with second largest and i - 1 will be the one with i - 1, that is, it will be the one with i - 1, that is, it will be the one with i - 1, that is, it will be three, because right now both are not equal, so this is the largest and this is the second largest. Okay, so what did I do? Now look at the second largest as the largest, since these two are not equal then it is obvious, so I will have to make f equal to three. Right, it will take one operation, so here I am counting the operations here. So I will have to make f equal to three. After cutting five, we will make it a 'th' here, okay, here cutting five, we will make it a 'th' here, okay, here cutting five, we will make it a 'th' here, okay, here I write that after cutting five, we made a three here, it is clear till here, after that look, when the work of these two is done, then come here. I am fine, now look again I will do the same thing, who is the largest, it will be the eighth one and who is the second largest, see the second largest one, that is one, now look at this one and this one is not equal means second to largest. You will have to make it equal to the largest, that is, th will have to be made equal to one. Okay, so look, when you make this th equal to one, then pay attention. Let's assume that you have made it equal to one, but the problem is that even before this three, this You must have made the element before three also equal to three. Look, pay attention here in index number two, you had made it equal to three, so those elements will also have to be made equal to one. Okay, so you can do it like this. As soon as you see, okay, this largest element three is not equal to the second largest element, so the largest element i.e. this three and element i.e. this three and element i.e. this three and all the elements before it, I will have to change them all because I have reached here. Meaning, I had made the one behind it equal to this one, right, I had done it, I had made it equal to Yth, so those people will also have to be made equal to one, otherwise how many elements will there be in total. Look, it is here right now, isn't it? So this many elements i.e. n minus aa this many elements i.e. n minus aa this many elements i.e. n minus aa elements will have to be changed, n my aa will be how much it will be, 3 minus i is one but two elements will have to be changed, which elements are in one was converted to this one and one was converted to this. Converted it to one, it is clear till here, after that, when I came here, there is nothing on its left side, otherwise the story is over, look, all the elements have become one, okay, but look at the operation here, how much I had counted two, so here I added two, a total of three operations were done, okay, this is very important, we will do another example dry run so that there is more clarity, okay, as I take it, this time because of the example numbers are equal to a value. I have sorted the numbers 11 22 3. Sorting has to be done because what is the benefit of sorting. You are getting the largest and second largest next to each other. Adjacent is fine 0 1 2 3 4 n = 5. Total five is fine 0 1 2 3 4 n = 5. Total five is fine 0 1 2 3 4 n = 5. Total five elements aa, starting from here, I am counting the operations here, okay, I compared aa, what is mine, which is the largest and which is the second largest, i will be the one with -1, okay, if we assume that this is will be the one with -1, okay, if we assume that this is will be the one with -1, okay, if we assume that this is also three, then I would have skipped it because both are already equal, so I would have brought i here but this guy is two and so the second largest guy has become two, both are not equal, okay if both are not equal, what does it mean that I should add the biggest guy and All the elements that were there before that will have to be made equal to two. Okay, so what I said is that n - i operation will have to be done, so what I said is that n - i operation will have to be done, so what I said is that n - i operation will have to be done, so how much is n - i n? Brother, five is my so how much is n - i n? Brother, five is my so how much is n - i n? Brother, five is my 4, that is, there is only one element which I will have to make equal to two. And that's right, look, there is only one element, it has started here, okay, so I have added one operation here, okay, now here comes mine, okay, come here, this time, look at the largest, which one is the second one? Look, the largest is two, here i-1 also has Look, the largest is two, here i-1 also has Look, the largest is two, here i-1 also has two, if both are equal, then hit skip because I wanted equal, I brought it here and yes, I have updated it in two. I have updated it and write it here, okay, now when I come here, see that this time the largest is two, that is, the one with the index, and if you look in my index, then it is one, okay, now look, pay attention, this is a very important part. I am erasing all these, remember there was three here, I changed it to two, okay now look, pay attention, the largest and second largest are not equal this time, okay, this time the largest is not equal, so what did I say, yes, change the largest. It will have to be done, but the people who were there before will also have to be changed. See, because this is one, so when I make this two one, then the ones before it would also have been two because I have been equalizing everyone, while reaching here, convert them into one. How many elements will have to be converted in total? Look, A minus aa is my 5 and I am my minus 5 or a total of three elements will have to be converted and who are those three elements? Look, one, two, three, so look, I have added three operations. What does it mean that all of them are here, then I made these people new, this also became one, okay, now i came here, I saw that i and i, my friend, both are equal, no problem, skip it. i came here the story ended, there is no element before that, ok, see total four operations were required and this is also your answer, it was a very simple logic, so if you want to code the story, then it is very simple, sorted it, ok, what else? That i = n sorted it, ok, what else? That i = n sorted it, ok, what else? That i = n - starting from 1. Look, we are starting from the right side - starting from 1. Look, we are starting from the right side - starting from 1. Look, we are starting from the right side because that will be the largest element. Okay, i greater than n will go till zero. i ps aa minus okay for loop this will be greater than 0. Because it is obvious that a will reach here only then you will be able to get i-1. here only then you will be able to get i-1. here only then you will be able to get i-1. When it reaches here, there is nothing in i-1. When it reaches here, there is nothing in i-1. When it reaches here, there is nothing in i-1. Okay, so we will take a to one. Write greater than 0 or greater than equal to two. Write it down, it is only one thing, okay, and I had said that brother, if the numbers of aa are equal, the numbers of aa minus va, then that means both of them are already equal, then continue, that is what we wanted, continue and If both are equal then what will you add in the operations and if it is not so then what will you add in the operations P = n - Aa in the operations P = n - Aa in the operations P = n - Aa elements will have to be converted, there is no need to convert, as you see here I had written two after converting, then after converting I wrote one. There was no need to cut that, you have to count the operations, otherwise count the operations from here, you have to remove the operations only, return operations, that's ok, simple, just had to think how to sort, get it sorted and I gave an example, one or two examples, dry. Run the code immediately came to my mind ok so and how much will be the time complexity t n l n will be ok because you have used sorting and space complexity is constant off and because you have not used extra variables but yes sorting which utility You are using it internally, if he uses space then his space will be taken but you don't have to worry about it, the interviewer will not ask that much, that kind of question is fine, the main thing is that if you have done sorting, then n log n is its time complexity. Let's code quickly. And let's finish it, so let's code quickly and finish it immediately. Okay, so friend, first of all I said that we will sort beginning of numbers and of numbers. Okay, after that let's find the size. numbers dot size for. int a = n-1 start with q dot size for. int a = n-1 start with q dot size for. int a = n-1 start with q because it is sorted in ascending order the one on the right most will be the largest element i greater equal 1 i minus ok now let's come I told you brother if numbers of i equal i numbers If i is - 1 then it - 1 then it - 1 then it is ok to continue and if it is not so then let us count the number of operations and how many operations are required. Here we reduce operations plus i to zero. How many elements will have to be changed n - aa element. n - aa element. n - aa element. Okay, so submit the return operations and let's see. Hope fully we should be able to pass all the dist cases indeed yes if there is any doubt please raise it in the comment section and will try to help you out see you guys. In the next video thank you
Reduction Operations to Make the Array Elements Equal
minimum-degree-of-a-connected-trio-in-a-graph
Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps: 1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`. 2. Find the **next largest** value in `nums` **strictly smaller** than `largest`. Let its value be `nextLargest`. 3. Reduce `nums[i]` to `nextLargest`. Return _the number of operations to make all elements in_ `nums` _equal_. **Example 1:** **Input:** nums = \[5,1,3\] **Output:** 3 **Explanation:** It takes 3 operations to make all elements in nums equal: 1. largest = 5 at index 0. nextLargest = 3. Reduce nums\[0\] to 3. nums = \[3,1,3\]. 2. largest = 3 at index 0. nextLargest = 1. Reduce nums\[0\] to 1. nums = \[1,1,3\]. 3. largest = 3 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1\]. **Example 2:** **Input:** nums = \[1,1,1\] **Output:** 0 **Explanation:** All elements in nums are already equal. **Example 3:** **Input:** nums = \[1,1,2,2,3\] **Output:** 4 **Explanation:** It takes 4 operations to make all elements in nums equal: 1. largest = 3 at index 4. nextLargest = 2. Reduce nums\[4\] to 2. nums = \[1,1,2,2,2\]. 2. largest = 2 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1,2,2\]. 3. largest = 2 at index 3. nextLargest = 1. Reduce nums\[3\] to 1. nums = \[1,1,1,1,2\]. 4. largest = 2 at index 4. nextLargest = 1. Reduce nums\[4\] to 1. nums = \[1,1,1,1,1\]. **Constraints:** * `1 <= nums.length <= 5 * 104` * `1 <= nums[i] <= 5 * 104`
Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and v are neighbors of u and are neighbors of each other.
Graph
Hard
null
983
hey so welcome back and there's another daily code problem so today it was actually yet again a another uh cost optimization problem or a dynamic programming problem is a better term for it so yeah so basically what you're given is a set of days that you want to travel and so this is kind of the calendar year so or the day within the calendar so it's like the first day which would be like January 1st January 4th January 6th and so on so this could go all the way up to 365. and then you also have a Cause associated with one day travel passes seven day and 30-day travel passes seven day and 30-day travel passes seven day and 30-day travel passes and so um what you want to do is say okay I want to gather what the minimum kind of cost that associated with traveling for every single one of these days you know we don't really care about traveling on the day 15 or day 14 we just want to make sure that we use whatever tickets we need to travel at the most affordable cost so whenever you think of minimization or Max musician or anything with optimization like you should think of dynamic programming and that's kind of the solution for today's question and so there's multiple ways you can do kind of dynamic programming this one's gonna be like one-dimensional sometimes it's like one-dimensional sometimes it's like one-dimensional sometimes it's like a two-dimensional array that you need a two-dimensional array that you need a two-dimensional array that you need but for this since we're just kind of dealing with kind of days in a calendar year and costs like it kind of I kind of naturally thought of okay we want to use like a one-dimensional array like a one-dimensional array like a one-dimensional array um but often you can use a 2d array so always try to think of how can I formulate my DP array to kind of match this question and so what we're going to do is we'll have our DP array initially set to zero and this is going to represent okay what is the cost kind of minimal cost that we found so far uh for traveling on a particular day and so we're going to multiply this by the last day plus one and so that last day will be the last day that we want to travel on which will be the number 20. and so if this was day 365 the length of this DP array would be 365 plus one and we add the plus one here because it's not zero index it's one index so we want to go from like 1 to 365 and not zero one 0-364. 0-364. 0-364. okay and so to grab the last day we just look at our days negative one and so next um what we want to do is also we're going to have a set just called like travel days and this is just used so we can kind of get an 01 lookup of the days that we actually want to travel on because those are the days that we will actually consider the cost for and so that will be just yeah the set of the days that we want to travel and so now what we're going to do is we're going to iterate through every day between one to the last day that we want to travel and so from there what we expect is that we'll return the last index within our DP array and this is kind of just common templated dynamic programming problem like Solutions is that typically you would build your array so that as you're solving the problem you're kind of aggregating that minimal cost all the way until you reach the last day which is um you know this is what it'll cost to travel every single day of the year that we want to travel on um and that'll be kind of held in the DP array here at index 20. um and so from there what we're going to say is okay if this day is not in the list of days that we want to travel we're just going to ignore it and just aggregate that minimal cost forward because we don't really want to say okay we don't want to add any extra cost to travel on day 15 for this example because we don't really care like we just care about traveling day 20. so that's just going to be okay the DP at this day will be equal to the day previous of it otherwise we do actually want to consider the cost and so it'll be the result of kind of our minimization function where we consider these three scenarios and so the first scenario is we'll look at the previous day from the current one and then we basically just add the cost for one day so this represents kind of a one day pass and so you just say okay get the minimal cost for the previous day that we've been aggregating forward and just add okay if we go from that date plus this running cost of zero what would it be great and so from there what we'll do is it cost s with an s is we want to do the same thing but we want to look at seven days ago and then we'll say okay what is the cost of that we add the cost for a seven day pass and then same thing with a 30-day pass and then same thing with a 30-day pass and then same thing with a 30-day pass now the only issue is then this one will never throw an exception because you're starting at index one and index 0 will hold like zero and so that solves the first case so if we're at index one and then we do a negative seven this will go out of bounds in our DP array because it'll be like negative six index into our DP so we'll actually just want to do okay take the maximum this is just a little python trick we just take the maximum of zero in this so if it is negative you just grab index 0 instead of like index six great so let's just try that oh and we want brackets here oh I think there's an issue um oh we want two here oops yeah okay great yes that's it um basically the time complexity for this is in this base complexity so for space this DP array will be at most 365 so that's kind of like a constant space it won't grow linearly but this travel days is extra space that we're using out for that kind of o1 lookup so it's kind of a time and space trade-off here is so that time and space trade-off here is so that time and space trade-off here is so that by Saving on space or saving on time we require some extra space and storage here so that'll be kind of O of n um where n is the number of days here and then for the time complexity we're just going to be iterating through every day in this list so that's also ovent or every day between I think it's kind of constant time because you just iterate through each of these options and then you go at most the last day yeah so it's kind of bounded on 365 so you can kind of say that it's constant time and space really um but to be safe I would say that it's of n time and over and it's defined space because you're grabbing all this here yeah okay so it's oven and oven in my book but feel free to add in the comments um what you think it is and any you know solution that you provided and how you did it maybe you did uh this is a bottom down approach with a one-dimensional right maybe you did a one-dimensional right maybe you did a one-dimensional right maybe you did a top-down approach with minimization and top-down approach with minimization and top-down approach with minimization and a 2d array but if you're free to post your code in the solution and let me know what you did and what you think the time complexity is so yeah I hope that helped and good luck with the rest your algorithms have a great day
Minimum Cost For Tickets
validate-stack-sequences
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. Train tickets are sold in **three different ways**: * a **1-day** pass is sold for `costs[0]` dollars, * a **7-day** pass is sold for `costs[1]` dollars, and * a **30-day** pass is sold for `costs[2]` dollars. The passes allow that many days of consecutive travel. * For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`. Return _the minimum number of dollars you need to travel every day in the given list of days_. **Example 1:** **Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\] **Output:** 11 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1. On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9. On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20. In total, you spent $11 and covered all the days of your travel. **Example 2:** **Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\] **Output:** 17 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30. On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31. In total, you spent $17 and covered all the days of your travel. **Constraints:** * `1 <= days.length <= 365` * `1 <= days[i] <= 365` * `days` is in strictly increasing order. * `costs.length == 3` * `1 <= costs[i] <= 1000`
null
Array,Stack,Simulation
Medium
null
1,528
to be very honest this is an easy problem to solve but I believe that this problem is asked in interviews because your interviewer wants to see how much of a concise solution that you can come up with because it is very simple to come up with a brute Source solution and a solution where you are iterating over every character so how do you go about solving it Hello friends welcome back to my Channel first I will explain you the problem statement and summative cases going forward we will start with the brute Source solution and then make our way to an efficient solution so that you are visualizing how we can come up with a very short solution after that we will also do a try run of the code so that you can actually see how it's working that way you will never forget it without further Ado let's get started let us make sure that we are understanding the problem statement correctly in this problem you are given a sample string and an array of indices so what if this array of indices actually tell you let us look at a sample test case in a sample test case you can see that I have this string and this area of indices so this array of indices is telling me that in my final string R will be at the fourth position once again in my final string this character e this will come at the third index for this particular test case this string will be your answer you can verify it right check it out o should come at the fifth Index right and if you find it out 0 1 2 3 4 5. for o is in fact coming at the fifth index so technically this string has been shuffled as per all of these indices and you have to find out the original string or the reef node string for your first test case this is your restore string similarly you have your second test case you have a string ABC and these are its indices your final answer will be the same string ABC because your indices are given in the exact same order so where will a go in the final string that will be at the zeroth index where will see go at the final string that will be at the second index so just confirm it once again let us look back at our first test case where does key go k will go at the seventh index and you can check it out K is at the seventh index in fact right so if this problem statement is now even clearer feel free to stop the video and try the problem once again otherwise let us dive into the solution when you start thinking of a solution what is the first thing that comes to your mind you will try to think that okay you need some sort of a mapping that can tell me that the fourth character is R right you need a mapping that can tell that the third index will be e right so this tells me that I need some sort of a map so if I have a map how can I populate it I can say that the fourth index should be a r moving ahead I can say that the fifth index should be o the sixth index will be C and then similarly you are gonna populate your entire map once you have this map ready what will you do you need to form your string from the zeroth index right and then you can go character by character so first of all you look at the zeroth index and then get the character over here you get an L right next you will try to search for the first index and then get the character over here so you get a i similarly you will keep on moving ahead and you will get your complete string and this method works right it will give you a correct answer every time but the only limitation of this method is that you are utilizing an extra structure and certainly you are doing a lot more checks just to determine that hey where will my character actually go and as I said before this problem is all about how much of a concise solution that you can come up with when you solve this problem yourself you realize right that this is such a basic question I just need to find a very efficient way that I can populate the string immediately so how do you go about doing that let us have a look once again let us take up our sample test case correct and try to think what are the stuff that you know that the length of this current string is 9 right so this tells you that the length of a reef node string or the original string it will be once again nine right it cannot be larger or it cannot be smaller so what I can do is I can create a new character array that have nine spaces so a zero based indexing will mean that you start from the index 0 and go all the way up till index 8 correct and this array this will hold your final string now just follow the problem and we will do exactly what the problem said it is telling me that photo string S I have a character R and where does it go it goes at the index four correct so just take up this R and add it to your fourth Index right similarly move ahead now what if the second character is o and your indices array tells you that this second character will go at your fifth index so just take up this o and add it to your fifth index over here similarly you will keep moving ahead where does the next character C go C goes at the sixth index so I am gonna write down C at my sixth index over here for the next character that is K where does K go k goes at the seventh index so you add it at the seventh index over here similarly you will keep on moving ahead for each character and then populate them at all of these specific indexes once you do that your character array will start to look something like this for now you see this character array ultimately has your final string just convert this to a string and return it as your answer this is much more efficient right you do not need a complex structure like a map and now let us quickly do a drawing of the code and see how much of a short solution that you can come up with on the left side of your screen you have the actual code to implement this solution yes it is that concise and on the right once again I have my sample test case that is passed in as a input parameter to the function restore string oh and by the way this complete code and its test cases are also available in my GitHub profile you can find the link in the description below moving on with a dry run what was the first thing that we do first of all we need to create a character array right and this character array will be of the same length so I have my character array that starts at index 0 and ends at index 8 right and this is an ultimately store your answer and how do we go about solving it now check out the second Loop and this is where all the magic happens what was our question saying our question said that in an indices array the first value this is determining where will my first character go correct and that is exactly what we do check it out the current value of I is 0 so what do I do FTR at right how does this revolve this resolves to FTR now indices 0 is 4 right so I am doing FTR at 4 so this is now revolving to this particular block correct and what do you equate it to s dot Care at 0 and what is f dot carat 0 that is the letter r so I will do R over here and as soon as I do it R will come over here moving ahead what will happen the value of I will now change to 1 and this time you will refer to this particular number this refers to this block over here and what do you populate the second character that is o so when this Loop runs ahead Q will enter o and similarly this array will be populated completely once this Loop is completed you simply return this array as your answer so technically this was just a one line solution right the time complexity of this solution is order of n because you need to iterate through the entire string only once and the space complexity of this solution is also order of n because you need some extra space to determine the position of each character I hope I was able to simplify the problem and its solution for him for my final thoughts I just want to say that whenever you encounter these kind of problems in an interview try to come with a solution and present it to your interviewer there are chances that your interview will say that okay how can you improve it then try to think of concise wave because you will be able to visualize that okay there are ways where I can make this solution shorter and ask your interviewer that okay what is the time complexity you are expecting what if the space complexity you are expecting that way you will get a hint for example in this problem you need not use a hash fact right you can just use arrays and they are a less complex data structure correct so less complex Solutions are always desirable just keep that in mind so while going through this video did you face any problems or have you seen any other such problems which can be false just using a single line there are certain questions trust me so tell me all of it in the comment section below and it will be helpful for anyone else also who is watching this video I'll be happy to help you out as a reminder that if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos and I will bring more problems for you until then see ya
Shuffle String
kids-with-the-greatest-number-of-candies
You are given a string `s` and an integer array `indices` of the **same length**. The string `s` will be shuffled such that the character at the `ith` position moves to `indices[i]` in the shuffled string. Return _the shuffled string_. **Example 1:** **Input:** s = "codeleet ", `indices` = \[4,5,6,7,0,2,1,3\] **Output:** "leetcode " **Explanation:** As shown, "codeleet " becomes "leetcode " after shuffling. **Example 2:** **Input:** s = "abc ", `indices` = \[0,1,2\] **Output:** "abc " **Explanation:** After shuffling, each character remains in its position. **Constraints:** * `s.length == indices.length == n` * `1 <= n <= 100` * `s` consists of only lowercase English letters. * `0 <= indices[i] < n` * All values of `indices` are **unique**.
Use greedy approach. For each kid check if candies[i] + extraCandies ≥ maximum in Candies[i].
Array
Easy
null
1,830
hello everyone let's take a look at the code 1830 minimum number of operations to make string sorted it's the last question in the bi-weekly context the bi-weekly context the bi-weekly context and it's related to math so it's a pretty hard question i hope it will not being the interview question otherwise it will be too hard and it will fail a lot of people okay so the um algorithm problem description is quite complex next there two steps to like convert the string okay let's just take a look at this example so the input is cb we can say uh from the uh that after five operations cba becomes a b become visa basic acb abc so with fun it becomes the previous permutations every time so the problem is actually financial rank in all permutations for the inputs okay so let's take this example there are no duplicates so let's take this example first the first character is c so we can put a and b in the first position since they are all smaller than c so if we put a and b in first position we have two choices and for the remaining four characters we have a factorial four so choice is for 48 if the first position is say for a second position now it's d we can also use a and b in the second position so we have to multiply the factorial of three which is twelve for third position we can put eight so we have two for the fourth position we can also put a then we have one and so the total realm is 48 plus 12 plus 2 plus 1 which is 63. okay what if there are duplicates let's take a look at this example in 6th example um for a it occurred three times for b to occur twice so we have five choices and for the remaining seven positions we have factor of seven permutations but we know there are many to do on duplication since we have three 3a we have 2b how many duplications we have since we have 3 a 2b so we have a factorial of 3 multiplied factorial of 2. so the final total unique number is five multiplied as a factor of seven the same divided factor of three then divide factorial of two when we place a and b in first position for the second third first positions we can apply the same algorithm okay so let's take a look at our first version of implementation first i defined mode as this number as the problem required and we count the frequency here just for each character and the conscious frequency okay so we pre-built uh like a okay so we pre-built uh like a okay so we pre-built uh like a pre-process to build pre-process to build pre-process to build a factorial table so that we can speed up things up a little since we will can't like calculate the factor every time later so this is a factor of one factor of two factorial of three factorial four and so on okay this is our answer finally we just written this answer now we need to for loop each character in the string after each iteration and minus and we just exclude this character from our frequency table okay what is frequency sum here like for this example frequency sum is 5 since we have 3a and 2b and which is to duplicate the duplicates factor of three multiple factorial of two so in this for loop we just build the frequency sum and duplicates here okay at last we just use this formula frequent sum is five factorial and minus one is this one factorial seven and mode and we divide by this duplicates you may notice that i don't have uh that mode here when i calculate duplicate so you can pass one as a small since then there are no overflows but we know the length of this s can be like 3000 so it will overflow here can we just put mode here we can't since we divide by duplicates if we move for first there will be some issue here the answer will not be correct so we are doing division in like we are doing mode in division like it's very hard how can we deal with it okay it's inspired by this link so modern integration we can find a famous little serum theorem like things here like p is a prime number and for any integer a we know uh x number a to the p and a is an integer multiplier a multiple of p okay let's assume that we divide by eight square so a to the p minus two uh and uh one divided by a like is the integer multiple of p so assume a s2 duplicates so we replace a with duplicate since a is any integer a and duplicate it's an integer so 1 divided by duplicates is like duplicate to the p minus 2 one like mod p right so since p is this number which is prime so we can do this like conversion previously here we multiply 1 divided by duplicates now we can just multiply like duplicates to the mode minus two then finally we just mode this number and for this pw function it's a very typical uh that functions said we calculate the pow and we also mod the number here so this is a very typical function or a very typical helper function using a lot of liquid questions so this is our final answer so when we calculate two duplicates we can mode this number and finally we just multiply the duplicates to the mode minus two and finally we move this mode this is the final answer so yeah and this conversion can be applied to many um problems in the code one reduce like some mass problems related to the combination like permutations okay that's it thanks so much
Minimum Number of Operations to Make String Sorted
count-good-meals
You are given a string `s` (**0-indexed**)​​​​​​. You are asked to perform the following operation on `s`​​​​​​ until you get a sorted string: 1. Find **the largest index** `i` such that `1 <= i < s.length` and `s[i] < s[i - 1]`. 2. Find **the largest index** `j` such that `i <= j < s.length` and `s[k] < s[i - 1]` for all the possible values of `k` in the range `[i, j]` inclusive. 3. Swap the two characters at indices `i - 1`​​​​ and `j`​​​​​. 4. Reverse the suffix starting at index `i`​​​​​​. Return _the number of operations needed to make the string sorted._ Since the answer can be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "cba " **Output:** 5 **Explanation:** The simulation goes as follows: Operation 1: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "cab ", then reverse the suffix starting at 2. Now, s= "cab ". Operation 2: i=1, j=2. Swap s\[0\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 1. Now, s= "bca ". Operation 3: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 2. Now, s= "bac ". Operation 4: i=1, j=1. Swap s\[0\] and s\[1\] to get s= "abc ", then reverse the suffix starting at 1. Now, s= "acb ". Operation 5: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "abc ", then reverse the suffix starting at 2. Now, s= "abc ". **Example 2:** **Input:** s = "aabaa " **Output:** 2 **Explanation:** The simulation goes as follows: Operation 1: i=3, j=4. Swap s\[2\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 3. Now, s= "aaaba ". Operation 2: i=4, j=4. Swap s\[3\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 4. Now, s= "aaaab ". **Constraints:** * `1 <= s.length <= 3000` * `s`​​​​​​ consists only of lowercase English letters.
Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers
Array,Hash Table
Medium
1,1798,2220
985
um hello so today we are going to do this problem called sum of even numbers after queries so the problem says uh this is part of Fleet code um daily challenge the problem says we get a an array for numbers and an array of queries and the queries contain both a value and an index and what we want to do with these is basically take the number at the opposition and add value to it and then what we want is for each query we want to print the sum of the even values of the numbers so that's what we want to return um and basically we'll put for each query we'll put the sum in the in an answers array and we will written that um okay so let's take a look at this example here so um we have this array and the first query for example the index is 0 and the value to add is one so we add that to here and so that will end up with two three four and so we add the sum of all of these and we end up with of all of the even values by the way that someone suggests the even values and if we take the look at the second one the index is one we want to add minus three so that will become this and sum of even value is two plus four and you can see here we have eight and six and we do the same thing for the rest so it's pretty straightforward right now how can we solve it The Brute Force way to do it will be to um go through all the queries right and then for each query take the index and value and just do the exact operation and then do the Traverse the numbers again after the modification and then add the at each even value to the sum and then add the sum right but that would be like of Q and right because like I have so that would be like o of qn with Q the number of queries and the number of elements in the array right so that's not um that's not good because if you look here at the constraint 10 to the power of 4 queries and 10 to the power of 4. so if we do multiplication that would be too big right um okay so let's see how we can solve it um so here we have this array right so we have this array here let's see how we can do that so we can definitely just keep running some right so first just initially grab the sum of all the even numbers so that would be 2 and 4. 6 right and then we'll need to go through the queries and the queries will be value and Index right let's call it queries like this um so for example here one zero which means for this index 0 1 2 3 so for this index 0 because this is the index and this is the vowel we want to add one and you can see what happens here right one plus one equal to two so it became even so that's one of the cases so basically the cases are the number wasn't was odd before but after the query but with query it becomes even right so for this number what does it mean we just need to add it to s right and becomes eight and then add that to our result so in this case what we need to do is just so if the number was before add and it became even just add it to some and then that would be what we add to the result now let's take a look at another case so the second case is happens here where the we want to add minus three to position one and we get this so you can see the number was even but it became odd okay so this is our second case okay so what is case two uh number was even became odd so what should we do here we should definitely remove this right because it just became uh it became odd it's no longer two so we need to remove it from our running sum because we are still counting it here but since -1 is odd we shouldn't add it but since -1 is odd we shouldn't add it but since -1 is odd we shouldn't add it we should just subtract this one right so that's what will give us six so in this case we will just um what should we do here we should just subtract number before no initial number right not minus one but two from our running sum s and then add s to the answer um now what are other cases so we have add to even so we handled add to even right and now we handled also even to add we may other cases are add to add so the number was add and it's still odd after the query do nothing right so here nothing foreign and now it's still even with the query now this one is interesting because that means it was part of the sum but we need to replace with the new value and so here we just need to do s minus the old value right because it was counted as part of s and we need to do S Plus the new value so subtract the old one add the new one all right so this is a good class of problems where we do case-by-case analysis right where we do case-by-case analysis right where we do case-by-case analysis right um but like I don't like us like to do like all of these five cases right so let's kind of reduce this into a simple implementation okay so let's see where do we need to do anything so for add to if for um add to add we don't need to do anything right so no don't worry about this so if they are both odd we don't need to do anything now you can see here if it's hard to even uh let me actually write this here so if to even that means we need to do S Plus new value um to even yeah plus a new value if it's even to add we need to subtract the old value right and here we need to do both so you can see actually we can kind of reduce this down to only one implementation which is if the old value is even which means we are in this case or this case in both cases we need to subtract it right which means we need to do s minus old value right and S by the way initially is the sum of all a in the array for a even right that's the initial value of s right initially we just grab the sum of all the elements now when the result after applying the query is even we add the value but if it's add we don't do anything so you can see that applies to this case even we add the value the new value and if it's even here we add the new value if it's add we do nothing we just subtract the old value but we do nothing with the new value right which makes sense we want to only sum the even values so in this case here if the new value is even we want s plus all the value a new value sorry you want to add the new value it's what we are doing here what we are doing in this case here so S Plus new value okay and of course for each query we want to add to our result array we want to add s sorry now we just need to kind of replace the old value a new value with these values so remember this would be for a query for Val and index in the query right so here old value is just the number before doing the modifications so this would be just the number uh let me write it down so this would be just the number let's call it a instead of nums so that would be a at index and then here we do the modification to apply the query plus Val and now it's the new value and so this here means this is the new value right and that's pretty much all there is to it so um I want to highlight that this problem is an example of a case-by-case analysis is an example of a case-by-case analysis is an example of a case-by-case analysis and so for this kind of problem definitely do the case by case analysis but also once if there are a lot of cases try to think what is the common between them and how can you come up with a smaller uh easier to implement solution right okay so that's pretty much it now let's um write this down and make sure it passes these cases okay so let's implement the solution that we just mentioned so first we need the sum and so that would be the sum of all of the initial sum of all of the even values and so a for a in a so I'll modify this to be a and this to be Q just for easy to be easy to write and this would be if a actually let's leave it maybe yeah just for clarity so for a in numbers if a is um even right and then we need to do our result that we will return at the end here and we need to go through the queries which are val value and index inquiry and we want to check if the old value is even which is this is just what we saw in the overview then we want to subtract it um and then we want to apply the query so this would be a plus value right and then we want to check if the new value is even if it is we want to add it to the sum and that's pretty much it and then here we want to add to Res this sum here and that should be it now let's run this um okay so this should be queries here and this needs to be numbers okay yeah okay so that looks good let's submit okay so that passes test cases um in terms of time complexity here so if we consider Q to be the length of queries that would be o of Q here right and we are doing just but we are doing here of an operation as well right so overall it's oven plus Q um and in terms of space um we are using just this s extra array otherwise we are using nums but we also have this result array and so overall it's just open space right um actually it's of uh Q space because s uh res um length is a Q the number of queries yeah so that's pretty much it for this problem um please like And subscribe and see you on the next one bye
Sum of Even Numbers After Queries
bag-of-tokens
You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`. For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`. Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[1,2,3,4\], queries = \[\[1,0\],\[-3,1\],\[-4,0\],\[2,3\]\] **Output:** \[8,6,2,4\] **Explanation:** At the beginning, the array is \[1,2,3,4\]. After adding 1 to nums\[0\], the array is \[2,2,3,4\], and the sum of even values is 2 + 2 + 4 = 8. After adding -3 to nums\[1\], the array is \[2,-1,3,4\], and the sum of even values is 2 + 4 = 6. After adding -4 to nums\[0\], the array is \[-2,-1,3,4\], and the sum of even values is -2 + 4 = 2. After adding 2 to nums\[3\], the array is \[-2,-1,3,6\], and the sum of even values is -2 + 6 = 4. **Example 2:** **Input:** nums = \[1\], queries = \[\[4,0\]\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `1 <= queries.length <= 104` * `-104 <= vali <= 104` * `0 <= indexi < nums.length`
null
Array,Two Pointers,Greedy,Sorting
Medium
null
1,444
hey everybody this is Larry this is the last day right yay we made it friends the last day of the March Deco daily challenge hit the like button to subscribe and join me on Discord let me know what you think about this poem and uh yeah just we're gonna be I mean if you've been following along uh you know that my streak is at 10 94 right now and what I mean by that by saying that is that uh we're gonna fight two of April as well just to be funny because I'm just putting down my phone um so let's do it together you know even if you get it you don't maybe we'll learn from each other leave a comment and all this good stuff okay so first of all the first thing I saw was mod for some reason so that's uh that's I think the mod song I go mod before I sing this and then I do this basically there's a it's not a template but it's basically code that I know won't compile but by the time I get to it'll be like oh yeah come on man before you submit you have to remember the man okay so let's take a look a number of ways to cut a pieces so given a rectangular piece of represents rows times columns containing A's and dots and they're given the integer K and it's a hard part by the way uh you have to cut the piece in the K pieces you think K minus one cuts for each cut you can choose the direction of vertical horizontal then you get to choose a cut position at the cell boundary and cut the present the two pieces of course you have a square pizza but you know in the New York there vertical pieces or rectangular pieces but what the Apple come on you have at least made it like pepperoni or something I guess anyway I don't know I'm a New Yorker New York you know how can you be talking about pizza why is it a pizza just make it like I don't know pie or something apple pie I don't know anyway sorry this is triggering piece of uh anyway okay if you cut Pizza vertically give the left part of the piece of the person you got the pizza horizontally uh give the upper part of the piece of depression give the last piece of pizza to the last person return the number of ways such that cutting the pizza in such that the each piece contains at least one apple since the app uh since the Apple since the answer can be a huge number of modern okay I mean I'm gonna look at the constraints real quick but really I knew what I wanted to do and the question is just whether the constraints allow us to do it um yeah but basically the idea really is just before like some things with dynamic programming is the idea and a lot of things that are kind of uh maybe in this particular case implementation will be a little bit tricky and in that part of the implementation there is some understanding and pattern Eve from practice things that you can figure out but yeah but that's what I would say and I'm trying to think how much of it is necessary but the idea is basically brute force it um with memorization I mean you could do it in a uh you know you guys are doing bottoms up obviously but the idea in The Brute first is that okay let's see if we could cut one of the top two of the top three of the top four of the top dot right uh and then you could see if you could cut up uh one off to the left two off to the left three off to the left dot and then part of that is just checking whether you can see if there's a there's an apple or pepperoni I'm gonna call it pepperoni for the rest of this video I'm gonna mess up but I'm gonna try uh if this is gonna be a pepperoni on that thing and of course that's uh a sub problem if you will okay we're doing diet programming I'm using subform really but that's basically the idea right okay and so now you have two problems right or maybe not two but you reduce one problem the number of ways blah um into another problem of okay before us and let me just write this out right uh maybe that'll make it slightly uh you know and then the second problem is finding the uh pepperoni in a rectangle in a good time right because obviously you could iterate for it but it may be too slow right so okay so let's just say we have count of um uh how do you want to do it let's just say x y and K left right and this is gonna uh of course we have to talk about what these words mean or the inputs mean or is it we don't always have to do it but for this one uh you know if you're clear about things to yourself then you can kind of you know you run into edge cases then you can really ask yourself okay you know is it plus one is it minus one is it not either of those things you know uh that's what defining means so basically now this is rectangle starting from row X and Y is rectangle starting from uh column y or maybe another way of putting it is X Y is that the is the upper left um corner or cell of this of the remaining uh rectangle or pizza and then K is just number of cuts left and in this case now then it'll be just count of uh zero and then K right okay and uh yeah so if K is equal to zero and then we have to have some magic function right so if mm-hmm mm-hmm mm-hmm because basically the reason why we need a magic function well we'll see in a second but basically we need another the last slice because basically if K is equal to zero that means we're not cutting anymore right if we're not cutting anymore uh this is the last slice and this is the last slice we have to check that has an app on it right so if contains Apple of let's say X Y inclusive to I didn't write the words uh number of rows is you got pizza number of columns is you got a piece of Sub-Zero Sub-Zero Sub-Zero and uh let's say this is inclusive so it's gonna be R minus one C minus one right so if this contains Apple to that cell or with that rectangle then we return one this is one way to do it otherwise we return zero because that means that we ran out the last slice doesn't have any outposts we become very sad okay great um yeah okay right so I'm just kind of making sure that I'm structurally it okay yeah okay I mean I do worry about performance to be frank um so I don't know if this is going to time out now because what is it 50 Q oh no 50 times 10 times 100 it's 2.5 mil I might 10 times 100 it's 2.5 mil I might 10 times 100 it's 2.5 mil I might rewrite another language later but basically okay so let's do a quick analysis right um we don't know what this cost thing get is in terms of cost but basically okay now let's do you know vertical uh yeah vertical cuts it doesn't really matter but or like in terms of like either vertical first or so then let's say we go I as you go from X plus one two oh I think I messed up this is already obviously uh horizontal Cuts because we're doing yeah we're doing well so yeah whoops right then basically it contains Apple of X um Okay so yeah X plus one no just x and x oh no sorry X and I yeah X and I and for and from y now right this y goes to C minus one right Yeah so basically now we have two halves right we have the left half and then the rate half so this is the left half and contains Apple from I plus one R minus one y c minus one then we uh okay so we have some result is equal to zero and then you have this we added two count of I think I messed this up or I'm the way that I'm doing it is a little bit awkward let me think I should yeah I think this is more accurate I think that's why I was a little bit confused okay I think this is good though yeah this counts now we're chopping off it at the eye so now this is I plus 1 y k minus 1. and of course okay and here we assume that K is already greater than one because if it's zero we always return something so you cannot unless you I guess pass in something to begin with that's negative but then that's you know you're being silly yeah um and then maybe you know modded by mod of course and then now vertical cut is going to be the same thing right for I in range of Y uh yeah y to C if contains Apple from uh I guess X doesn't change so it's X from uh that right y to I and contains Apple of uh same thing and then I plus one C minus one this is cutting close to the edge but uh yeah and then if that's the case then we cut it vertically so if x we have I plus one and then K minus one and then we mod the stuff and then at the end we return R and should be okay so that's basically the structure um let's just say for you know we're going to test to see this I mean this is actually gonna be too slow still but um uh let's just return true for now right um so what's the complexity here assuming that this is over one and we don't know that we can convince this to be o of one um I mean okay spoiler I do know but in theory at this point of uh just so that we're clear but um but hypothetically this is the part of this code where we're like well okay now can we you know make someone what is the analysis of this right um before we go on because if this is already too slow if we assume this is all of one and this is always too slow then we need to do more optimizations before even contemplating this thing right so okay so what's the complexity here right X could go to uh it's O of r uh y can go to C I mean I guess just R and C right and then K is obviously just K right so this is going to be so the number of possible inputs is distinct possible input to solve R times c times K well and then um each input costs o of all plus C right and technically it's all process plus c times uh this apple function right I technically is probably only I'm just keeping consistent it's all right but if we assume this is all at one for now right so if we assume that's all one then the each input cost of uh plus C because that's just the two Loops right um in time sorry then total time it's going to be o of R times c times K times R plus C right and if you plug it in this is I'm plugging right now 50 times 50 typo 50 times 10 times 100 right and that's going to be 2.5 mil which to be that's going to be 2.5 mil which to be that's going to be 2.5 mil which to be honest is a little bit slow already right 2.5 mil if you ask me right 2.5 mil if you ask me right 2.5 mil if you ask me so I'm out of no confidence about this uh I might cheat a little bit later in a way that I'll show you but uh but I think technically speaking for one test case that will be fast enough and to be honest I know that this is going to be a good enough in another language maybe python is a weird Edge case where it's not um but then um what was I going to say I forgot what I was gonna say hmm old people problems just uh being forgetful you know maybe I've been having too much sugar maybe that's also the reason let me get uh water real quick because I've been talking a little bit too much so yeah but this also of course assumes that we memorize right so let's do the memory station now why not right so let's just say count has cash is you go to uh this is annoying to write uh oh no it's fine but times 10 right yeah okay that's not so bad because I was I didn't do the math so this is the total time but for each input cost all of one space because we only have to store my number so Total Space is actually only All Of All Times c times K which is going to be me pulling up calculators by one point to 50 times 10 is 25 000 which is you know easy to do uh relatively so yeah so this is going to be this times I always forget which time action this goes right and then the cash is just say none right uh and in this particular no that's true okay never mind for a second uh so now we can just go well if we have this cash then we return the cache right and if not then we do the calculations then we get the answer we're very happy oh oops this is true and then cash up of course this is true why would you ever put this as first right past Larry created that yesterday that's in case you didn't get to uh okay that's funny real quick uh okay it's not defined I changed it to Big K somewhere by accident whoops didn't I uh yeah because I was using k for the Big O uh okay oh I named it account as cash maybe Spoto with s2y but um yeah hmm oh I'm being dumb of course this has to be of course this comes out now this has to be do uh tiny top part that part this part I don't know that I need but it's probably fine okay I mean obviously this is gonna be one because we always has a return true but the thing that I'm actually testing on is um and there's only 10 no that was one uh the case that I actually want is when R and C is equal to 50 right and KSA 10 because that's where you have the most recursing recursive recursion uh yeah so let's just say oh is it 50 oh man so 5 10. two three four five yep yeah okay and then one two three four five ten one two three four five right hopefully I didn't make an error okay I'm still gonna be the wrong answer obviously what I want is actually um uh just put RC and K just make sure I mean it's fine either way but I just wanna I mean I guess even if it's 49 is okay because so 50 10 so yeah so this is the worst case and assuming that we have over one we have seven point uh 789 milliseconds which already is kind of slow oh it's slow the reason why that's slow isn't because it's slow is because on lead code if you haven't ran into this before and why now running again it costs one seconds the reason why that I have a concern is that on lead code um but not other online judges are not usually anyway maybe I'm wrong about that but uh um judges time out time limit exceeded not by the complexity they don't know how complex or you know there's no easy way to check complexity so they do it by having a time limit right and the time limit is usually say 10 seconds or whatever it is it does sometimes they make it bigger but it doesn't matter right the thing is that because they use something called a sum of execution time meaning that execution time of all the test cases just added together so then that means that and because you don't know how many test cases there are um you know like maybe my code like you know it takes one second for cases maybe with S40 cases it's too slow if there's 20 cases it's fast enough how is the you know how can you find like there's no way to know right it's basically the idea um okay so then now let's say for the sake of learning hopefully this makes sense so far this is going to be along with it is a very long video but um yeah let's say you have this so far and well now you have to implement this way uh naively how would you do it well naively you would just look through the rectangle but that could be R times C right like if this is these are zeros these are the end then you know and if you do it all the time uh where's my other thing you can put this thing becomes a lie it's R plus c times R times C which means this is going to be times another uh 2500 which means that this becomes like what 62 trillion or something I don't know look I don't I can't do math right uh hopefully you did it for me but either 62 trillion or 6 trillion it doesn't really matter it is too slow right um so we have to try to do a little bit better um so the way that you would think about doing this there are a couple of ways you can do it right um I'm just thinking about how to visualize it so I'm gonna just bring up uh the good old paintbrush sorry setting it up so there are a couple of ways you can think about this so I'm still pressing some buttons hang on Friends uh hope everyone's having a great you know Thursday oh no that's the one button uh I'll get there okay there we go um yeah gosh all right let's go do some copy and pasting but maybe I don't even need to hang on uh okay so let's just say you have you know and uh right something like this right and then now this is not the prettiest thing and then you have pepperonis in random places right and then the idea is that okay how can you make queries of um of like any arbitrary rectangle right uh and in this case the rectangles are actually not no I mean they are going to be arbitrary right just because um when you do these queries when you do a division you have to check the top half and the left half and all this stuff so it's gonna be relatively arbitrary even though maybe some of them would be um maybe one part of the query will always be um next to one of the sides or something maybe but I think it's still going to be pretty weird right so then the there are a couple of ways you can think about this right um so the way to do this it turns out is almost like an idea of prefix sum but in two dimensions and if you don't know about prefix sum maybe it's not that important because now I'm drawing the geometry and hopefully the geometry will um you know the visualization will kind of you know you learn from the geometry right and the idea here is that okay let's say you know what is the this how many pepperoni is there in this rectangle right well have only in this rectangle it just turns out to be a decomposition of the number of pepperoni in this rectangle minus the number of pepperoni in uh I'm gonna choose another color hanger uh minus the number of pepperoni in this rectangle minus the number of pepperoni on this rectangle right so then now basically in a way you're saying that okay you have this rectangle you want to subtract whoops uh what the what is wrong with this thing am I like pressing a bun box maybe I am sorry hang on technical difficulties what is going on with this pen did I like Drop it a little bit too hot uh this expensive what is going on sorry friends do you see that huh okay now it's better I that one I actually didn't okay that's really weird Okay anyway so you have um you have this rectang oh I you wasted too much stuff anyway you have this rectangle and then you want to subtract oh what happened okay let me try again sorry friends technical difficulty so it is just equal to this rectangle right minus uh this rectangle minus this uh this rectangle right so I have to choose another color so now uh I know that missing one hang on so now but because of that we noticed that we subtracted this thing twice so basically now you just have to uh add this back on right so now you have three rectangles oh sorry four uh yeah four rectangles right um and the reason why we structure it this way is because then now we can pre-process we can pre-process we can pre-process how many pepperonis are there just starting from the corner right now we Define the question into a question that we can solve a little bit easier um and that's basically the idea um yeah right I'm gonna write this in a very funky way I'm not gonna lie um but I think I don't know if it's true because I usually write it uh Bottoms Up and kind of do this pre-processing stuff and kind of do this pre-processing stuff and kind of do this pre-processing stuff but I think I'm gonna try to write this in a funky way um and maybe it's more intuitive leave me a comment whether you think this is true um yeah okay so basically now let me try to make sure I'm just trying to make sure that uh my bounce or I do have to be very careful my bounds because I don't want to do off by one that is why so basically this is um direct the number of pepperoni in um I'm gonna say apples just because all my function names are like this right from this corner and this is um yeah okay let me how many apples are inside a x a y two bxby uh inclusive right and then yeah and then count apples oops count Apple the pro as well but okay fine I'm consistently wrong anyway then I guess uh tired I don't want to fix but yeah but how many apples are in um X Y to uh minus one C minus one Corner inclusive right that's basically the idea right so as we said it's going to be this minus can apple of so we want BX inclusive so it's going to be X plus one b y minus count Apple of wait is it by uh let me you can't see me doing it because I'm too lazy to we put it up but I'm just looking at my diagram so no this is going to be from a y right so it's just the uh no this is just a fat bottom one and then now we subtract the uh the right side and that's what this will be yeah and then now we add back on that little uh double counted corner uh and then I'll just be B1 b y plus one right and then this we just return this is greater than or equal to zero right oh well no this well that would always be true has to be greater than zero whoops that would have been a the painful thing to debug and then count Outpost um okay wait how many apples are there to x y well um yeah and you could do this a number of ways and like I said in theory uh I probably you know we're not teaching or whatever I probably just do it uh tops uh yeah bottoms up uh if you want to do it that way it's very similar to how you construct um say a binomial this should be a binomial the exponent of a binomial polynomial for example binomial polynomial that sounds like a song okay anyway um but yeah but I'm gonna wait just a little bit differently right so how many apples are there from X to y or that corner well we could just do it one way to slice it is maybe that's not very smart and maybe the weight I'm doing is a little bit weird not that I think about it um oh no I know I'm just trying to be too cute right okay I got it sorry friends uh I'm just double checking that I don't have to my drawing blocking the screen because sometimes that happens and then I'm like I did all this explanation and coding and stuff for no reason okay no um okay so then basically it is just um return count the number of rows a number of Apple on in a row of X Plus count Apple of X plus one y right um you can think about it as if you have a rectangle now I'm counting the number of apples on the top row and then recursively calculate um uh the number of apples on the next well the next rectangle without the top row right um oh wait uh I think I need a divider because yeah right it was this is kind of getting iffy but I'm still doing it right so ever by Row three and X Y uh it's just how many oh how many apples are in row X starting from column y right and I need there needs to be a base case by the way I didn't really do it I didn't really complete this yet so I'm aware of it I'm a little bit slow this is a half an hour video there's maybe another five minutes ten minutes left I don't know I'm going very slow um but hopefully it's insightful right I'm not doing it just for I don't know basing time maybe I am I don't know glad you've been drunk so yeah um okay so then this is just return count Apple by row same row y plus one Plus red piece of X Y is equal to a right yeah something like that I mean we could rewrite it in a second um but that's basically the idea right like if uh let's just say p is equal to zero uh we increment by one something like this right uh and then now let's do the base case so basically this idea is the same thing but now by column right so we want to get how many apples are in the world starting from column y well that's just maybe one maybe zero plus the rest of the row right so that's basically the idea and in this case if Y is equal to C then we return 0 because now we reach the at the end that's basically the idea and here's the same thing where if x is equal to R um then we return 0 because well we just ran out right um okay now we're done right uh no I know I mean okay we're given our bounds I probably did some really funky things to do without bounds actually but uh huh but oh yeah I know I knew this because uh because this can be whatever X could be out of balance is what I mean as well hmm that's not true then is it huh how why is it our bounds man hmm as we say in the business yikes hmm why is this all right let me double check it real quick um I guess I have a debugger actually but still um does it tell you like I wish that for this is such a like everything just tell me the index you know like if it's all about I mean it's fine but just tell me you know okay why not let's see if this gets me it may not uh see it doesn't go all the way to the last one okay uh this is only okay let me just kill this one for now and then huh so why does this fail for 50 awesome that was silly now I don't have that case anymore but anyway what's weird though right like there's nothing wrong with these things that uh also this should be right for these so I'm like really wrong in some places but well see well is it just always returning zero okay so that I probably have some way to fix um don't over here though hmm one-time error contains apple right uh let's just let me do a quick assert hmm oh there you go do I have a typo somewhere X goes to oh I goes to R minus one or minus oh okay yeah okay whoops I see that's probably the other issue too just do off by once uh I mean still one or I said my assertion why do you take away my assertion let's stop let's double check this assertion for now hang on okay now we're in the debugging phase but well we're almost there hmm does it tell me the actual value no I just tells that assertion and then okay well where else could it be I um I mean this is the only place that we're you know running so and we only have this is these are small cases so uh huh this doesn't this isn't fail this oh no wait one zero hmm okay that does fail the assertion so zero goes to uh no way that's not I printed this in the wrong way actually it's a little bit awkward because this actually prints ax BX so it goes to one zero to zero two which is the entire rectangle and angle it goes to one two to zero two did I do with typo hmm uh the other thing about this problem is that it's very easy to make a typo and you know this from uh the explanation video will probably be very long even if I had not done a live but as you can see this is the risk of doing it live hope you're enjoying this but you know it's fine so okay so what are those let's print this out in a normal person thing right all right so zero which makes sense and then it checks so it does fly from zero it does this check so then that's zero two uh okay so it goes from zero to zero two what is this again so this is zero two okay yeah that makes sense and then it does one two what should this be one two to zero two what oh why am I doing this way oh no I do a x a y That's why Larry what are you doing why is this ax a y who writes this oh no this is a no axx is what right is fine I'm just inputting it in a long way because library is dumb okay yeah why do you do things like this okay yeah why what is wrong with me how can I group up to Elka anyway it's just a very bad typo slash confusion uh that's a but this is the corner and then okay that's not right is it yeah that's right maybe all right let's try again okay I mean at least we turn one which is progress maybe I guess hopefully uh and we no longer failed the assertion so that's also progress um hmm maybe now just doesn't fail because I thought that was a little bit weird but maybe not maybe I'm still going out of bounds oops what am I doing weird then I should go to C minus one that's fine C minus this part is still weird though oh no because if this goes to C minus one then this is just an entire slice so now this still needs to be that hmm new X new y okay this is good or correct ish unless I misunderstood the problem now the problem is okay uh hmm huh this is just silver wait let's do it's inclusive right okay now maybe I have to check this maybe I have enough buy one hmm should be okay Maybe all right well uh more debugging sorry friends let's double check this is how things work to sometimes all right so some CO2 this is returning one which is clearly oh no that's true one zero two three two okay uh okay well I mean I think one thing that we can do is actually uh for the purpose of debugging um just to uh you know count zero of four x is in range of ax a y plus one for y and range of uh B what oh what no PX right uh that's why I got confused right what was it okay piece of X Y is equal to a yeah basically we're just comparing with proof first right and this is why we have assertions oh well okay so that means that these functions are right so that means that this function is right um because it's been it matches the brute force in every Square so far I mean you know who knows where this is actually true but at least for the inputs that we worry about so then that means that something else is kind of weird about um but now that means that we know that this part has an issue hmm maybe I do have an additional typo so the same X we go y plus one right yeah okay why is it retelling I mean this one is actually the one and that's right but hmm is it this part no I mean this part looks pretty straightforward really uh let's just print out this I guess uh okay so it goes to one two which is but that means that we're missing some potential things uh one another one two so that's just the last thing right but clearly from here it should also make a chord to one that's why it's wrong 11 off by one here somewhere yes what was it seeing right so this is X hmm so I think one thing that we can do um is that uh you see is that this is like a square and sometimes for squares it's easy that to mix up x y and that's what I did a little earlier right so let's kind of see what it just gives me an error if this you know the idea here is that if um uh now it's out over but the idea is that you know if I have X Y mixed then there's more ways to kind of give me um our balance exception and stuff like this um but now it's just very well let me understand this problem that would be funny if I just go on it uh I mean I knew how to do it entire way but I don't know uh okay um hmm let's see so I've and even in this one oh I guess I could keep this in there just further I could find this again for the uh the three the new case four um it still looks okay or this part of the code looks okay so I'm convinced that this part is okay at least for now right but that means that the only displays that's left okay am I missing a row or something I mean so if this is X it chops up to five right let's see and this is a very long video why is it going one two all right let's take a look uh hmm so one with one cut left is going to be one okay I want to see Zero one with two cut with wait did I miss the K minus one somewhere or something how can you have two oh no yeah oh no it's three Cuts total oh no that's it's not three Cuts it's three slices so this is actually K minus one okay oh my this is the silliest I mean there are a lot of things I'm silly debugging but alright that was pretty dumb okay hello guys uh a lot of people make mistakes I'm gonna make a lot of them hope you uh hit the follow button and hit the Subscribe button I did love fun uh give Larry some uh love but yeah but one thing that I would say about this is we're not done yet and we're almost there with 95 percent of the dares bear with me uh this part is the easiest um per se is that if you know if you kind of you know uh skimmed over as I did because I was trying to debug uh I think you know we're good now maybe um is that um if you I mean if you really look at how these things are constructed it will just look at each cell once this means that this is going to be of R times C uh times four even in the worst case right but what can you do well what can you do is memorize right because how many possible inputs are there to this thing well same as here right R times C how many Hospital inputs are there to this thing also R times C so all we have to do is memorization and yeah so that's just uh let's just do it really quick and the funny thing is it may still time out and I'm just gonna like I don't know just be very sad say um oops um yeah right so then now you have something like all right and of course you have to actually use it otherwise that's just sad right so that's already uh pretty Gucci and then of course uh I mean you could add a factor by not caching this uh if you're really lazy but I think that's just I think it gets amortized out anyway to like end uh all times c times 50 or something but like but it's fine oops uh nope and the same thing right and then of course once again this is just not good enough if you don't cash or if you don't use it okay and there you go now I'm gonna give a quick run and then be very sad to remember that you know you have to allocate a little bit more foreign so this ran pretty quickly but of course like we said we have to uh do the 50ks I think so let's do it let's add this 10. uh let's see what are we doing all right and then that's one real quick um now is it gonna time out I don't know so it so that's the thing right like this case it's good we have the right answers we're very happy oh I left them print statement somewhere didn't I okay maybe we can after my but before we do anything let's make an optimization of not printing something okay I mean that didn't actually change it that much but I'm gonna give it a quick submit I expected the time limit um maybe we get a little bit lucky and we do uh and I it takes 12 seconds uh there are some other things that you can maybe do an optimization on by doing it Bottoms Up to be fine just a big one um but really I'm happy that I don't have to optimize to be frank uh because I think I'd probably vote mostly the same and then uh hmm maybe I hmm why um I don't know what I did oh no I just had to type or I forgot to do it okay so that's a different one yeah um yeah now that we did all this uh this function is gonna be all of one because it gets amortized out um because this is always going to be all of one as well after we fill out the cache which means that is going to be all of and all times c um which is linear right so what is the complexity here uh it's going to be of R times C I mean this is the complex day for time this is the complexity for space and yeah thanks for you know joining me on my on this very long journey uh to this problem I hope you really enjoyed it hope you really uh you know figure this out and hope you are uh this K minus one took me like 10 minutes or something that's really sad I just didn't I misread the poem ultimately still I suppose uh I mean some of you might know that I did a 72 hour fast earlier in the week uh this problem was already another fast for me apparently so I don't know but I'm joking aside thanks for watching if you're still here uh let me show you the top of the code real quick so you want to pause the screen let me make the slightly smaller uh this is too small to see maybe but if you just want to pause and kind of look at it this is the top uh these are my two functions uh this is what I mean I don't know if there's a technical term for it but what I call it is uh a memorization of a loop because you can think about these things as a Four State uh yeah for um a for Loop um but memory memorize incrementally almost like a prefix some with suffix sum or something like this so yeah so you know this is just a more visual way of doing it and then here um oh yeah and then contains apple is the geometry part of it there's no memorization here um it's just geometry we kind of showed it on the you know we drew it out and then here's the bottom which is the uh and I'm gonna just skip the I guess the cache actually fits on the page but yeah but this is just proof of making her sandal Cuts vertical Cuts making sure and I don't think technically you need to support um because this gets checked at the end but it probably is an optimization that makes it slightly faster to be frank because you don't want a infinitely cutting apart that um you don't want to do work on a part that doesn't have any Outpost and this of course is all of one anyway so uh so it's a very cheap check probably needed to type to pass time out to be honest because even with it we end up spending 12 seconds anyway right so yeah um that's all I have for this one let me know what you think show me some love hit the like button hit it twice no wait because then that unlocks it okay hit it three times send it to your friends uh send to your enemies because I don't know they may not appreciate watching this for an hour and that's all I have for this one let me know what you think uh yeah stay good stay healthy to good mental health I'll see y'all later and take care bye
Number of Ways of Cutting a Pizza
number-of-steps-to-reduce-a-number-to-zero
Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts. For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person. _Return the number of ways of cutting the pizza such that each piece contains **at least** one apple._ Since the answer can be a huge number, return this modulo 10^9 + 7. **Example 1:** **Input:** pizza = \[ "A.. ", "AAA ", "... "\], k = 3 **Output:** 3 **Explanation:** The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple. **Example 2:** **Input:** pizza = \[ "A.. ", "AA. ", "... "\], k = 3 **Output:** 1 **Example 3:** **Input:** pizza = \[ "A.. ", "A.. ", "... "\], k = 1 **Output:** 1 **Constraints:** * `1 <= rows, cols <= 50` * `rows == pizza.length` * `cols == pizza[i].length` * `1 <= k <= 10` * `pizza` consists of characters `'A'` and `'.'` only.
Simulate the process to get the final answer.
Math,Bit Manipulation
Easy
1303,2288
1,345
hello everyone so in this video let us talk about a problem from lead code that is a hard problem the problem name is jump game four so i've already made a video on jump game one jump game two and jump game three they are like a single video in all of the three jump games are already made so if you haven't like watched that video i highly recommend to first watch that video out because that will that video will also give you a lot of learning points so let us now jump down to the jump game 4 okay the problem statement goes like this that you're given an array of integers ar and you are initially positioned at the first index of this whole array fine now in one step you can jump from index i to i plus one if the array permits like if there are more elements on the right side you can also go to one step left that is i minus one and you can go to a particular j index such that the value of a r i and the value of arj is same which means that let's say that you are on a block that is of value five so you can move to any other block in that area that is also having the value five fine so like you can teleport so you have three type of moves you can do you can either move one step ahead one step back or you can teleport to another block in that same array which has the same value as the value you are upon currently now you have to minimize the number of steps you have to do so that you have to reach the last like area of the index uh like last index of this whole area sorry and that's the whole problem now how you can do that uh you can pause this video you can think over that how you can solve this problem but what you can see here is that greedy approach do not work here why because it can happen like it should not be like you can only go one step ahead because it can happen that maybe you take one step okay you are currently on let's say five and you can teleport to one of the another five but let's say there is one more five that is too far from reaching the end but let's say that you just move two steps ahead and then you can directly move to the last step so it means that there are some sort of a dp all you have to some sort of store the states you have already traded over but can i directly use dp here yes we can but what you can also observe is that you have multiple options around it that you from one step you can either go to the left or right or to teleport to some other point so you have to also somehow know where are all the positions to which you can teleport to so that you can get the smallest amount of distance you can land upon what i mean by this is let's say that okay let us take the example let's say that this is an array and you're currently on this point now maybe you can just take uh three steps to land upon this point or else what you can also have done is that you have gone to a different point and then it might have just taken two steps to land upon this point so this is also like three steps one two three and this is also like one step two step three step so like they couldn't so you have to also somehow know what are the smallest steps that you can do so in that scenario what you can do is that you have to somehow keep track of the number of jumps you are doing at every point of time what i mean by this is that let's say that you are doing some jumps one two three you have landed up on this point of time that point now what you can also see is let's say that i have also done this jump so this value is five and this value is also five so from five you can either do this jump because this is the first point you cannot go back jump or you can have done this jump so both of these jump will take one amount like one cost okay so this will take one course and this will take one cost so now this is the least amount of moves required to get to this point so let's say that this point is six okay so this is the least amount of like points because in any other way let's say that if you even if you take one more route to just directly come to this point then also it will take more than or equal to this amount of uh steps only so whatever point you reach the first is the minimum amount of step it will take to reach that point because it cannot happen that later on you find out a point that is much more lessing so whenever you're traversing the or finding out the least position for any one of the points that is actually the least position only why because later on it will not happen you will land on to the same point again even if you land up on the same point it will be taking more amount of steps to land upon that one instead of just taking smaller steps so you have to also understand that you're that you just want minimum amount of steps only got it so that is the overall logic where you just have to store out the points now it all sounds very confusing to you but what you can do here is that you can some sort of a make a queue now what you can do is you can first push the starting index that is the zeroth index into the queue and then so from q like from zeroth index you have three options you have to also make a map you can say that is storing out for every number let's say that it is five at what positions five is occurring like it's a six at work position six is okay so that you know from any point of time like from every point which point i can reach to uh so that because if there's also a thing that the same values you can directly move down to those points also so you can also have to know which indexes i can directly go to so if there are a couple of fives like this five and there's one more five so you know that you can reach this five or you can also use this type in only one step so that you can directly like you can also like make a visited vector so that you can also store out this information key okay the minimum amount of steps take to reach this point is like you start from zero so this is one you can like reach this in one point you can also use this in one point so that you will not like find out the answer for this again because you know that this is the minimum answer because it will not happen key you again find it a route and it will get you in less than one position i hope you get the point so that is why you have to somehow store these values also and this is the dp value that you have to store the minimum values to each of these points and from this point let's say that you reach out this point and you want to let's say reach out this point at six now you directly reach down to this point from this point you can directly go to this point so you know that this point requires one moves and now this is just one plus one move that is two moves that is required so from the queue you can directly fill out the other boxes also so this is one this will also take two steps and from the steps and this was required one step so this will require two steps they could disregard two steps because from this point you can go to this point in minimum one step only okay so you can like some sort of user queue to fill out the positions and from this position when you get these positions you can like push these indexes in the queue because now i know that the minimum amount of steps required to get to this point are no because i already do that you can get to this point by just one step and one step in one step so you can like fill out this position and push these indexes into the queue and then iterate over these points like again so that you can fill out for the whole thing and you will obviously will get the maximum or the like you have to reach the last index only so you will obviously be getting the minimum amount of steps required that you can get so that's the overall logic for this problem let us go down to the code part so what i've done here is that this is the first map that i actually created out that is uh like that is a map of queue but you can also make a map of vectors also i just uh just a fancy term to like use a key also but i'm just storing out what particular element is mapping to what indexes so that i can just directly create over them so just a map of integer to a vector i just used q but you can use a vector also that is that mapping out whatever a particular q like a particular index is at then i use the queue and this is the distance that distance vector is just a dp vector that will store what is the amount of minimum distance of course it will take to reach down a particular point this is the distance that i initialize the starting is zero that for the starting index we don't have to require any cost because i land or start from the starting index so it is zero and also push the starting index that is zero so that i will continue moving around the cube so we will move and do a while loop until our queue is empty it's just sort of a bfs only what you can understand is that i push out the first queue like the first segment if it is not the last index like if it is a last index we can directly quit at this point because we just want the last index why do we trade over all the other points also okay then we just peek out to this point else what you can easily see here is that now we have three options you have to either move back front or to the same index now if i just want to move back then i should also ensure that there should be at least one element back to it also so if i minus 1 is greater than equal to 0 which means that the left element exists and if it is not already distorted because i initialize my distance to be minus 1 all are minus 1 which means that i have not visited them but whenever i move to some point i will only check that if it is not wasted i will first mark out the distance okay so from i minus 1 you can reach that point by distance of i plus 1 because you just only required one more step and then you will push out that particular index in the queue so it means that from the particular element which i cannot reach i will first mark out the distance and then push that particular index into the queue so that i can again iterate over that similarly i can do it for the right element that is i plus one and also for all the elements that are in the map okay because that i can directly move down to so i iterate over the map also all the elements that i can jump in one step mark it out also pop it out from the queue that is just a simple implementation and just in the end i will be printing out the distance required to reach the last index that is n minus one so that's the overall logic the code will be in the description of this problem don't worry thank you for watching this video till then i'll see you next time next month keep coding and bye
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,675
hey everybody this is larry this is me going with q4 of the weekly contest 217 uh minimized deviation in array um so this was a tricky problem um we're gonna go over this and then we'll do some minor quick code reviews and then um you know you could watch me still be live during the contest so hit the like button and subscribe on drummond discord and the way that i like to explain these problems is not just the solution but the way that i thought about it during the contest so that you know you see my thought process you could fast forward in 2x or watching 2x if you uh you know feel that's a little bit too slow but anyway so the we have two operations which is that one is given an even number we could divide it by two given an odd number we could multiply by two but the key thing to know for this problem is that um if this is an odd number you can multiply by two obviously as we said but you only do it once right because once you do it um once you have an item when you multiply by two it becomes an even number so you cannot do this again you have to be divided by two um or you can only divide it by two so putting that noticing that um i would try the way that i was trying to do is actually i misread this during the contest i read it the other some reason i just misread it but from that um you would try to find an invariant which is uh something that doesn't change as we loop through the array so the first thing that i do for this problem and i like to go with code maybe visualization is a little bit tricky let me know but basically for this problem um i took the invariant is that um or one of the things that we notice is that as we said because we can only do art once uh let's get it into a state in which we can keep on where everything is the same and everything every number in the array is even right so that's basically my first idea um so for every number is that is odd in the way we make it an even number we sorted though you can actually probably don't need to sort like this but um but yeah our best answer right now is just the biggest number minus the smallest number and then the invariant is trying to figure out um you know let's say we have the biggest number that we oh sorry let's say we start the smallest number right in this new array our smallest number once um once we get past the smallest number and we uh we cannot go any longer right because if we take the smallest number and we divide it by two um and we go under the smallest number um yeah uh because once we go under the smallest number then you know we don't need it anymore um and then after that it just becomes a heap problem of okay you know let's say you have a list of even numbers right so let's say you have this array so you know we made it even so and sorted it uh so it's let's sort it first 1 3 4 5 20 and then we make them even so 2 6 4 10 20 so okay let's move to four here right so let's say we have an array of even numbers which is how i draw about this during the contest um well the thing is that we you know because we can only make the numbers smaller now because every number is even we're always going to want to take the in a greedy kind of way we want to take the biggest number and make it half right so in this case we take the biggest number we make it half and you know make and then now this is not the biggest number anymore we make them take the biggest number make it half and so forth um so that's basically the idea behind this and also once we um you know once we see an odd number we know that this is the biggest odd number so we're not gonna we're gonna stop there so okay so you know as we were doing the thing uh we want the thing that we want to check of course is that okay we have this the biggest number and therefore the smallest number right so that is what this problem is trying to find that's the deviation of the problem or the um the array so every time when we take the biggest number um you know it could so two things can happen right one is that it's still the biggest number which nothing happens because you put it back in the array it's the biggest element and then we check it again anyway later right um but if it's the smallest number let's say for whatever reason this is six and no uh well now we have a newest smaller thumb where we put in the front so now we just have to keep track of that um that if we divided by two and it is the newest smallest number then we use it to uh keep to do the calculations on later on otherwise for every iteration we know what the previous smallest number is um and it's gonna be the current smallest number until unless you divide by two and it becomes smaller so now we can just calculate okay now the range of this array is just eight because it's just ten minus two right um and then now this becomes a five so since it is not smaller than two we know that it's just going to be inside somewhere uh so that's basically the idea and using a max heap that's how we're gonna keep on popping off the top and so forth uh and then the other thing is well why is it that when we get a odd number we can stop well we can get it when we get an odd number we can't do any operation on it right so that means that even if we go into the middle let's say this four and we make it you know we do operation on it doesn't change the answer and it's not for the better because we could change this two to one but that only makes the answer worse so the greedy right after that you're able to terminate so that those are basically the observations that i needed for this problem and that's pretty much it um that's the implementation is that while we have a heap element and it should keep on having heap elements we and this is a max heap so this is why i changed them to negative numbers because in python heap is a min heap so i just did negative numbers to make a max seep so yeah one once this new number is smaller than the new smaller then we break i think this is actually necessary but otherwise again we this is the range now the current now is the biggest element in the heap which is the biggest element in the way so you do that from the largest element and the smallest element um we popped a heap and if it's an odd number we're done after we you know calculate the range otherwise we update this smallest number to the new smallest number and this is what i forgot to do during the contest right eight five minutes penalty uh and knocked myself off top hundred i guess and then we put push it back into the heap um that's pretty much it and the invariant is such that you know everything in the array we keep track of this new smallest new small is what i call it but the smallest element in the hebrews we keep track of that and that's true and then the height the biggest element is the top of the heap because it's a max heap and that all the numbers inside uh between those two numbers and that the biggest element will have to be an even number for us to go on so that's pretty much it this is actually uh i found this problem to be honest uh easier than qtvq was kind of really tricky but yeah uh let's do a quick code review to see if you know people did it enough any funky way oh yeah i forgot to do it in an analysis um so what is the complexity for this problem well it may look daunting but because we're only divided by two uh or we get to um because we don't know how long this one loops because for every element we put in a back but it turns out that because we divided by two every time at worst um it's let's say the number is 2 to the 30th and most that's going to take 30 operations to get it to an odd number so that means that for each element or in the array at most it's going to be 32 elements or um so it's going to be all of 32 times 10 to the fifth which is fast enough uh and in terms of space it's just all of n which is the input so yeah so of n um of n uh time o of n space as a result if you want to put the constant as uh log of the range or the log of the u where u is the size of the in universe from 1 to 2 to 32 or something like that um but yeah let me know what you think you could watch me solve it live during the contest okay let me actually take a look and let's turn to the fifth um okay well oh okay gives me something okay it's five and one okay now we're going to pick a symbol yeah it should be good because at most is 32 times each number maybe is oh no that's why i wanted the other film no this is okay you don't wait to only do this if it's odd so actually this is not true because that means you're going to do this once and now we have all even numbers now we want the smallest actually you a big number there this is not even close but oops kidding me all right let's give it a go to half an hour to go it's one of those days i can't even copy and paste into something how do i get sir so this is six and ten no i don't uh whoops this isn't right how did i not catch this i meant to do this okay that one oh okay so i did uh hey everybody uh yeah thanks for watching let me know what you think about this uh problem set it's that was a very tough problem set um so and this farm as well so hit the like button the subscriber and drum and discord let me know what you think let me know your questions and i will see y'all next farm bye
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,662
hi python developers welcome to today's lead code daily number 1662 track F2 string arrays are equivalent so in this problem we are comparing the characters instead of the strings in the arrays or to say we only care the overall position of each of the characters not the position in the strings for example here this character C we only care about the overall position that is 0 1 and 2 so the position for this character is two instead of zero likewise this character in the second array is also in position two so that's why we are comparing those two characters instead of comparing C and BC we are not comparing the strings but we are comparing each of the characters by their overall position in the array in food all of them other theme then we return to otherwise the false we know the brutal thought way to solve this problem is to concatenate all these strings in each of the array to a big string and then we compare the first and the second big string if those two big strings are the same time we return true otherwise the fourth now the problem in the brutal fourth method is that we have to concatenate the big strings this will take actual spaces that is not necessary so is there a way that we can uh like a pointer we can go through all the characters in The arrays and each of them we will take just one character from both the arrays then we can compare them so this method is called a generator so in our generator we can return a piece of the information one by one so like here we can return this piece of information under this disease so we can return one character a time from this whole array then we will be able to compare the characters instead of this whole big string now let's look at the python code the first step is to generate the characters the return is a generator of strings and in this function instead of the normal functions which will usually stop the function without return the generator functions will return the informations one piece at a time instead of returning all the information at once so we can see that each of the time we will just return one of the characters from the word array in our Manufacturing the first step is to check the size of them if the size is different that written Force secondly because in Python we have zip so that we can return C1 and C2 together if they are different than written Force if we do not written Force previously at last we return true
Check If Two String Arrays are Equivalent
minimum-numbers-of-function-calls-to-make-target-array
Given two string arrays `word1` and `word2`, return `true` _if the two arrays **represent** the same string, and_ `false` _otherwise._ A string is **represented** by an array if the array elements concatenated **in order** forms the string. **Example 1:** **Input:** word1 = \[ "ab ", "c "\], word2 = \[ "a ", "bc "\] **Output:** true **Explanation:** word1 represents string "ab " + "c " -> "abc " word2 represents string "a " + "bc " -> "abc " The strings are the same, so return true. **Example 2:** **Input:** word1 = \[ "a ", "cb "\], word2 = \[ "ab ", "c "\] **Output:** false **Example 3:** **Input:** word1 = \[ "abc ", "d ", "defg "\], word2 = \[ "abcddefg "\] **Output:** true **Constraints:** * `1 <= word1.length, word2.length <= 103` * `1 <= word1[i].length, word2[i].length <= 103` * `1 <= sum(word1[i].length), sum(word2[i].length) <= 103` * `word1[i]` and `word2[i]` consist of lowercase letters.
Work backwards: try to go from nums to arr. You should try to divide by 2 as much as possible, but you can only divide by 2 if everything is even.
Array,Greedy
Medium
null
117
Hi guys welcome to take to live Nivedita and in this video we are going to solve populated next right points in its node to service problem is I have given you a cup binary tree and said here what is populated next point to Point to it Mix Right Noticed a Prisoner Next Flight Mode Next Point VS So what will we do with its mark? Next 9 will be the tunnel for that note. Okay, we will set the tunnel that there is no note to the right of it, so its next 9 will be the convincing example. Do you understand that there is one here in the night of the first seven? Now see, if there is nothing here, then what will be the next note of Vansh? Your logart is ok, that is located on the right, so the next of two will be 9 three. After all, there is nothing on the right, so what will be the next note of 3 here, it will be null for four. There is fiber in the diet, hence the rate of four will be next note5 of five, next of five will be seven and seven will be connected note channel because there is nothing in next of seven i.e. tight, because there is nothing in next of seven i.e. tight, what will we do by sourcing tight, next of seven will not be right, it will be final. Ok so in this problem we are looking at what we should do level wise, what are we doing level wise, we are looking at the level poison, there is no right choice on anyone's right side, there is no right choice here in these means, you see who has someone on his right side or not, okay? So the gesture is bad in a way when the level of all rises we are seeing that in one can right in this level is there any note to the right of vansh in this level or not if there is then it will be its next9 if not then null What will happen if it becomes national then here one has become national, in this level you will see that if you are a light mechanic, then two is next 9. Secondly, in this level itself, there is nothing in his favor, then what will happen to him, next 9 will become convinced. We will do this level wise here, so somewhere here we can use level order rice. Okay, here what we will do is use gas, our level and tower styles and solve this problem. Okay, usually what we would do. What are the level and base year, what do they travel left-to-right, do base year, what do they travel left-to-right, do base year, what do they travel left-to-right, do n't they do it like this, 17234 5748, but to solve this problem, what will we do, instead of doing left-to-right travels, we will do it right-to-left. do, instead of doing left-to-right travels, we will do it right-to-left. do, instead of doing left-to-right travels, we will do it right-to-left. Okay and to solve this problem, let's come to what our approach will be is we are going to use ka here, we are going to use level and traversal wise, so what we will do here is we will use ka, okay so first level. But what is ours One is from 123 A is 457 nights on the coast So what will we do Why will we take one here Now why I Why I What will we do in the initial We will do the root note inside i.e. we will root note inside i.e. we will root note inside i.e. we will set the one in Yes so we are interested What will we do after inside the point, what will we do after that, there are no other elements at that level, otherwise what we will do now is take it out from here, this path is the top element, the current one, OK, and we will take a previous one for here, previous What will we do first? Initially we will see that there is no other element at this level. You first, what will happen to the houses in the cat means that nothing is going to happen next. What will we do next. We will enter the forest next. If it is educational then here But this will be null, okay, now there is no other element in this level, so what will we do to prevent it, we will not change it here, if there was any element here then it would be the result of the previous smart top. Okay, but in this condition first. This is not the case in the level, otherwise we look for the second level, then what will we do, first put the right child of the first inside, here it becomes the mother circle level, okay, we will do it this minute, then we will see what element is there on the right left, what is its What is the condition of the channel? Set that also, so this is your level. What was your first level light? Now, what is your second level? Like this is the second level. Now we will see for the second level. Now what will we do? We will extract the top element from here, what is the dhamaal in the topic, what is the free top element, what is our serial, what is our previous, what will happen here, there will be a tap, okay, prevent, this preparation will be in al, what is we, what is the neck of Shri, what will we do, we will make the tap okay. Now there is an element ahead of this too, so what will we do with the previous one, we will open the top, the passenger count will be done, ok then what happened to us here, the top has been updated, will there be a problem at that place? Two will be done. Okay, now what will we do in the inspection of the top, will we do the previous, not ready, two, keep connecting, three, this is what we need, right, three, collect, tap, this is what we have to do at this level, two should be connected, there should be no connection. If it should be then two connection Africa Next tap i.e. what has become of this two connect thrill is the next tap i.e. what has become of this two connect thrill is the next tap side of the entry this has been made now what will we do see what you had to do along with popping, you can do this trick and here you can do this What to do here after connecting you had to see what is its left and right side, what is the condition of its light, then what should I do with this light, save it for 1 minute here, if there is anything in the last, otherwise I will leave it, then you will For this reason, we had taken it out, connected it from here, what will we do after the connection, then right to left, let's see, is it right? Yes, if it is right, will you five or insult? Right five, what will happen to you here, you will be insulted. Okay, then what will you do? You will send the photo, it will come on the left side, you will set it as foreign, you will do OK, so what will be your third level, what will this become, your third level, now what will we do on the third level, we will collect the next point. Now how will you do that in the Collectorate, here I have told you, let me tell you again what you have to do, you have to take the top element, then what will be your element, what will be your seven, what will be the human prevent, what will be your tap, what will be the previous tap, ok take. Lia, what will we do now, so you call the next fuel's next previous key, honey speaker tap prevent channel, do OK now see what is the next element, let's pause it, let's see what is the next element, write whenever you are here. To get off the hook, here we will pop it like this, before popping it, after recording it, we will see the connection in it, after making this connection, after the connection, we will see what is the left and right side of the intake, what is not there. Level will not be created, okay then what will you do from here, you will remove the face, okay, the top element will be your fiber of Play Store here, five will be updated, you will also update the previous one, what will you do, you will see the previous five by clicking here. First what you had to do was to update Prevent by tap Seventh OK so that Nursing Seventh was selected by you because it has this level and element so we will update it then you have to update the top sometime. After updating the top card do the next to top. After cutting prevent not lost admin or added ok consumed Will give love will update the page Entry fee will make it round Will open the fabric Then like the top Will take elements and will do rice That this will be a file and this will be a photo Then what's next on the phone Top's Next Previous Unified Look, this is what we had to do, this is what I said, to fold 5.7 Conventional 5.7 Conventional 5.7 Conventional 14.55 Connection Illegal Connection Al This had to be done, did 14.55 Connection Illegal Connection Al This had to be done, did 14.55 Connection Illegal Connection Al This had to be done, did not do it, after doing this here, it has finally become ours, what will we do, will we return Lootkand, I have already connected this Our work was to say connection, so we have connected, what will happen to you after connecting, if you press the button finally, this will happen. Okay, now I will see for the second example, for the sake of example, you will see, so what is there here? There will be this tap, this next, we need this next, this is the tap, ok, connect this, six, Kunwar International, now look, open it, next seven connect 3031 next, do this, now let's give an example, what will we do here, okay, if we use it here, then I Why will we use end and I have told my father that level rise is going to connect us all, we will do this at level 5840 and whatever we will do from here, we will do it from the right side. Okay, so what will you do first, you will make eight on this side, add. Apart from this, there is no one else, okay, so what will we do first, we will start from here, we will take the previous, from here we will take reverse will be your tap and top here, what will you do, top element, what will you do, you will take at, now we will see. That the next one is going to be reduced i.e. the next stop of the stop will be reduced i.e. the next stop of the stop will be reduced i.e. the next stop of the stop will be prevented equal to or what we will do is see whether the top is the middle point, is its right toe left side, will the right side destroy the tent and insult the extra one? Then what are we going to do, what happened here, we cannot update the previous one because in this level and in this phase of honey one and this is the limit, isn't it? The add technology that we have here is that this is the add of the second level. This is the second level, this level has no more elements, so we will not do anything here, it has been connected here, what will we do after the connection, again enter our taste of tap, this and what in the top elements case. Your pen is going to happen, okay, this is going to happen, so what will we do now, we are going to try to topped in the next minute and connect, it is not going to happen, we also want that, then what will we do here, whatever your right left of the tank. You will be able to use the same channels of protein in your diet, now you are making another one here, voting sir, is there anyone in his life, otherwise he will let you stay, he will not get torn, okay eat, what are you going to do after that, look, see what this is, this dandruff collect. You have already done it, you will make arrangements here, the previous one is your top, it will go to her hips, it will be done in the tank, thank you all, now what you have to do is write here, the tank is done, now we will change the top, we have just updated their effort here. Can do top Apart from this is done, it will take three inches, so what will we do now Top is done here, so now what will we do, if there is a stone from the top, what to do, then you start here to do Will subscribe, okay, we will start again, we will do left side and then right side, after that 1622, this is your third level plug is ready, what is there in the level till now, its weight is only 600, so this is what we need, now for this I Will start the same process will do the project Any previous people is your A and there will be a chart of top institutions then it is protein, it is ok cotton, this is what you will do, you will exchange the top, we will be the tap on the lifting connection, along with updating the environment, prevent. Updated, what will you do, we will take out the photo, okay, then for voting, we will see if there is any left, right side, if there is a left side, then you blur it here, after setting the sentence, what will you do now, it is here. I have paid important from here, six will be okay, so when are you going to get well, so papa, if you are going to be okay, then six will be connected, what will be the previous or recording audio, there not only their tips got connected, now what will we update the entry or Can't open, we will open it. Okay, we will open it. Now, what is there after that, let's see the fiction. Is there a right or left side, where is it thrust ? ? ? 464, so this is your fourth level is ready, is n't it is ready again for the fuel of last week. You have to search by one click, it is not ready, there is a left and right side, so you will see, here I have cotton here, this will come here, so please inspect it must be education, this has become current, this is what we need, that. Should have been specific Next point 56001 Not Connected 66 Will have to be null This should also be done Now this is done This level is done Now we will add to this We will take this to the end here Otherwise it is ready here too It is done, now we connect on it is here and we will take the top crop element of that level 3131, then what will we do, we will collect thirteen from the environment, keep the settings connected again, Anil Sadan's National, what should I do now by updating the previous Whose quercetin will you open and give, then what will you do? You will see on 30th, is there any left and right side, is there no Sachin's fight going on, so there will be no low level here, there will be no extra for this, then what will we do from here. We will put the body, look at the seventh rice, this clothes and environment will be topped on the server, will only 3990 become seventh connect Khatik Sachin, then what will we do by updating this, what will we do, we will remove it otherwise we will open yours, it is consumed ok What stops me again is the fact that there is no ginger and idea, there will be a level for it, otherwise what we will do is put it, from here we will see the pen of the phone, apart from supporting the laptop, will it be previous or not, will it be P7, it is consumed. So what if they update the default or entry for equal, because if you are limited, nothing will happen to us, but it has become ours, by supporting the scientists, to entertain everyone and tap that next tap, this is what we had to do, right? By folding 1763 Under International, this was yours, so what are you returning the level to, changing the level voice, we will also change the level in your record too, now what will we do, first of all we will do the second one, then we will adapt to the form. If it is not * then adapt to the form. If it is not * then adapt to the form. If it is not * then we will make it general then why will we take it because the type which will be date of Lord is not of type, first we will set the routine i.e. if Vansh is called then it will be done set the routine i.e. if Vansh is called then it will be done set the routine i.e. if Vansh is called then it will be done as per the example for the example that we will check here viral It is suitable, till the time I don't get entry in Kyun, we will do it, okay, we will take a friend or if we don't ask, then the size is of that level, it is ours, okay, so first of all, thanks Pawan, we will get the size, what will we do now, as long as it is one size. What operation do you have to perform? If not, then we go here. Import the level wise. As long as it is our size, we are performing this operation. Ride, so share it here. We follow you. You are using Jio. We will do these points from the beginning till the end, whatever the mother operation will be, we will perform it. Okay, so stop animal here because we have taken the front, we will turn off the hotspot, then what will we do, from the top, we will remove the previous and reverse, we have taken it here. We have level wine, otherwise we keep changing the channel, otherwise we keep updating the side, so what we will do here is consume it will become channel, then call welcome top key for any one, then we will check whether the top is right or left. Is it there? If so, why will I ask you and will you give it for free? Okay, after that, if you follow this, you will not follow it, because your size was the first, why did you look at the elements of one, then this band will form only one time. But why would I have pushed two and three to have a wedding in Luton, okay then we will come here because I am not anti, two is three, it is light weight, in that size will be found in two after going to America and what prevention have been done here. We have not fought, then we have already done the guide channel, then here we will get this potato twice, ok, first what will we do, from here on three, it will be on top because we will silencer it again, balance the right and the left later. Reddy will be the silencer, then your two will be inserted, here you will remove the free, but what will you do on the next one, basic scientific reverse, you will get the channel here, so add, the abstraction we were doing, this is what is happening inside our for loop, okay. Along with this, we are also preparing the next level here, OK, this is ours, finally, what will we do, when we have completely connected, after doing the next point, OK, then we can finally connect Rudrapur and * Let's finally connect Rudrapur and * Let's finally connect Rudrapur and * Let's do this, not the code. It's time to give flowers. It's time to thank you.
Populating Next Right Pointers in Each Node II
populating-next-right-pointers-in-each-node-ii
Given a binary tree struct Node { int val; Node \*left; Node \*right; Node \*next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`. Initially, all next pointers are set to `NULL`. **Example 1:** **Input:** root = \[1,2,3,4,5,null,7\] **Output:** \[1,#,2,3,#,4,5,7,#\] **Explanation:** Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 6000]`. * `-100 <= Node.val <= 100` **Follow-up:** * You may only use constant extra space. * The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
null
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
116
752
okay all right guys welcome to our channel code with sunny and in this video i will be again talking about the good problems of the lead code and the today our problem name is open the lock and the index number is 752 and the problem is of medium type problem delete code okay so actually i'm making this video after very long time since i were quite busy uh i think i should have to do one thing uh if you haven't subscribed to our channel yet i will recommend to subscribe it since we are reaching a threshold of you can see a thousands of subscribers and we need your support so for supporting us for supporting code with sunny either you can donate to these credentials you can see over here or you can at least subscribe to our channel or share our videos like our videos and all that stuff okay hi everyone this is welcome to my channel today i'm going to discuss the problem your support so that you could become more reachable to those codeds that are still uh requiring the concepts and is still requiring the correct ideas to solve our problems okay so talking about this problem now open the law okay so index number is 752 as i've already now we have a lock in front of us containing four circular wheels and each wheel has ten slots zero one two three up to nine and uh there's a lock that is going to start at zero that is this one okay and representing the state of four wheels that is the first character is denoting the first state of the wheel second third fourth that is the state of the four wheels and we have been given a list of dead ends and dead ends list is basically signifying that this state of wheel should not be reached suppose darien's vector contains a string like zero one two and four it means that the wheel should not reach this state and this state should be prohibited okay and okay so meaning if the log displays any one of these codes the wheels of the lock will stop turning and you will be unable to open it okay given a target value target string representing the value of the wheels that will unlock the lock it means that there is a should be a given a target string that will unlock this wheel okay and when it will be unlocked when i will reach the target string and return the minimum total number of turns required to open the lock or minus one if it is impossible okay so we need to return the what is the minimum number of turns okay so it means that if we are at state let's say zero that means this is the current state of the wheel and let's say this is the target string and we need to find it out what is the minimum number of moves so that i can transform this string to this string that is this is the source string and this is the target string minimum number of moves to transform the source string to this target string such that in the all the possible states in between we should not reach a dead industry let me write it down dead end state if you're not understanding this dead end state let me explain this in much more simpler words okay so let me first erase this whole stuff and the simpler statement is suppose my initial statement that is my initial source string is this one let's say denote it as s and i need to figure it out the target string that is i need to reach a state called target string zero two and let's say this is st it means that we need to convert my source string to this target string in the minimum number of moves okay i think i should have forgotten what is the type of moves that we have to do okay the type of moves that we have to do is suppose the ith character of my string is whose numerical value is 9 i need to increment this 9 to its next position and what is that next position it is 10 but you can easily see the wheels should have the 10 slots between 0 to 9 and then the next value of 9 would be not 10 it should be like 0 so let me erase this 10 and let me place a 0 over here okay so in other words what is the next value of zero it should be one next value of one it should be two and so on and when it reaches to nine that is so on when it reaches to nine the next value of nine would become zero it means it is a circular pattern that we need to follow that is the next slot of a particular number would be like n plus 1 and when n plus 1 reaches the value of 10 i need to consider n plus 1 as 0 and similarly the previous slot of the wheels should be like 1 once previous would be 0 and 0's previous should be 9 this should be taken care of that okay so this was the explanation of the moves now talking about the minimum number of moves okay this is the minimum we need to figure it out what is the minimum number of moves we have to do to the reach this state now let us consider the dead end state vector that is the sequence of strings that would be given to us where the when we are transforming my source string to this target string that particular state should not be reached okay so let us consider we have only a single string in our data dead industry vector and this is the particular string and this is my source string and you need to consider it to zero two now okay we will work upon by picking a specific character you can easily see first three characters already match we need not to consider for that for now we need to consider to transform this zero to this two so i will make a string like triple zero one but you can easily see this string is already in dead industry vector so this is the state of the will should not be reached we need to avoid that and how we can avoid that just try to find out the different state rather than this state okay so how can we find out a different state rather than this state would be like we are not going to transform this to triple zero one we will transform it to double zero then one and then single zero then i will again transform this to double zero one okay so this is the first next string this would be the next string that is firstly i have transformed for the this character then i have transformed for this character then i will just decrement my third character that is third character this one it would become zero again one okay and if this reaches one i will just transform this triple zero one to its next state but can this be a valid state no this is not a valid state because you have reached again another state whose string is already present in this dead end vector so here arises another exception we should not have to reach to certain state or certain state of the wheel whose string representation is already present in dead end vector okay then how we can do that okay so no need to worry about let me explain in much more simpler words okay so let me raise this stuff okay now uh you should have to memorize that i have a dead end vector which have a string like triple zero one okay that is this string i need to avoid this state okay so how i can transform that let's say i'm transforming this triple zero and that is four times zero to a state called zero one zero in one moves okay then again i will transform this string to another state and what is that another state triple zero uh not triple zero uh double zero one then again i will transform this to the double zero one two now you can easily see i can transform this again back to this state like uh double zero or triple zero this one or two i think that is already two in one step i can remove or i can change any character of the string to the next or previous okay now talking about the sequence of moves you can easily see this string is not present in my dead invector and this string is also not present as well as this string is also not present so this gives us the idea that these sequence of strings are not present and what is the number of moves in one move second move third move four move so we require four moves to transform this string four times zero so this is three times zero and two and this is the target string and this is the source string so my answer comes out to be 4 but this can be the minimum answer i don't know so this can be the minimum we need to find out the minimum answers okay so now this is the sequence of step that you should follow that every state of the will should not be present in the dead end vector and if there are not a sequence of step to reach the target string we need to return minus one in that case okay so talking about the approach now let's move further to understand how we can approach this problem with the help of certain graph theory concepts like depth first search or breadth first search okay so let's move for that okay so talking about the approach so i think i've forgotten to mention the talking about the constraints also so i've forgotten to do that the dead end's length is 500 so we can have a brute force type approach and the target dot length is always 4 so there would be like a string of maximum string would be like 4 times 9 and if you consider the numerical value of 4 times 9 it will come around to be from 0 to 4 times 9 would be like 10 power 4 okay so we can have a brute force solution to find the minimum number of moves and target will not be in the list of dead ends also and target and errors consist of the digits one this can be helpful but now let us move further to understand this with the help of steps approach now you can see we have a source string and we have a target string and we need to find the minimum number of moves now consider this as the problem of graph theory finding the uh okay so in other words let us say what is the minimum number of steps minimum number of moves to go from a source node to this target node in a graph let's say we have a graph like uh this one and this one we have a graph like this one let's call it as a directed graph okay and we need to find what is the minimum number of moves to reach from this source string to this target string and so it could be like try to traverse try to have a breadth first search starting from the source string to the target string and find out the level of this target string with respect to the source string okay you can easily see here it comes out to be one two so the target string is at level equal to two uh with respect to source string and this is the minimum number of moves actually so it means that you need to transform your source string to this target string uh in the minimum number of moves and this can be easily done with the help of breadth first search that is start traversing from the source string to this target string now comes the main thing what should be the directed edge okay so directed edge would be like consider string you have like a triple four times zero and another string like zero uh zero one and another string like zero 0 9 and another string like 0 9 0 now this is the actual source string and for this source string all the other three strings that i have mentioned are adjacent to this string so there would be a node directed edge from this string to this string and this string to this string also okay now there are total eight possible directed edge starting from a particular node okay eight for eight forty eight possible edges why i am seeing eight possible edges it would be like uh for every character there are maximum four characters in a string and for every character i can just increment a character to its next position or i can decrement the character to its previous position so there are eight possible different states that is the next nodes and the next nodes for a particular node and there would be eight directed edges so you need to consider all the directed edges now there would be also like uh on certain nodes where you should not have to go like this node is present in the dead ins vector so this node should not be traversed you need to take care for that so you need to just eliminate that condition that is whenever i reached a certain node that already consists of dead ends vector you need to just not to consider that and then find the minimum level of this target string with respect to source string and that is your answer and if it could not be reached you need to return -1 in that case okay you need to return -1 in that case okay you need to return -1 in that case okay so let us try to understand this in a more deeper way with the help of code and how to consider this as a problem graph theory and all that okay so let's move further okay so talking about the code i've already some submitted some codes okay you can see first i've gotten the wrong answer because i have mixed one corner case now i've got accepted but runtime is very bad one eight zero ms then i try to optimize my code further then i got 240 then i got 128 finally and this is good i think okay we're talking about the code okay let us talk about over here okay so you can easily see i've taken uh okay a set basically a set uh hash set where you can store all the uh integral value of the strings like we have the string like triple zero then one then i will store one because there would be like a maximum of the strings count would be like uh the length is four and uh in worst case would be like four times nine so i will take like four times nine then i will take exactly four times and if i will take like a string is like this state okay so if the string is like zero two three then i will take 23 because this is the value that i want okay so i will take a q and this is used for the breadth first search then i will push out the zero because i need to start from a string having the characters like four times zero and the initial level is zero i need to reach the target string and minimum number of moves would be like a level of target string with the with respect to source string so i have taken a visited vector also vis of zero is true and start traversing in the breadth first search manner and take out the initial string and the initial level of the current state and now if that string that value is already present in my dead end vector and not to go further with this value okay so i will use the continue statement and also if i reach the target note that i've used hty function which converts a string into this numerical value and if my value v is reached over the target i will return the level that is yes i have found the string right now note that i have used the queue you can use a dikstra algorithm also but i don't prefer to use the dextra algorithm in such case where the my graph is the weighted graph where every edge is exactly one every edge weight is exactly equal to one you need to consider the extra algorithm when the edge of it is can be greater than or equal to one then you can consider the extra algorithm but here every edit is exactly equal to 1 i will consider the q based approach which will also give us the correct answer now i will take my current string would be like 4 times 0 plus this value i have done this because so you need to consider this extra zeros uh leading zeros like you have the value 23 then you need to figure it out like this zero two three then only you can change the every state of the character to its previous or to its next and then find out the next value of string so this entire thing is going to do that as what i have said now okay so start i tweeting four times and this four times is because consider every character and find out the my current value of the character then find out its next value and find out its previous value note that i have considered next and previous with the help of this ternary condition like nums is nine then my previous should be zero otherwise that is my next should be zero and otherwise my next is num plus one and similarly in the case of previous also now s1 is current ns2 is also current and s1 of j would be like this value and h2 j would be like this value that is my next string and previous string respectively now is if my value that is s1 and s2 that is my next and previous for every state of the character is not visited then i will push into the queue and perform the breadth first search respectively like in the sequence of manage and you are already aware of that if you have if you know the slightly concept of breadth first search finding the levels of a node with respect to source node you can easily understand all these steps okay so if that state is not reached v is not equal to h2f target any time that is it doesn't happen that my source string can reach to a target string like in through any of the paths then this entire queue will be executed and finally we will return -1 as your answer return -1 as your answer return -1 as your answer so this is the entire code so if you have any doubts do let me know in the comment section of the video and i will ask you guys to join our telegram channel subscribe to our videos and channels and share our videos and okay thank you for watching this video
Open the Lock
ip-to-cidr
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: `'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'`. The wheels can rotate freely and wrap around: for example we can turn `'9'` to be `'0'`, or `'0'` to be `'9'`. Each move consists of turning one wheel one slot. The lock initially starts at `'0000'`, a string representing the state of the 4 wheels. You are given a list of `deadends` dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. Given a `target` representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible. **Example 1:** **Input:** deadends = \[ "0201 ", "0101 ", "0102 ", "1212 ", "2002 "\], target = "0202 " **Output:** 6 **Explanation:** A sequence of valid moves would be "0000 " -> "1000 " -> "1100 " -> "1200 " -> "1201 " -> "1202 " -> "0202 ". Note that a sequence like "0000 " -> "0001 " -> "0002 " -> "0102 " -> "0202 " would be invalid, because the wheels of the lock become stuck after the display becomes the dead end "0102 ". **Example 2:** **Input:** deadends = \[ "8888 "\], target = "0009 " **Output:** 1 **Explanation:** We can turn the last wheel in reverse to move from "0000 " -> "0009 ". **Example 3:** **Input:** deadends = \[ "8887 ", "8889 ", "8878 ", "8898 ", "8788 ", "8988 ", "7888 ", "9888 "\], target = "8888 " **Output:** -1 **Explanation:** We cannot reach the target without getting stuck. **Constraints:** * `1 <= deadends.length <= 500` * `deadends[i].length == 4` * `target.length == 4` * target **will not be** in the list `deadends`. * `target` and `deadends[i]` consist of digits only.
Convert the ip addresses to and from (long) integers. You want to know what is the most addresses you can put in this block starting from the "start" ip, up to n. It is the smallest between the lowest bit of start and the highest bit of n. Then, repeat this process with a new start and n.
String,Bit Manipulation
Medium
93,468
43
Ok gas so today we will see multiply stream so this is what we have 2 inches and we have to return we have to produce the product which will also represent Naman so we have two problems if we look at us one problem is that whatever name first The name you are asking for, first we have to convert it into integer, then we have to get its product, after that again we have to convert the string, after that we have to return, it takes the integer and converts it. Here we are waiting for the big integers. Big will wait for that, what does Big interior actually take the input? If we write Big integers equal tu new big sorry you also gintijar equal tu input stream which gives value hot see so here we have this in the string. If we do it with the method, then here we will take the first testing and we will take the second testing and will number it as OK and this will be the input we need in one place. If we want to take it in the output, then what will we do again, whatever will be the value, now we will multiply it by me, then we got the result, because we want the result, then what we have to do with the result is to convert it into a string, then we will write the string result in this. We will do it and return it in the last, does it have or not? There will be capitals in both the places, the question is whether it is passing or not. The first problem was that we had to convert from sting to wait, which we did with big integers and then we wait. Then we converted it to Steam, the only meaning was that if we have to convert a lot of things which are not mentioned here, which are not actually mentioned in the description, then we cannot do that with normal integers.
Multiply Strings
multiply-strings
Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string. **Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly. **Example 1:** **Input:** num1 = "2", num2 = "3" **Output:** "6" **Example 2:** **Input:** num1 = "123", num2 = "456" **Output:** "56088" **Constraints:** * `1 <= num1.length, num2.length <= 200` * `num1` and `num2` consist of digits only. * Both `num1` and `num2` do not contain any leading zero, except the number `0` itself.
null
Math,String,Simulation
Medium
2,66,67,415
925
hello everyone so in this video let us talk about one more easy problem from lead code the problem name is Long pressed name okay so you're given that your friend who is typing his name into a keyboard sometimes when we are typing a character C they type that particular key and it might get hold for a pretty long amount of time and thus that particular character is typed more than one time okay now your like your question is to examine that you are given the tight characters that it what it is actually typed and you are also given that what is the name that I want to write okay so because the friend is adding a name and there's also a typed character like what is what he actually typed out you just have to tell that whether this type is actually inferred from this name or this is actually wrong in simple terms whether let's say that this is Alex and this is a l e x so what you are actually trying to say is that maybe when he's trying to write on Alex he has pressed a long time and it has make a two times then L is type 1 again then he might when he's typing e he might have pressed e a little longer so that 2 times e is pressed and then X it is perfect so you have got this type but it is inferring from this Alex that is fine but let's let if you find out this what you can see is that the name is s-a-e-d okay now what you can name is s-a-e-d okay now what you can name is s-a-e-d okay now what you can see is that s when you write an S we might have pressed s pretty long so it is coming out as a student then when he is typing a is type pretty long so it has come two times okay then he might be pressing e then he pressed e gave his only one e but then here again press D but there is no more e again hope you get the point what is trying to say here is that the words in this name should be there but it can happen that it might be pressed too long so that there are multiple occurrences but it cannot it should not be happening that if there are two e's here that it had been two e's but there is only one e that is wrong okay so that is how you have to check it out so the very simple observation which I comes by just seeing is that for every word what I can do is I have in the typed sentence I will have to shrink it okay by shrink it what I mean by this is I have to somehow get it to the very smallest that if I typing out this name what is the character and its occurrence so a and how much it is typed L how much types e how much it is type so because it is it should be typed let's say two times but it is typed five times which means that it is long pressed so I have to somehow get how much long press this e should like it is long press two let's say I want two e's and I've got five fees that is fine but if I want two e's and I only get one is then it is bad so I should be getting a frequency of every of this character in the particular order so uh and the name as well in type sentence and I just compare them out okay that whether I can like the frequency of the word in this typed name should be greater than or equal to the frequency of the character in this actual name and in the same order as well nothing much here to be uh thought about here that is one of the code path so that it will become more creative nothing much difficult as of now so what I've done is that I have written a convert function this convert function will shorten the string by checking that what all are a continuous segment of characters are there and shortening them into one character and also writing down how much time it has occurred what I mean by this is let's say this a l e x is converted to this function to Alex only but how much time a has occurred two times how much time L has occurred one time how much time e has occurs two times x is a good one time so this particular string is converted to this format this new string with the frequency of how much characters it has occurred on okay so let's say a has occurred two times L is one time here second two times x is one time so I have let's say like uh shrinking the knowledge of the string into a smaller information so that it can be used for matching out the typed string and the accusing there are multiple options or multiple approaches to solve this problem out but I have thought to use this so I've used this convert function to convert this particular string into a pair of string the actual modified string and objector which throws out the occurrence of those characters at a particular instance so I will tell you how this convert function will work but I will get these two strings so let's say I have these two things so s AED so let's take this example only so my first thing was s a e d and the next string was s a e d so this string will be converted to s a e d only one occurrence of those characters followed by their okay like how much time it has occurred so in the original string so it has okay one time a has occurred one time e has occurred two times and D has occurred one time so this is the short form of the first string that I want the name strength now I'll use the same function to convert the short form of this string as well so it will be also converted to s a e d but s should be occurred two times e like a should be a two times e 1 times and D two times now what you can observe is that I actually want this string but I got this string so from this string if I want to backtrack to this string what I want is that every character in this string should be greater than or equal to this numbers because then only I can backtrack to this because let's say if I have two s's and I want One S I can just delete out so if this is more this number is more than it is fine but if it is less I cannot backtrack to the original string that I want so if this is 2 is greater than this number that is fine 2 is greater than this number that's fine one is more than this number that is wrong because I have only one e here but I want two e's that is false so I can directly get out what is the contradiction and act in this thing so what we have done is that if the two strings that we have formed after conversion this SC 80 and scad if they are not same then it is already bad string because I have shortened them to most smallest form these two strings should be same if they are not same then it is already bad okay because then uh Whatever frequency they might be having but the character should be same now so if they're not same then answer is already false that they should not be converted back to this original string if they're same we will iterate over any of these strings okay because if they are same we'll check that if the ith character on the first thing and second string are same they will always be remaining same you can just remove up this condition as well okay but what I'll do is that in the second so name data okay so there is name data and the type data so the actual name String so if the name String okay that I've won if it is less than the type data okay so we have tied with this string it has more frequency then it is fine because then we can just go around we can just delete out some characters from this type data to get the name data so if this is part is larger then or larger than equal to this nine name data we just continue what we will keep on doing it but if it is smaller then we just return false that this is bad and if this follow-up this is bad and if this follow-up this is bad and if this follow-up continuously we move around without hitting this false condition and answers too because for every character in The typed data the frequency is larger so from the which I want in the name data so I can just print now all this convert function work what we'll do is that we just rated over this whole string Wonder one and we just make a vector of count of how much time a particular character is counted like occurred we just initialize with one and just check that whether a particular character is equal so we want to build an answer Vector as well okay so let's say answer string so what I'll do is that I'll just take the current character that is a let's say in this is typing a and I just push that in the answer character and just check that whether the next cat is also equal to the answer the last character if that's say which means that they are continuously building out so let's say I have how this convert function is working well let's just check it out in a very small manner uh it will let's say I have a string that is a s t Okay I have to build a shortened form of the string so I will first push a inside the string that is a that should be building out if you want to put the next word that is also a then it is bad because I want only single occurring so I will not enter a word that is equal to last character that we have just inserted so I'll just make it I will not insert it but because it is same I will increment the frequency that it has occurred two times maybe it has gone three times but when I want to insert s then which means that this particular segment is free like finished and then I will insert the next getter and start counting out how much time this character is I want to insert in the back but that is already present so I will increment the count okay and thus I will get the count as well as the unique words so I will just push back if they are not same I will just increment so what I'll do is that if the last getter that is already present in the answer string is not equal to the string over factor I want to insert that I will just insert that make my total one because I want to start a new segment and I just want to make my uh answer push that in a new character and the count is also pushed because the particular frequency of how much that particular character is stored storage count or else we'll just increase my total that this is forming a continuous stretch of words or a segment of the same type uh words of same type A so which is an increment by total in the end we have a total string that is a new uh string that is only thing of fingering like only have the words of single time as well as the count of those stored in Vector as a count Vector so that's it you can also pause this video and try to see over this convert function how this actually rotate over the whole string and just convert the string into the shortest form with the frequencies in this table lateral logic and the good part for this particular problem I love to see your code as well in the description of this particular video you can share it out with me because if I do multiple approaches to solve this problem out so that's your logic and the good part from my side for this particular problem if you still have a doubts you can mention in the comment box of this particular problem thank you for your video to the end I will see you in the next interview fooding and bye
Long Pressed Name
construct-binary-tree-from-preorder-and-postorder-traversal
Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times. You examine the `typed` characters of the keyboard. Return `True` if it is possible that it was your friends name, with some characters (possibly none) being long pressed. **Example 1:** **Input:** name = "alex ", typed = "aaleex " **Output:** true **Explanation:** 'a' and 'e' in 'alex' were long pressed. **Example 2:** **Input:** name = "saeed ", typed = "ssaaedd " **Output:** false **Explanation:** 'e' must have been pressed twice, but it was not in the typed output. **Constraints:** * `1 <= name.length, typed.length <= 1000` * `name` and `typed` consist of only lowercase English letters.
null
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
Medium
null
1,897
Hello friends welcome to my channel here solv code problems and prepared to the Cod interview today's problem number 18 97 redistribute characters to make all strings equal you given an array of strings words zero indexed in one operation pick two distinct indexes I and J their wordss of I is a nonempty sing and move any character from word I to any position of words J WR true if you can make everything in words equal using any number of operation and false overwise let's do it what can we do first thing I uh I think it should work we can calculate total number of appearance each character in all strings and check it's each number of occurrences divided by number of strings so let's do it first of all we need to count number of words so let's create variable n equals to L of whats El we need a dictionary for count characters count let's use function default dict if argument int it's helpful function it return zero if chars doesn't have some value by uh okay let's check each word in words and each character in each word for Char in what and increment number now we have a dictionary view of number of occurrences each characters now we need to check count because CH dot values we need to check numbers without um not characters but only numbers so I use here fun method values which return only values of dictionary and if count modul n doesn't equals to zero false otherwise true that's all solution let's check test it works let's submited yes it also works it's quite simple and U beautiful solution so that's it for today thanks for watching see you tomorrow bye
Redistribute Characters to Make All Strings Equal
maximize-palindrome-length-from-subsequences
You are given an array of strings `words` (**0-indexed**). In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`. Return `true` _if you can make **every** string in_ `words` _**equal** using **any** number of operations_, _and_ `false` _otherwise_. **Example 1:** **Input:** words = \[ "abc ", "aabc ", "bc "\] **Output:** true **Explanation:** Move the first 'a' in `words[1] to the front of words[2], to make` `words[1]` = "abc " and words\[2\] = "abc ". All the strings are now equal to "abc ", so return `true`. **Example 2:** **Input:** words = \[ "ab ", "a "\] **Output:** false **Explanation:** It is impossible to make all the strings equal using the operation. **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 100` * `words[i]` consists of lowercase English letters.
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subsequences are non-empty.
String,Dynamic Programming
Hard
516
729
Hello friends to Jhal Ajay, welcome all of you to my YouTube channel Tier-3, in today's my YouTube channel Tier-3, in today's my YouTube channel Tier-3, in today's video there is a new question in the to-do list video there is a new question in the to-do list video there is a new question in the to-do list named MyCalendar First Design and Design Question. This is a design middle question and in a way we have to If you want to design a calendar, then let's see the question. The question says that you have to implement program to this calendar. Special new event and diet will not be possible booking. So basically what is the booking. What is the booking that as if someone is already there is a meeting time from two o'clock. There is a meeting in the evening for 5 minutes, only he comes and in that there are three to four because you cannot attend two to three to four meetings, so we will not do that, you have to call at that time that this is not possible and if If this does n't happen, then it is disgusting for us to do it, so how do you design it, we have many methods of doing this, we simple means in that city, hmm, another means, we can organize an event in the list and check and hydration is applied- By assuming that A and hydration is applied- By assuming that A and hydration is applied- By assuming that A is this Uber app with events or not, then that is also a B but I will get it done today, with the help of binary search tree, let's type some BST and let's see how it will work, so let's see now like I say this, first let's understand the noble typing what is a notification like let's say one event and with help there is five, okay two to five, this is an event which I have added in the calendar, if a new event is coming, then by insulting it. First I have to check whether I have any other event that overlaps with it, then how are the people of some overlap? Keep that in mind because they will be required in the implementation. What are the overlap cases like if there is an upcoming event of theirs? Starting point and end intimidation, reply, this is exactly overlapped, this is 125, in this case also we cannot add them, then how do we make it so that the person who is liking our upcoming events has between 2 to 5. Our false case has happened, what has happened is that our starting time of the event is fighting between this and the ending is equal to this or the pending is more than this, in both these cases also we cannot make it even tight because look, believe it or not, this one My time is 3 o'clock so I will come to the solitaire meeting so I can't add this lemon juice then see this cornflour from this point on the left then where is a pass that the starting time was at 1 o'clock but the ending time was somewhere at 2 o'clock And that means it can vary, I am showing a general eye that it can also be done like this from Indore, here I have shown in two to five that the overlapping will be like this, okay so it can also be like this that the starting first. It is done but the ending is saying so it is around this time so this is the case exactly so there is no point in writing it but there is a little bit of this attitude of one in it just keep in mind that if the time is earlier and the ending is The time was 2 o'clock, so this is some kind of fruit or cement, it is a treatment, because look, if I have one meeting instead of theirs, then he will be lost, because after having 1 to 2 meetings, I will go and sit in the meeting at 2 o'clock. If there is no problem, then we will take this storm, keep it in the room, then I will do this case, the rest is to make as many backgrounds as possible, all these diagrams will represent our force, share it as a force, starting here, the whole meaning of such a big whole starts at one o'clock. When it ends at 6:00, he cannot it ends at 6:00, he cannot it ends at 6:00, he cannot attend because in two to five Bullet meetings, these are some false cases. Now we keep a figure aside which will be useful to us, so when we will do the infection. While checking, I keep it aside. Now let's talk about how to do this question. So what do we do? Let's understand that initially there will be some event, then after entering, Late Sports 11 is an event of time only. They reject it, there will be no problem, next is ok, the event is coming, I have got it done, of course, let's check once that there is no typing going on, I got it done right, then we got it done, then we got it checked, if one is right. Okay, if it does n't fit then it will be returned to the Play Store for not sitting. Now I am seated, okay sir, if it will be added then how will I add it, that is, because I am a binary search tree, because look, if a new event comes to me, its starting time. If what is its starting time or its Indian time, that means I will keep shopping for the end of the new event that comes, this old dysentery Yadav, Manoj, who is Nayanthara, she is ad ash and wide, then what should be the new event that is coming because I will keep it so that all of them will be big meaning they will start in the current events and if this dish is not there then it will mean on the left side and what will be my tab in this case is that in this case my wide S land will be inhabited then this I have O, seeing this we can generate BST, so now let's see in this we will simply do it like this and keep checking every time, if it is on the right side then we will put more towards the right side, if it is on the left side then towards the left side and one more. So what do we say now, that's it, now we have to keep the fat recursively, meaning look, we have to keep the binary search tree in any way, if the laser beam had not been made bad, then we keep the fat recursively, what do we believe that R will become the right side. It will also be made, how it will be made, it has nothing to do with us, just the left side of ours will be made inside, the life will be made, so when the notes from both the restaurants go to us, we will simply attach this with this, so come. Yes, this thing is clear, okay, this is the section on how the infection will happen and now if I talk about deletion, feel a little ashamed of me, while checking, we will just keep this condition in mind that if all these things come, if any such thing comes, then for If you have to return, you will get it checked in another way, meaning by following the current events in your career, just like Italy has become, suppose this is a tree, descended from this type, it has become mine and now the current comes, some event, current events came, I got dizzy with it. Now if I talk about mixing the time then it is Login because see if this event comes new one I will check whether its Indian time like I told you what is wide s what is widest no the brightness of the event has increased current feel this means that Where will all those events go? Like all those events on the right side. This is a trick, so there is no need to check with the people on the left side. Go to the right and compare with this note. Then go to the right and left. With this note, go to the comparison of life and If we reach such a place that there is no overlapping left, then the simple thing is that we can insert even toe, which is the trick, I hope it will be clear to you that how to do infection and how to check. If you want to handle it, now once again turning towards our according lesson, so first of all what do we have for the coding lesson, we have one now, so we have to design these, we will make a note because in the note, we will cut it and keep a left side pointer one. Right side point, both note type, experiment note, someone will point, although go, I cannot say point, I can say reference, both of them came to me and one to me, son's, what to do for your data, I have to give my data to my Either I join a separate class or what can I do, I create one on it or I take an internet ID, so what to do, we take independence in this, which size, yes, son's name data will be cut now. Note, you can do this and in this we are initially starting point, this point and ending point or to data is equal to new DJ type to dosa, this data of 80 starting point echo point, we will make the left side is null and the right side is also below. After writing, I have seen that if I send a voice mail, the design of the note is done, I will join the class now, I will ignore the type, I will do the fruit, there is no need for potatoes, I am doing this for a customer named B, with the initial inside it, you will get angry, won't you? Trigono happened, right now let's take the infection. Type the note thank you, make that Lord Litton and see that tweet from the left side is done in Honda, the whole of the Akhilesh side has become the country, the whole of the right side has become the interior, set your current reminder. So what will be the interest? A tobo will take the note and the result, you mean the control that one will take this pregnant road route note and neither will give it, then one will take it by name, take it, then one will take it by name, now if we do something here through If the route is there i.e. the current route note is the route is there i.e. the current route note is the route is there i.e. the current route note is the people, it is simple, only a few came out, I returned the LED light bill, don't do anything, Kanodia will come, new event will come, everyone will cream, till the event came, if I have any booking, then that is my booking below. It will be routed in the opposite direction if they take the first team at the barrier at this time a note type of RTI take the winner for the right side Now what do we do like I said if the end points of the current events i.e. Widest if that greater comes to the i.e. Widest if that greater comes to the i.e. Widest if that greater comes to the vice of my route i.e. where do I have to vice of my route i.e. where do I have to vice of my route i.e. where do I have to go, to the right side then I want you to become right free, how will you become again, I made the night and became its two note age that it I collected the load in my man Tinwari Bal and gave it to the right and right side. There are only two options in the left site, I will have the dot go to the left, what should I do, if there is no left among the two, then I will go to my current one. I do left in the left side, I also check such side that if RGT is not null then I post RGT in r.br itself tasty post RGT in r.br itself tasty post RGT in r.br itself tasty and in the last I do return route and do that and above in the function was LED. Not coming to the obscenity will keep the bullion that if it is they can insert and note then it will loot a paint road coming and will take a controller and vaginal weight will be coming in the input here also the first case if there is a root tap that is not made yet If it is the first event, then you do it, my work is over, now I will make two Maggi breads from here, the person would pause it, initial and quantity of your gifts, that is, I will check left and right for free, that is, whether I can do the lieutenant, that is, what my new booking has come. I can cut it on the left side, I can go somewhere, I can do it at night, although I am going to college, but my work is just look at the two near me, if I have to, I will go towards the west, or towards the right, anywhere. You come from here to two, if two come from here, then this event of ₹ 1 can be added, so then this event of ₹ 1 can be added, so then this event of ₹ 1 can be added, so now we check something, now of course he would have seen this condition which is from the fall, the first condition and data i.e. That the starting point of my upcoming event is condition and data i.e. That the starting point of my upcoming event is equal to the cutting point of the data and the standing point of the current data is also equal to the encounter of Panda, then return forms, this is what overlapping condition I have done this, click on accept, this one. If it is, then I will implement it directly, I will not go into much detail in the explanation. If you have any idea how you can limit this overlapping condition score, then I don't have this time, I am writing quickly in Delhi, end data's zero friend request to data. 10. Jio phone model test of 1 to 2 data can also be seen by pausing the video to see that if I do the implementation then first I would advise you to make the entire interview in my notebook and see in which case it will spread. of your data that one scripters in art and data isi phone the president and your data ka vansh is this letter request you all to date 80 th should return forms a that in blouse how is this android data ka0 phone is lab assistant half gone invent Ki and data's lineage difference request uh here date 8th ki one scheme's return for less so send something, how did it happen, now it comes to tighten and toe the left side, so let's check what is the wide action heroine question. Was the admin point of the one who is white i.e. Justice has been Was the admin point of the one who is white i.e. Justice has been Was the admin point of the one who is white i.e. Justice has been venta, its sliding point, if the current is towards more than one person of the route, it means to do the right side effect, in that case of duty, ghost two take it to the right side, then you are daughter. After getting the GST side reduced on the right side and sent it, get the elective subject checked in the other wise and sent the dot left side online and in the last you should come with anything from both, relative and RGT. With this our method note class ends. Calendar is this Mukti and take fans like Pretty Priya Fruit tap the fruit initially and create a new entry using it, okay now it is done now in the booking, first of all I grease it from the root which is military, now there is confusion. I said, please, who is military, what should I do, who is my husband, what is his route, if he is on tap, then what do I have to do, treat route request to create a third, I will call the third. How far will it take for this, what form will it take, and will it not interfere, so new node 98 and end that it is done, OK, now the tree was empty, the case of the crotch is done, this case, when the woman was not empty, your toe land safely and see. That request came down dot check take the question take the root lake air pregnant note take a lesson mum and son that if chiffon was gone that pension return forms can not be added interest in other wise started return after minute I have done this company, family man got tensed, I was doing this series once to Ajay, okay, submit, okay, what has happened, that will be the solution for you, video player, if you get scolded by anyone in this, then you can comment section. Comment in and I will give you this device. Net first of all you have to do one thing of all the intervals. Take a notebook and see all the intervals in which it can be spread. Then you will easily understand the question. So with this Let's meet together in tomorrow's next video. Left leg video please comment channel subscribe my channel thank you.
My Calendar I
my-calendar-i
You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a **double booking**. A **double booking** happens when two events have some non-empty intersection (i.e., some moment is common to both events.). The event can be represented as a pair of integers `start` and `end` that represents a booking on the half-open interval `[start, end)`, the range of real numbers `x` such that `start <= x < end`. Implement the `MyCalendar` class: * `MyCalendar()` Initializes the calendar object. * `boolean book(int start, int end)` Returns `true` if the event can be added to the calendar successfully without causing a **double booking**. Otherwise, return `false` and do not add the event to the calendar. **Example 1:** **Input** \[ "MyCalendar ", "book ", "book ", "book "\] \[\[\], \[10, 20\], \[15, 25\], \[20, 30\]\] **Output** \[null, true, false, true\] **Explanation** MyCalendar myCalendar = new MyCalendar(); myCalendar.book(10, 20); // return True myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event. myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20. **Constraints:** * `0 <= start < end <= 109` * At most `1000` calls will be made to `book`.
Store the events as a sorted list of intervals. If none of the events conflict, then the new event can be added.
Design,Segment Tree,Ordered Set
Medium
731,732
946
hello everyone welcome to day 16th of march great code challenge and i hope all of you are having a great time the question that we have in today's validate stack sequences and the question itself says stacks so the approach that we will use to solve this question would be against tax to your surprise they've already solved this question in the month of february 2021 the comments speak for itself really help thank you for making this video and abhishek jain said this is lit i'm attaching the link of this video in the description below i just went through it i have clearly explained the approach in this video along with this i have walked through multiple test cases one for the positive scenario one for the negative one i hope you really enjoy watching it up also in case you like it please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates from coding decoded i'll see you tomorrow with another fresh question but till then good bye
Validate Stack Sequences
smallest-range-ii
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explanation:** We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 **Example 2:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\] **Output:** false **Explanation:** 1 cannot be popped before 2. **Constraints:** * `1 <= pushed.length <= 1000` * `0 <= pushed[i] <= 1000` * All the elements of `pushed` are **unique**. * `popped.length == pushed.length` * `popped` is a permutation of `pushed`.
null
Array,Math,Greedy,Sorting
Medium
null
206
hey there guys it's cooper codes today we're going to be looking at the problem reversal link list in this video i'm going to be going over the iterative approach to solving this problem we're going to start by looking at some of the basic linked list concepts assuming that you've had light experience in linked list or you know maybe a little bit more advanced we're going to make sure you understand the fundamental ideas behind how you end up solving this problem uh let's get into it alright guys let's get started so we have our link list one two three let's just make sure we understand how to traverse a linked list and kind of what it means to change the dot next property of each node in the list if we can understand this we can see some common pitfalls beginners make when approaching this problem so let's take a look at the node one for example so node one has a value of one and its dot next property is the node with the value of two and this is specifically the node that's like that's right there pretty much right in the middle of the list and so since it's that node we have to be very careful about changing that dot next property if we were to change this dot next property to instead of this node right here at the two right if we change it to none we're going to run into an issue because what that's pretty much doing is this arrow in our diagram signifies the dot next property right that means we wouldn't have an arrow anymore and so if we didn't save that node 2 that means we've lost access to the entire rest of the list it doesn't matter if your list is one more item or a thousand more items you've lost access to everything else and so that's a huge issue when dealing with linked list you really have to understand that changing the dot next property is huge because whenever you change a dot next property that means you could possibly be losing out on the entire rest of your linked list alright guys so i cleaned up our diagram just a little bit we're using the exact same link list right except i added a little arrow pointer to show where our head variable is it's important to remember that head means the first node in our linked list it doesn't mean anything else it's not a special node type it there's no like head node type of node it just means the first node in our linked list head node is super important imagine you wanted to go through your linked list twice right if you just use the head node it would look like this right you'd have your head variable right and you go ahead and then to get to the next node it would have to be head dot next right and so now our head arrow is pointing to here right and now we're at 2 so now head is equal to our note of 2 right and so now we can do 2 dot next so head dot next right and that's going to get us to 3 and then technically one thing i missed initially didn't show you guys kind of on purpose is three has a dot next property except it points to none right and that's super important because we know when head is equal to none that means we've reached the end of the list right and so one issue that i was kind of talking about before is if we wanted to loop through the list again we would kind of be screwed in this situation because we don't have access to the nodes behind us right that's a super important concept if we wanted to save our head we would have to make a saved head variable and set it equal to head so pretty much what we're doing is if we want to loop back right we need to save our head variable initially right so an example of what that would look like is let's just say you know i'll move this other stuff out the way let's just say we wanted to save it we can add in a little arrow here and we could just be calling it you know saved head right simple variable name and so if head moves forward it will move like this like we talked about before but saved head will stay in the same spot right and then for a great example of showing you how we could loop through it again we take head back right we pretty much take what i mean take head back what we're doing is we're saying head is equal to saved head the value of saved head and so that kind of is going to bring our head all the way back all right guys at this point in the video we've talked a little bit about various linkedin concepts but we haven't really got to the problem of reversing a linked list right so i think the great way to approach this problem especially if you're having trouble with it is let's draw out together an example of what the reversed linked list would look like so there's one way to do it let's just first we know that the if it's one two three the nodes are going to be three two one so let's just draw the circles three two one with no arrows so we can worry about the arrows in a second because the arrows are important remember the arrows in the diagram represent a dot next property in each node hopefully that makes sense so here we go so one two three is going to become a three two one because that's the reverse right and so now let's think about where are the nodes pointing to right let's see here so we kind of want the nodes to point like this right going to the right so 3 since it's going to be our head node super important that's why i decided 3 to be our first value here is because three is going to be the head node right if you set one as the head node and then pointed one pointing to two pointing to three you'll see that's exactly what our list on the top right here is and so now let's finish up our dot next here so the three point the two points to the one and the one points to the none so let's take a look at this right i think it's good to go node by node through our top example so let's look at the node one and see how it's changed initially the node one was pointing to node two right i'm looking right here right one is pointing to node two right but now one is pointing to none that's super important to understand one was pointing to node two now one is pointing to none right so that's like the first one right so look because we want to look at every single thing and how it's changed because i'm trying to bring you guys into the intuition and to just tell you the answer right all right so let's write down how each node has changed so before the one was pointing to 2. now the 1 is pointing to none right now let's take another look right at the 2 was pointing to 3. and when i say was i mean of the example on our top the original linked list we were given before the reversal right and so now two is pointing to one and if you're confused as to how i got two pointing to one is i'm taking a look at our bottom list right and i'm seeing where is the you know pointer going from to it's pretty much two's dot next property is going to one in our example on the bottom right and so now let's take a look at three in our initial example was pointing to none right now three is pointing to two hopefully these examples kind of make sense now i'm going to get into the pattern if you haven't already seen it and so there's a specific pattern here that i'm going to go into let's go through node by node our original link list right and so pretty much imagine there was a previous pointer node right this is going to help us the concept of previous pointers and like next pointers is super common in linked list questions so if you're ever confused as to how to approach something try and think about if a previous pointer could help you or if a next pointer could help you so we have a pointer that's going before the one and a pointer at the one the pointer at the one to be like our current pointer right and so originally what is that pointer well it would be none right because there's nothing there we would originally set it to none right now let's move these forward just one right so now our current pointer is going to move to two and now our previous pointer is going to move to 1. you might see what's happening here what is our previous pointer well it's 1 right now let's move forward again so our current pointer is going to go to 3 and our previous pointer is going to be a 2 right and so now let's just mark down what our previous pointer was our previous pointer is 2 right now here's what's going to happen our current pointer oh our current so our current pointer there we go technical difficulties uh our current pointer is now set to none so we're not going to move forward right now look at this we discovered a great pattern here our previous pointer was none one and two right look at this in our reversed linked list it was none one and two that's the idea and the concept behind reverse and linked list i haven't seen a lot of videos explain it this way so i'm hoping this kind of brings you to the intuition of actually finding that iterative solution right it's all about looking at the patterns and you know seeing what you can do and i know looking at patterns is vague but what i mean when i say looking at patterns is looking at how your input is handled or shown in the linked list example and then your output is shown write down the inputs write down the outputs and try and figure out how they got from the input to the output right so hopefully we can kind of understand how this can be coded out right i'm going to clean this up and we're going to get into it all right guys hopefully you kind of understanding the pattern that we saw previously but this is kind of getting into how our code is actually going to approach it pretty much what we're going to try and do is set our.next properties do is set our.next properties do is set our.next properties to the previous node does that make sense because remember think about our first example previous is initially going to be set to none i want to make sure that's super clear originally set to none because if you're at the first node the only thing behind you is nothing right because you're at the very first node remember the head node is always the first node of the list right so let's see here previous is always set to not right and in our reversed list i erased it here but we still have the reversed notes on the bottom right in a reverse list our one was pointing to none right and if you're confused on what the reverse list looks like i would encourage you to draw it out yourself and so you can kind of follow along that way if you're not confused that's great as well and so originally it's none and so we're going to have our current value and then change the dot next property to point to our previous hopefully that makes sense and so think about it our current is going to point to our previous our one remember our current is one is going to point to our previous which is none which is exactly what we want for our uh for our linked list right remember this though let's look at this let's actually make that change i'm talking about where we take our one and we set its dot next property to previous right previous is now none right there's gonna be issues there because look at this we broke a link right that means if we don't save the two if we don't save our next node right we have no way of accessing the rest of our list right and so let's take a look at this again let's do it the right way this time right what we can do is down here i will make a next variable right and while we have the ones dot next pointing to two we can save 2 with our next node variable does that make sense we're pretty much saving it because we know we have to change the ones.next pointer to go behind it right ones.next pointer to go behind it right ones.next pointer to go behind it right but we still want to save what it was pointing to the 2 right and so now if we change the ones.next and so now if we change the ones.next and so now if we change the ones.next and uh put it to our previous right which uh is none right oh my that's terrible one second which was none right what's gonna happen there is now we actually do have access to the two node because we saved it with the next node right and what you can do here is you can kind of like jump nodes in a way we can set the value of current equal to next that's how we kind of do that jump because you might be confused okay i know the pointers are out of place i know we've lost the rest of the list besides the next node right but how do we actually get current to the next node we said current is equal to next and when we say current is equal to next what's going to happen is this since the next is pointing to the 2 current is now going to be pointing to the 2 as well right and so now when we move our current forward we also have to move our previous forward super important um i'll go a step back actually and say this is an important way of doing these steps is you have to do them in order first previous has to point to current right so previous is equal to current that's how we make that jump right now we have to make another jump we have to move current forward to next right boom and then while we are at our new current we can set our next to whatever it is right those are the three jumps it's previous moves to current moves to next and next moves forward hopefully that makes sense and so that those are super crucial operations because like programming this is a loop right so the same things are going to be happening over and over again right so let me do this one a little bit faster and maybe you'll get an idea of the intuition right okay we're at two right we now have saved our two dot next thankfully right and so now since we have two dot next saved we know it's safe to change 2.next since we have the next node saved 2.next since we have the next node saved 2.next since we have the next node saved right and so let's do this now we're going to set our current.next right set our current.next right set our current.next right current.next is going to be set equal to current.next is going to be set equal to current.next is going to be set equal to previous hopefully that's all good there right and so now think about what our reverse was looking like in our reversed linked list was two pointing to one yes it was so now we're on the right track now we have a decent idea that can be semi-confident in our answer right semi-confident in our answer right semi-confident in our answer right and so now same exact thing i'm going to do the jumps originally we're going to move previous which is now 1 is going to move to what the value of current is right current is now going to move to the value of next right and now at this current at the when current has been changed to next we can move next forward right now next is going to be none right and so now when we're at the three what we're going to do is the same thing right we're going to take this arrow which is the threes dot next property right and we're going to make a point to the thing behind it right super important step here when we looked at our uh the reversed linked list that we won right the head of that linked list was three right so you have to think about look at your pointers look at how you're looping through how can you save that head of three right what's going to happen is our previous is going to move forward right same steps the three steps previous moves forward current goes to next right but now next has nowhere to go unfortunately right and we can do some code to make sure that doesn't mess anything up right but now think about it since current's equal to none we're gonna be done right and so since we're done look at the one pointer that's pointing to three right that should give you a good indication of what your head should be right we're probably going to want to return previous right because if we return previous it's going to give us the linked list three two one all right so now that we have a decent idea of the intuition and how to problem solve it let's get into the leak code all right guys let's get into it so i kind of cleaned up our diagram a little bit i took away the original and reversed from the bottom and i made our linked list back to its original state so not reversed right and so the first thing you want to do when you go from diagram to code is you kind of want to look at your variables you want to see what do you use when do you use it do you have to declare anything you have to save anything that's kind of the idea right and so let's see here previous we know we set it initially to none right so we can do that there now we can look at our current right and i'll point it out right here it's right here's what i'm looking at right current is pointing to one right and so you can say current is equal to head because that one node is our head right the first node given to us right and so now we can kind of get an idea of how we loop through this code right we're going to say while current doesn't equal none if you're confused on why current doesn't equal none is what we're supposed to do here you can go back and look at how we went through the array or went through the linked list before right and you'll kind of see why that's the case right so now we know that we don't have a next saved yet right well good news we have a current and so if we know our current node we know that we can get the dot next property right something people get confused on is they're like oh no what if it's none right that's totally okay because if current.next is equal to none current.next is equal to none current.next is equal to none it's not like you're going to get the error that's pretty common where you say none dot next right you know if you're in this while loop current isn't none that's literally at line 16 it's the uh it's the main point of it right it's current doesn't equal none right so current.next could be none but you're current.next could be none but you're current.next could be none but you're not going to get an error from that alone right and so let's add that in next node right let's just say uh next for our example right uh it looks like it's a keyword and we'll just go with it for now so next is going to be equal to current dot next right and so with current.next dot next right and so with current.next dot next right and so with current.next what we're kind of looking for is saying okay whatever we're at we're going to save the next note right so now we can get into actually changing the dot next property of our current right because remember one of the goals is to make that arrow which one is pointing to two we want one to point to none right and so let's do that right now we can do current dot next right is equal to previous right so let's take a look here uh and let's do that on our paper so now we're gonna have one and now one is now going to point to the value of prev which is none value previous right and so we still have current that's important current doesn't change it's next property changes right and since we still have current let's do our three jumps right previous right oh i'll make the ipad then go to the side here for a second so previous is now equal to what current is right that's our first jump right first jump now our next jump because now we have one and two they're kind of separated because one.next kind of separated because one.next kind of separated because one.next doesn't point to two anymore but we saved it through the next note right so now let's do our second jump current is going to be equal to next right sec second jump right and this is kind of not super intuitive but i was talking about the three jumps before our third jump is actually this one at the top because it's going to loop through again if current isn't equal to none this isn't super intuitive but the third jump is actually at the top of our while loop uh it just made sense to call it the third jump um before because when you're doing on paper it kind of was like the third jump right but realistically you're making that jump again at the top an important reason why you make that jump at the top is if you look at this line i'm highlighting right here right if next for any reason is none right and we tried to do you know next is equal that's current dot next down here right we could run into the issue where it's none dot next you may have ran into this trying to solve the problem yourself so it's important to realize that none.next is important to realize that none.next is important to realize that none.next is one of the huge issues in linked list problems so it's important that we did that at the top because remember at the top we always know one important thing the current does not equal none so it's gonna be any it's gonna be like three dot next it's gonna be like ten dot next whatever the value the note is right whatever the note is right and but we know that even if it's not next is none we can still access that none right we run into issues when you say none dot next it's going to give us an error right and so as we've stated before if you look at the other slides returning previous is what's going to be most beneficial for us right um when we return previous it's going to help us the most and it's going to give us that last value which is going to be our head right because if imagine with a link list of one two three you'd want your reversed one to be the three at the very end right and so it would instead be you know you have to what your current's at one you loop to two you loop to three then you're at none but your previous is logging behind you it's at that three which you want to be your new head node right and so that's why i returned previous right and so let's take a look here fantastic and so this was kind of an in-depth way of viewing this problem i in-depth way of viewing this problem i in-depth way of viewing this problem i know there are more simple problems out there right or there are more simple explanations of this problem out there but this video is definitely for the person who's beginning at lea code and kind of wants an idea of how everything works um i know i just because of the video's length i didn't go back into things in detail over and over again i kind of did in some areas for the really important stuff right but i wanted to make an emphasis on some of the key important things but it did definitely gloss over some of the other things um if you're still confused on this solution i would 100 recommending finding a python debugger right whatever you like to use and going through step by step i know the leeco debugger you have to pay for or something so don't worry about that if you don't have premium that's fine just find some python debugger online and go through step by step understanding why the code works alright guys thanks so much for watching the video i hope you enjoyed thank you
Reverse Linked List
reverse-linked-list
Given the `head` of a singly linked list, reverse the list, and return _the reversed list_. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[5,4,3,2,1\] **Example 2:** **Input:** head = \[1,2\] **Output:** \[2,1\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the list is the range `[0, 5000]`. * `-5000 <= Node.val <= 5000` **Follow up:** A linked list can be reversed either iteratively or recursively. Could you implement both?
null
Linked List,Recursion
Easy
92,156,234,2196,2236
55
when you first read this problem it feels like this is gonna involve some dynamic programming correct and to be very honest nobody actually likes dynamic programming so the good news is that this problem can be solved efficiently just by using the greedy approach and that's really wonderful so let's see what we can do about it Hello friends welcome back to my Channel first I will explain you the problem statement and we'll look at some sample test cases going forward we will start off with the most naive way and see why a recursive Solution on academic programming solution is not most optimal after that we will find an efficient solution using the greedy approach and then also do a dry run so that you can visualize how all of this is actually working in action without further Ado let's get started first of all let's try to make sure that we understand the problem statement correctly in this problem you are given an array where each element represents the maximum jump possible and you have to determine if you can reach the last index to understand it better let us look at our sample test cases in my first test case I have an array like this two three one four now what does this mean we can see it visually what do you see over here you see that you have a certain staircase and you are standing at the very first position itself right and for every step you can take a maximum of either two jumps or three jumps or one or either four jumps correct so this simply means that if I am at my starting position then I can take a maximum of two jumps so either I take a one jump and reach over here or I take two jumps and reach at the next position that is one correct similarly if I had been standing at this staircase that is where 3 is written then either you can take a jump of one or you can take a jump of two or you can take a jump of three right it simply means that this is the maximum jump you can make you can obviously make smaller jumps correct so the problem states that if you are standing at the start position that means right over here if there are way that you can reach the very last step if yes return a true if return a false so for a first test case you can see that if I am starting at my position 2 then first of all I take a jump of just one position correct and now what do you see over here now I can take a maximum of three jumps so what I will just do is I will stand over here and take a jump of three positions so you see I was able to reach my final step correct so for the first test case you will return true of your answer similarly let us look at our second test case once again just draw a diagram so you can visualize it correctly you are standing at this position now correct and once again either you can take a jump of three positions or you can take a jump of two positions or you can take a jump of one position correct and now just try to visualize no matter whatever you do somehow you will always land on this step where you cannot take any more jumps think about it if I am at the very first step the maximum jumps I can take are three right that will land me right over here if I am at step number two then the maximum jumps I can make are two once again I will land at zero if I am at this step now once again I can only do one more jump so once again I will be at zero once I am at 0 what is the maximum jump I can do I cannot do any jump from here so there is no way that I can reach the final staircase correct so for this particular test case you need to return false as your answer because there is no combination by which you can reach the very last step of the staircase correct so now if you feel that you have understood the problem statement even better feel free to first try it out otherwise let us dive into the solution and start off with the most naive way that you can think about okay so I have a sample array in front of me and if you try to visualize it will look something like this correct so if I am starting at this position then what are the possible jumps that I can make either I can make one jump or I can make two jumps or I can make three jumps right that is equivalent to you are standing over here and you either make one jump or two jumps or three jumps right that means if you are standing at the staircase with the value 3 then you have three options to choose from either you do one jump or you do two jumps or you would do three jumps correct and then where will they land you if you just did a one jump then you will land at index 2 correct if you do two jumps then where do you land at index 1. land you land at index 1. and if you do three jumps then where do you land at index 0. now watch what we are doing over here when you are at this step one with the value two that means you are standing right over here correct now how many jumps can you make either you make one jump or you will make two jumps right so it simply means that you will once again have two different scenarios either you make one jump or you make two jumps if you make one jump then you land at index one or if you make two jumps then you land at index 0 correct so what is happening over here you are making kind of a division tree correct and similarly when you are over here at the staircase with the value one once again you will just have one more position to go and you can make one jump and where will you reach you will reach a index 0. now when you go through this decision tree you realize that you cannot go anywhere from here and you cannot go anywhere from here either right so these are dead ends you just have one more situation remaining that is when you are at position one and even in that situation also you will just be able to reach a zero correct so this is also a dead end in fact so once you have exhausted out all of your options you can try to see if you were able to reach an index 4 at any point of time if yes then you could return a true otherwise you can return a false so this is a kind of a recursive solution but there is a certain problem you see that you are Computing the same case multiple number of times just watch over here you have already determined that if you start from position one then you will reach a dead end correct so there is actually no need to compute it again over here right so if you are able to store all of these reverts somewhere for example what you do is you create a DP array then for each of the indexes you can store that hey can I reach my last index from this position you determine that okay from the first position I cannot reach from the second position I cannot reach from the third position I cannot reach and so on correct but all of this just try to visualize this is so much work to do right so neither a recursive solution or a dynamic programming solution will help you out they will both end up taking a lot of time in fact The Brute Force approach is gonna take you the time complexity of order of n to power n and the dynamic programming approach is gonna take up a time complexity of order of M Square and as you remember I told you in the beginning this problem is not so complicated you can easily do it via a greedy approach and that too just in a single pass so how do you go about doing that to start finding an optimal solution first of all forget everything else and start to look at the problem once again very fresh so let us say I have this sample array in front of me now if you notice there is a very special thing about this particular test case this test case does not have the value 0 anywhere in here correct for what does that tell you it simply means that let us say I'm standing over here none of the values are 0 correct so for every stair I can at least jump one step right so if I am able to jump at least one step from every stair then no matter what happens I will always be able to reach the very last staircase correct try to think about it no matter how large your array if you do not have any zero anywhere then you can at least make one step things begin to change when one of the values becomes zero so when you reach at this position this is where things get tricky right you do not have anywhere else to go you cannot make any more jumps so first of all this is a very simple test case that if you do not have any zeros in the array your answer will be true each and every time and based upon this idea we can come up with a greedy approach as well to understand the greedy approach let us take up a generic array that is larger in size and it has zeros as well correct So currently what is the scenario you are standing over here and you have to reach the very last position right now for a moment forget everything else try to think what would have happened if you were standing at the second last position instead of the very first position just focus on this part now if somehow you were able to reach the second last position what is the value over here the value is 1 right that means with one step you can reach the Final Destination right so I can safely say that if I am able to reach the second last step then I will always reach my last step as well right just wait for a moment and try to think about it what am I saying you can be very sure that if you reach the second last step then you will always reach the last step as well so it can be safe to say that if I am able to make my final destination as the second last step then I will always be able to reach my last step as well right now based upon this idea just keep going one step backwards at a time I have shifted my final position right now try to go back one step again and once again apply the same logic if you were standing over here and you had to reach the Final Destination then can you reach it the answer is no correct because from this position you can make zero jumps right so right now my final definition will remain the same because I cannot reach the Final Destination starting from this step now keep doing this one step backward what happened if you were standing over here then can you reach the Final Destination no because once again you can just make zero jumps just keep doing this ahead and I guarantee you it will suddenly make sense now move one step back what happens at this position now if you're standing over here can you reach the final definition the answer is still no because from this position you can make a maximum of just one jump that means at the max I can reach just this Index right so once again the answer is no move one step backward now can you reach the final index if you are standing over here once again the answer is no because at the max you can make only two jumps and it won't reach you the final destination move one step backward now this is where things get interesting from this position you can make a maximum of five jumps so can you reach this Final Destination from this position either you make one jump no you make two jumps no you make three jumps no you make four jumps no then you make five jumps so yes if you've started at this index then you were able to reach the final position right so once again I can say the same thing I can move my final destination right over here because try to think if I am able to start from this position then I can reach over here and then I already know that from this position I can reach my final index so I will apply the same logic if I am able to reach at this index then I know for a fact that I will be able to reach my final index as well so once again keep repeating the same process and what I'm gonna do is I will move myself one step backwards now can you reach the final index from this position yes because you're allowed a maximum of two jumps and you can reach in just one jump itself so once again I will move my final position one step backwards Move Yourself one step backward can you reach the final index from this position yes because you can make one jump once again move your final index one step backward and move yourself one step backward can you reach the final position from this position yes just by one jump so I'm gonna move my flag one step backwards once again and this is where you stop so now I can safely say that I will be able to reach my final position notice that you do not have to outline the steps how you're reaching there you just have to tell me that hey are you able to reach yes you can do that one step two step five steps and then the final step right in this problem you do not have to outline the steps yes there can be a problem in the future where you have to trace these tips as well and determine the minimum number of jumps also that is hold together a different question but for this question itself the greedy approach is enough and you can see that it works in a linear time complexity also try to think of a scenario where you cannot reach the final step that is very simple actually so if you remember a few steps earlier this was my final index correct and let us say one of the value over here was three so if you remember when I was standing right over here what were the maximum steps I could take earlier I could take a maximum of five steps that is why I could reach over here and I updated my flag right but this time the value is 3. so I can only make a maximum of three jumps that means I can just reach over here so I am unable to reach my flag so what will you do you will keep on iterating in the backwards Direction until you find a larger value that can actually reach the flag what will happen is you will keep on going backwards and you realize that hey I cannot find a larger value in that scenario you are gonna return false as your answer so this is how a greedy approach looks like and you can be very sure that this will give you a optimal solution now based upon this idea let us quickly do a drawing of the code and see how it works in action on the left side of your screen you have the actual code to implement the solution and on the right once again I have my generic array that is passed in of an input parameter to the function can jump now moving on with the dry run of the code what is the first thing that we do of all we determine the initial final position that means where you will have to reach at the very beginning that is numstart length minus one that is the last position right so I know that I have to reach at this position currently right what do you do after that you start a for Loop that starts with the second last index and goes all the way up to the beginning and with each iteration we are just gonna do index minus that means we are moving one step backwards so I start off with the second half position right over here and then you just check can you reach the final position just from the index where you are standing you can reach right over here so what you do is you update your final position with the index that simply means that this final position now changes to this current index where you are sitting at what will happen now this Loop will run again and this time your pointer has been updated once again this Loop runs and you check can you reach the final index from here no so you will go one step backwards Can You Reach from here no so once again you will go one step backward you will keep on going back until you reach position 5. you know that you can reach from over here so you will move your final flag right over here this way when this Loop finally completes what will happen if you can reach the final position then this final Position will reach the very first index correct if you are able to arrive over here then yes you can go to the final index also so in this case you are gonna return true as your answer the time complexity of this solution is order of n because you only do one traversal of the array and the space complexity of the solution is order of 1 because you do not take any extra space to arrive at your solution I hope I will be able to simplify the problem and its solution for you as per my final thoughts I just want to say that whenever you are following problems using a greedy approach it is always a good idea to prove it out that this greedy approach will give you the correct solution there are also several other problems where if you go by the greedy approach then that solution will not be the most optimal check out my video on greedy approach algorithms if you want to know more about it so while going through this video did you face any problems or did you find any other better way to solve this problem tell me everything in the comment section below and I would love to discuss all of them with you I would also like to remind you that if you become a member of my channel then you do get priority reply to your comments and I will respond to them as quickly as possible as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also let me know what other problems you want me to solve next until then see ya
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
1,839
let's look at problem 18 39 long is the substring of all vowels in order so we are going to reach a solution based on the standard two pointer sliding window method so actually we practiced a number of similar problems following the same idea so here we will first look at the statement of the problem then we will analyze how to check effectively a substring is beautiful and then we look at the code and after the code we test several examples and comment again about the way we check the substring being beautiful so now let's look at the statement of the problem first it gives us the definition for a string being beautiful so here a string is beautiful if it satisfies the following two conditions the first condition is that all the bubbles must appear in the substring and the second one is that all the bubbles must appear in alphabetical order so next the problem lists several vowel several beautiful strings like this one and also several substrings which are not beautiful for example this one due to the order it's not beautiful and this one due to the fact that some of the vowels do not appear in the stream so the problem requires us to return the length of the longest beautiful substring in the given word so if no such substring exists we return zero so again here we are considering substring rather than subsequence so now let's look at the constraints in this problem so here the word is not empty and the length can be up to order 10 to the power fifth in other words we cannot solve this problem effectively using brute force so the second constraint is that the word consists of only vowel letters so now let's state the method and look at the example so first the method we're going to use is the standard two pointer sliding window method and the condition to check is that the substring and being beautiful the main idea is that for each index cl so we try to find the longest a beautiful substring starting from this index uh if uh there exists uh such um so um with that said let's look at the examples for example here in example one we have a beautiful string so which starts at a and ending at u so all the letters appear in order so the length is 13 and example two we have one beautiful substring which is a starting from a and a b and u and all the levels appear as in order so in example three we have a word which is a so the length is zero because for a beautiful string being beautiful the lens is at least five so with that said let's run the tooth pointer sliding window message so first make let's make some preparations so we can get the length of the work so just for coming in and also we set the length to be zero this is the variable we are going to return so now um in order to check effectively the order so that's also the key let me write here so the key is how to effectively check that a string is beautiful so for this we are going to uh introduce uh a order and check the beginning and end for a substring so uh let's first introduce the order so we have five vowels if the this is the one let's copy it here let's introduce it as box just for convenience of writing so we introduced the order so let's see the character and the index for index and character in enumerage aux so this gives us the character order so the smaller the character with smaller values should appear before the character with the larger value so now with that side let's run the standard while loop that is the selecting window step so we initialize the two pointers by zero and then we enter the while loop well l is less than n so the first is that we want to find the index corresponding to a right so on all up to the previous stage of l so for this we check if a word l if it's not a so we need to increment this l and continue the process so after this we will get a stage of l corresponding to letter a so if it has so then we try to expand the window so we first set r equals l plus one because the nd index should be greater than l so now we go to the critical condition for checking the substring to be beautiful so here the condition is necessary so first we need this one r is less than n and we check the order corresponding to word r and word r minus one so let's rest like this 5 minus 1 and our so the corresponding order is the order this guy and order this guy so the character corresponding to index r and should either have the same order as the previous letter this is the case or it's very large than the previous one so let's copy this one and red like this so we add one here so also we add princess here in order to make the make sure the or the logical order is correct so thus we have uh this so we can update the pointer by one so thus we uh get out of this loop so in order for the um substring to be beautiful we need to check another condition that is if that it ended as u right so here we are we make sure it starts at a then here we make sure it starts ends and u and here ensures the other relation then if this were the case then we found one substring which starts from l and ending at r minus one so in this case so we can after the length is maximum of length and l r minus 1 minus l plus 1 and this is the length of the corresponding uh the beautiful string in other words r minus l then actually here we can print out the things to check our solution of r plus one well here not r plus one r so um then with that state thus we exit so we can reset the left point l to be r so current r notice again so here is r because the potential beautiful substring starts uh from l and nd and r minus one so after this we are ready to print off the result or return this one so we return the lens so now i think let's check several examples so this is for example one so we know the beautiful string is this guy and it starts at index 7 and ending at before index the 20 right so that's um so here if we lack it we can actually print r -1 print r -1 print r -1 so let's check another one so the second example so for this one so we have our beautiful string is like this the length is 5 and the starting index is 15 and it ends before 20. so let's do another check that is this one a so in this case uh where we will have return zero because there are no valid um beautiful substring so up to now we are good to go let's check the generic case yeah it just passes the generic case that's it thank you
Longest Substring Of All Vowels in Order
decode-xored-array
A string is considered **beautiful** if it satisfies the following conditions: * Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it. * The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.). For example, strings `"aeiou "` and `"aaaaaaeiiiioou "` are considered **beautiful**, but `"uaeio "`, `"aeoiu "`, and `"aaaeeeooo "` are **not beautiful**. Given a string `word` consisting of English vowels, return _the **length of the longest beautiful substring** of_ `word`_. If no such substring exists, return_ `0`. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** word = "aeiaaioaaaaeiiiiouuuooaauuaeiu " **Output:** 13 **Explanation:** The longest beautiful substring in word is "aaaaeiiiiouuu " of length 13. **Example 2:** **Input:** word = "aeeeiiiioooauuuaeiou " **Output:** 5 **Explanation:** The longest beautiful substring in word is "aeiou " of length 5. **Example 3:** **Input:** word = "a " **Output:** 0 **Explanation:** There is no beautiful substring, so return 0. **Constraints:** * `1 <= word.length <= 5 * 105` * `word` consists of characters `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`.
Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i].
Array,Bit Manipulation
Easy
null
1,994
hey everybody this is larry this is me going with bi-weekly contest 60 me going with bi-weekly contest 60 me going with bi-weekly contest 60 number q4 the number of good subsets hit the like button hit the subscribe button join me in discord especially if you like contest problems and let me know what you think um so one disclaimer i have for this one is that i actually solved in java it's not necessary but i did some mental calculations that was wrong and i'll talk about that later but let's focus on the problem so the first thing to notice is that you know you should look at constraints for these things uh well the first thing i notice is that you know there's a mod so you should consider the mod i did but then the next thing is that is the constraints right one is that n is 10 to the fifth so it's hard to do brute force on that or is it but the second because it's that the numbers of i is them is dirty that means that every number um is less than or equal to 3 right so that's basically the basis for this problem is that okay that means that the number of primes the only ten so i actually looked this up because i was too lazy to code something up i googled this the first n primes and then i saw this list i was like okay so there are 10 primes i'm not doing right so that means that and because in this case you want distinct really poorly phrased if you ask me but that means that every prime number can only appear once in some way so that means that essentially there's two to the ten different possible products right um because that means that for every possible product it only takes either zero or one of each of these possibilities um which lends itself to a bit mass solution so making this observation is good enough for me to get working on it because then now i can process each number and using dynamic programming and i'll go over that in a second but this gives me an idea right um i kind of do some additional pre-processing which we'll talk about in pre-processing which we'll talk about in pre-processing which we'll talk about in a little bit but basically the idea here is uh let me actually pull up my other solution because i have a tle solution that i like in terms of progression why is this accepted in red is that seems okay it turned into green that's just that's a little bit scary actually for a second because i'm still during contest time so um but yeah so this is my original time limited exceeded solution but basically the idea here is that okay for each number um so this is a bit mask solution i'm gonna say that for this problem the prerequisite is a bit mask um if you're not familiar with mask maybe go over with some of my early other videos um especially with dynamic programming i think i have a couple of good ones for dynamic programming and bid masks um i could post some in the link below but i don't want to go over it here because it'll just take too long and i don't want to go over the same basic details every video that i do um so i apologize for that but yeah let's say you do right then there are a couple of cases that you have to consider one is that but basically the idea is that um okay let me pull up paint real quick so that i can draw some things for you but basically the idea is that okay bin mask is just some tf you know it's a boolean lookup thing right um so then here the idea about my bid mask is that okay let's say the pre this is your previous state and i'm too lazy to draw out all the numbers so pretend that this is you know 2 3 5 7 11 13 and 17 right um that means that me and here our bit mask represents 2 times 5 times 11 times 13 times 17 right and this is because these are the t values the true values right so this goes here and so forth and then that means that you know so basically we here keep track of the number of counts that we can do this and this is of course just the number of um this is just the number of twos and fives and so forth right uh if they were all primes and then now how um the next number if the next number is a degree for example then what does this mean right that means that well we have some count here i don't like the number the red so we have some x which is the number of count of or um of this product right so then now if we add a degree here what does that mean that means that you know what is the number of ways to do this thing right 2 times 11 times 13. i'm drawing these with the mouse so it's a little bit slow but so now we let's say we wanted to get this count and that we're processing it three right then that means that now the new um state so let's actually call this x sub i um and then now this is x of i plus one maybe of i for index um this is x um and way and possibly say i mean price is not the addition but yeah um so yeah so this count is going to be the number of discount plus the number of uh the previous count right so yeah so basically now that you process a degree you just add the number of ways to you know do that right so in and put in another way and i'm going to get rid of this for a second um so basically for example oh i cannot edit this here quite yet oh technical difficulties hang on this is my tre solution so you can say that for example like i was saying before you know you have you know f of um 2 then 3 or 2 times 5 times 7 times 11 times 13 is equal to some number let's say there are 20 of them right um 20 ways to do this then f of and now let's say we're processing a three and we want what does that mean right that means that this is just equal to uh this number that we are process plus the previous version of this so let's just call it this uh because i'm too lazy to change notation but basically it's just this plus the previous notation of this and put it in another way though it is just this plus uh yeah this times that uh yeah but basically this is just equal to the previous way which is 20 plus this which is uh oh oops no uh this is 20 because that's the number of ways to kind of have this product and here is the number of ways that we used to have it right before we process this number so that if we um so basically given that we're processing a three we can either um use this three if we use this 3 then the previous product has to be so let's say we're processing you know we're processing a new number three we have this number um if we use this three so this is the state or this is the product um if we use this three then the previous product have to be this minus the three it has to be this right or if we don't use this 3 we then the previous product is just the same right which is this thing um so then now we just sum the number of counts so that's basically the idea behind this one um so then you do this for every number and note that because there are only 10 possible primes you can actually try it for every possible uh product so that means that um let's say we're processing a three right what does that mean that means that we can try product is equal to three uh product is equal to six um and so forth and of course in this case product previous so previous product is either um previous product is either you go to one or product is three because we don't use it and in this case previous product is equal to two or product is uh six right and then you kind of dot this you do it for every um product that has a three in it so and there's only two at most two to the ten of these because um this had to be distinct right um because for example nine cannot be here because that includes two degrees so that's basically the idea um and it becomes a sort of a digit some dynamic programming and yeah and i just kind of um pre-process the ones that are not pre-process the ones that are not pre-process the ones that are not possible um because these we have because for example just have two twos this have two twos as well so all these have two twos um or all these have two twos these have two uh two degrees and just have two fives and these are all the numbers that are less than dirty that's no good i was gonna write a function about it but then i was like okay there's actually not that many so let's pre-process this um yeah uh and then here yeah we just put in a boolean array so that's these are lookup and then so one more thing that i didn't talk about um is that i didn't count once because you could think about once as that f for every one you can put in them um two to the so let's say you have ten ones you can actually you know do some permutation of the two to the n versions or two let's say the x ones then they're two to the x ways to kind of add that to the existing answer right um because you know that's just that's the number of combinations so that's basically so we keep track of the number of ones and then otherwise if this is a good meaning that it um if this is not no good do i use good i actually don't end up using good yeah because i end up doing this so i actually don't use this whoops um but yeah if this is good and what does that it means to be good uh when it gets here that means that is a product of distinct primes uh or product of primes that only appear once so then now we get the bitmask for that product mean um so if this number marks this prime is equal to zero then you know we do this thing and then here we look at every bit mask and do a dynamic programming as we talked about right basically if the count is greater than zero meaning that if it's at least if it contains at least one uh number meaning that it exists before and that there's no overlap basically this is just a bit mask you know boolean and of okay this overlap uh then this is no good so if the if there's no overlaps meaning the overlapped is zero then we just set the mass to be plus one or plus this previous number and then we mod it of course because of the mod and that's pretty much it and then for each ones we multiply by two at the very end um so how is the math work here right so the math is such that okay this loop is o of n and each loop does uh that's two to the x uh operations where x is equal to 10 because uh and you know because 30 is only 10 primes right so this is in total o n times two to the x where n is equal to a hundred thousand and times a thousand so this is roughly a hundred million uh to be honest i thought this would be fast enough uh but not in python so i changed it to java um that's basically the idea why i did in java um the reason why this failed in a time limit exceeded kind of way is because um the reason why i um the reason why ideas in time limit kind of ways and you can watch me do this during the contest live but during the contest you can see that for each of these um it takes at most one second in the worst case um but leeco actually does calculate time limit exceeded with respect to the sum of the execution time right not just execution time so as a result so if there are 20 test cases it may fail if the five test cases it may pass right so that's why my code time limited and i suspect that a lot of top people probably did it that way initially and then saw it fail um because of that reason um so there is one more optimization that i end up doing as a result which is that um but yeah that's why i submitted and that's why conver can converted this from python to java because i thought that 100 million maybe fast enough in java but not fastened up in other languages um but i was wrong it wasn't fast enough anyway but there's one more optimization is that noting that again num sub i is equal to dirty so that means that you don't have to process or 10 to the fifth or you have to but you don't have to do them one at a time you could combine them in a way so that's basically what i did here is that i put them in accounts um yeah i put them in counts so that the only dirty numbers um yeah and then here now if you look at this is just m o of 30 or x if you want to call it that um and each one of course does 2 to the x so this is now o of x times 2 to the x where x is equal to 10 and x is number of primes right so yeah so this is the same formula um and then i also do this thing with once which if you do mod power you can do it without this but i didn't have to do my part because this is at most 10 to the flip anyway right so it's just another for loop so yeah um so this is this part of the algorithm but of course in total complexity because we have to look at each number at least once here so this is going to be o of n plus x times 2 to the n uh 2 to the x and this is going to be fast enough and in terms of space um i only this is the most thing so this is 2 to the 10 so that means that this is 2 to the x space um or o of 2 to the x space where x is number of primes um yeah do i actually have to i actually have this lookup table as i said again this is not necessary but yeah i have this lookup table um but you can actually just put in the hash table if you put in a hash table then oh i guess that's what i did here but i just told a boolean table if you put in a boolean or you put in a hash table this would be o of x space anyway so it's not so even though this looks awkward is not actually true um but yeah so this is time and this is o of 2 to the x space but yeah um let me know what you think about this one is kind of a tricky one but yeah let me know what you think hit the like button hit the subscribe button you could watch me solve it live during the contest next um including the progression of how i did it oh i have to explain one more thing about the progression is that after combine them the key to note is that not including the ones um you can just take you have to take at most one of these bit masks um so basic basically for example if you have five degrees you have to choose between one of them so that we just this is a simple multiplication and of course you can do some math to make sure that this doesn't uh this isn't um much more go over mod but it should be good because this is only 10 to the fifth yeah this is only 10 to the fifth and this is bits and inch so this should fit in as well and you just mod it afterwards um but yeah um again you can watch myself it's live during the contest yes larry okay seven people i finished this and i'm 10 minutes of penalties so this is not great um how far behind am i okay let's refresh norms if comes good if the product of one or more distinct prime numbers we're gonna want good subsets not good subsets because if it's if i look up one or more distinct prime numbers what does that mean okay mod mode um how much penalties do i have yikes okay there are a lot of wrong answers on this one so i have to have some time to catch up but if i just had something wrong so it's fine okay so the length is 10 to the fifth but the numbers are only up to 30. so this is a interesting one if its product can be represented as a product of one or more distinct prime numbers what does that mean that english is kind of hard for me to pause in the morning i've got is six okay why is this not a good subset though it's a product of one or more distinct prime numbers this isn't this the product of at least one prime number i don't get it 23 okay three that's fine yeah why is four not good hmm i mean this is going to be some uh dynamic programming with pit masks i think to be honest but or something some variation of that but hmm the product of one or more distinct prime numbers okay i guess this is not this thing is what they're saying because four is two times two they could phrase that in a more like english way i think the distinct does a lot of work here okay um how many primes are there under 30 or 30 well i guess i was going to say 30 or less but uh there's no three so this only let's see there's only 10 primes under 30 so it is i was going to write something but i'm just going to copy and paste it so these are our primes and then now and now how do i want to think about this is doable for me probably but i have to think about it a little bit slower so okay the sorting help i guess it doesn't change anything if we're just doing that but um so that means that we're trying to think if so the hmm so each number here how do i think about this will contribute but the ones are kind of confusing but okay so that means that we for each one we have so it's two to the so for each number we do two to the ten is that fast enough yeah okay i think so hmm let's do the ten a thousand was ten to the fifth maybe not ten to the fifth times a thousand is a hundred million yeah a little sketch in python i wish they have a big i mean they should give you a big answer but that's fine let's see like n doesn't even have to be 10 to the fifth though i don't know why they do it this way uh is there a smaller way um 100 million is pretty slow in pipeline though i don't know i don't feel comfortable doing in python if this is the solution maybe there's a better solution though that's why i'm trying to think a little bit i think this is a easy solution easy for me uh all right wait doesn't buy fun anymore what three one two three just using it and i'm not using it okay and it's strictly yeah okay um i don't even know this is the correct language thing is uh 2 to the 10 so yeah i haven't done java in a while so that's why i'm like compiling maybe obvious to everybody thinks yeah okay maybe that i'm using another language construct okay i think there's a for each loop in java too but i don't want to look it up okay it's that good it should be okay my just doing some mind optimization what about some no good numbers maybe i did this backwards so four is no good and then every multiple of four so nine those are all no good i want something that basically means that it is only um because a six could be good for example because it's just two times three but yeah maybe i'm doing this in a weird way yeah maybe i don't do it i don't want to do that for every number though i should pre-process this okay though i should pre-process this okay though i should pre-process this okay um maybe i just do it this way so i do it manually uh okay 27 is not good because so this is three times two and that's it and then just 25 and then everything else doesn't matter so i should i shouldn't write code for this just to make sure this one's right though because i'm going to eat it later if i don't this is two times two so okay so four times even nine is too big and four times five is twenty so okay so yeah i'm okay there may be a cleaner way to do this but basically we just want to be able to skip um we want to be able to skip uh this and do this thing very quickly no if this is no good then we continue um because that means that this number can never be a part of set if except for one maybe if num sub i is equal to one then we do something funky which is we double everything yeah we double everything except for previous of one i suppose uh it's one enhancer one is not an answer right so yeah okay maybe this is a one not of zero okay maybe that makes more sense okay and then now otherwise we look at the contributions i got no mask on mask i need to okay actually no that's fine oops um okay now we just do this again whoops i need to put this in a constant somewhere um because i feel like i'm going to have a typo somewhere okay um and now j is greater than zero that's what i need to zero for but that's fine um i think this should be good maybe but i have to do this part but is let's go so i want something like this but we have to be clever about this because this is not going to be um yeah this is going to be i don't know i think that's okay because by the time we go to j and mask if j is j and mask um this would not be equal to zero anyway so okay maybe we're good here um and then now we just oh wait this is no longer okay i messed this up okay so zero means no none no numbers not because not one okay um times that this is one then we start at one and then we double all the components okay man that's a silly mistake if i had held it um now that means that this could be zero and then i don't need to do this um okay and then now we just sum from everything from here so do okay in theory not a platform but i should say that after i get this right first at least get it compiled first okay is it hmm what is uh what's the boolean in python uh in java is it just boolean or um i guess this right and okay so this is this okay that's not so bad i guess this doesn't have to be a long time ago well that is unfortunate i think how i'm doing once is wrong anyway i think this is wrong let's just do yeah okay let's at least try to get it to be non-zero first and then we'll think non-zero first and then we'll think non-zero first and then we'll think about it once uh why is this zero oh okay three and five okay i mean okay so we were good except for the one so then now we have to do um how many ones can there be i guess they're going to be as many as this so we just have to do it every time okay fine i mean we can actually do this in a smaller way but for now i'm going to just do it this way you know how to do the power math i know how to do our math but am i good here all right let me just the only thing i am worried about is this mod stuff i think i only do the modding here and here so i think i'm okay let's huh here goes nothing if it's t o yeah that'll be really sad because i spent a lot of time on this one okay well i guess i should have test this to be honest um because i feel like that is testable but i don't i um this is only 100 million though like see it's fast enough so it's a little bit awkward but there is one optimization that i could have done and i could have done this in python is that i could have condensed it i forgot that could be a frame so then now we can do everything in um yeah i could have done that okay fine um do i want to do it in python no i think i could do it in python now but uh how would i do this i mean this is doable larry just do it um so what happens if they're multiple twos all right let's play uh this actually isn't even ten thousand so i don't okay maybe it is i don't know i didn't really count um but let's just say we have this because i have to write answers just that is tlu so i could fix this is 41 why is it 41 should be just combinations of six right is this right because there's just five on this side five on this oh i mistyped so okay there's 30 plus 11 so okay 41 makes sense okay so that means that okay to be honest i also thought that 100 million should be fast enough though i don't know it's a little bit awkward but okay fine um maybe that's what other people did too i don't know that's why there's so many off by oh that's so many uh penalties um i guess we can move this here actually whatever let's just do it this way so that now i is the number so for now i is the number i cannot be zero anyway but once it's equal to count something one excuse me if no is no good thing is that i always submit it so it's okay oh this is not what i want i mean i guess it could be what i want hmm so let's get the mask it's this but hmm what does this mean this means that we can have counts number of them right so something like this maybe i'm actually not confident about this one but we'll give it a spin because the spinning is free spinning free whoa no good stuff i oh because we go up to oh okay i mixed up how i wanted to do these and then i changed my mind so then i now have to eat it also this doesn't make sense i'm watching a little bit too much slowed down myself half an hour okay it's just the same answer as before and now it suffers really fast i actually don't know hmm oh wait oh no this gives me a time limited okay so but this is right so let's see nope i know i'm spending a couple minutes here but at this point uh the extra time doesn't really matter i don't think i'm not that i'm not going that fast is my point uh actually i don't know if this gets copied but there should be a copy button here okay and then now let's just so that's my own code which i know works right quote maybe just that it may have made time limit but it doesn't time down to here so are these the same inputs yep okay except for this is much faster okay am i good yeah let's give it a go i yolo okay yeah thanks for watching hit the like button hit the subscribe button draw me a discord especially if you like talking or seeing about these contest farms in a more real time i'll see you later stay good stay healthy to good mental health uh yeah have good problem solving bye
The Number of Good Subsets
minimum-number-of-swaps-to-make-the-binary-string-alternating
You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers. * For example, if `nums = [1, 2, 3, 4]`: * `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3` respectively. * `[1, 4]` and `[4]` are not **good** subsets with products `4 = 2*2` and `4 = 2*2` respectively. Return _the number of different **good** subsets in_ `nums` _**modulo**_ `109 + 7`. A **subset** of `nums` is any array that can be obtained by deleting some (possibly none or all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different. **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 6 **Explanation:** The good subsets are: - \[1,2\]: product is 2, which is the product of distinct prime 2. - \[1,2,3\]: product is 6, which is the product of distinct primes 2 and 3. - \[1,3\]: product is 3, which is the product of distinct prime 3. - \[2\]: product is 2, which is the product of distinct prime 2. - \[2,3\]: product is 6, which is the product of distinct primes 2 and 3. - \[3\]: product is 3, which is the product of distinct prime 3. **Example 2:** **Input:** nums = \[4,2,3,15\] **Output:** 5 **Explanation:** The good subsets are: - \[2\]: product is 2, which is the product of distinct prime 2. - \[2,3\]: product is 6, which is the product of distinct primes 2 and 3. - \[2,15\]: product is 30, which is the product of distinct primes 2, 3, and 5. - \[3\]: product is 3, which is the product of distinct prime 3. - \[15\]: product is 15, which is the product of distinct primes 3 and 5. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 30`
Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.
String,Greedy
Medium
null
215
Le code problem number 215 K largest element in the Inn array so this problem gives us a integer array called num and an integer K and we have to return the K largest element in the array and here it notes that it is the largest element in the solid in the sorted order and not the cave distinct element so what this is telling us is that there is going to be duplicate numbers though right and here it asks whether or not we can do it without sorting in which we'll be using a priority Q not too sure whether that counts as sorting but this partic container makes everything easier so what the priority C does is it will basically sort the elements given by itself right so we do not need to actively sort it in a way but anyways like I mentioned the priority Q would okay let's say we have the input of this right and K being two okay so what we do is we initialize our PRI using the numbers so our PRI will look like this right we'll start from the we start from the biggest six actually sorts from smallest to largest so one two three four five six okay after that here while uh K de increments and K is still more than zero I will pop right since K is two I need to pop two right oh actually my bad sort it in descending order okay so since K is two as mention so what I will need to do is to pop only once actually because this is the five is the second largest number in the priority Q right so once this is Pop we just return five right top same thing if there are duplicate numbers basically the duplicate numbers will be just below it and when we pop it does not really affect the numbers below enough right okay so that's how a priority C makes this problem too easy not too sure whether it's the intended solution but since I did not sort it so technically I did not cheat okay anyways that's all I have to show thanks
Kth Largest Element in an Array
kth-largest-element-in-an-array
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element. You must solve it in `O(n)` time complexity. **Example 1:** **Input:** nums = \[3,2,1,5,6,4\], k = 2 **Output:** 5 **Example 2:** **Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4 **Output:** 4 **Constraints:** * `1 <= k <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
Medium
324,347,414,789,1014,2113,2204,2250
212
this is larry this is day nine of the leeco daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's farm which is word search two huh seems like that's uh that's a sequel to the one that we just did was it two days ago three days ago um so yeah so not that long ago already giving us a secret this is like a big company or something like that but uh oh no this is what i was worried about and that i will uh okay we said to okay i'm not looking i mean i know what this farm is anyway so okay see this is why i didn't like uh the move from explore to um to this thing right because now it may have me solving it previously and have the code on screen that doesn't mean i'm trying to cheat i actually didn't look at it i wasn't paying attention i was just making some comments about research too and sequels and big movie companies and so forth whatever now it's a little bit awkward when did i solve it why is it still in my cash i mean this was that's weird right like this was a year and two months ago and it was still in my uh like cookie or whatever the equivalent of local storage uh huh that's really weird also apparently i had wrong answer twice both those times so maybe this time i'll be a little bit more careful and of course um what was i gonna say uh what i was going to say is yeah i don't like being biased in knowing what happened before in any way i like to start fresh and i think i would like to think i'm mostly starting fresh so we'll see how that goes that would this one is a little bit awkward video uh i hope y'all were okay with that anyway let's get actually started uh onwards word search two so as you can tell i'm usually solving these live a lot of these or everything is unscripted and everything's off my head so let's see what this problem is um i'll actually go over a little bit about computationally hard problems in the video two days ago uh with research one so i'm not going to go into that too much but i would say that you know this is a computationally hard problem i'm not going to try to look too much into solving it in a polynomial time per se so i'm going to try to figure out what's the situation here okay let's actually read the problem now given all that set uh okay give an m by n board of characters and a list of string words return all words on the board okay so each one must be constructed from adjacent okay okay so now you basically it is like um like word search one except for now you have a list of words instead yikes right um i mean i think the canonical way and whenever i say that it means that uh i've solved this before which i have on leeco but even before that so it's a little bit i really hate that this kind of spoiled a little bit for me i mean i didn't really take a deep look but you know there's still like some hint of a shadow and it's at least it's hard for me to be like hey i'm starting fresh today because i'm not going to remember from a year ago versus like uh maybe i have some subconscious um like i read the problem on a subconscious level or something i don't know or solution or something so it's a little bit awkward but anyway the way that i would attack this is actually now that i think about it's kind of amusing because yesterday's problem and i guess they actually maybe put some effort into not because i don't know i think lee co probably put or i had thought that liko put all these problems kind of in a randomized kind of way like just give you random problems and do whatever but at least for these last three problems or the last two plus today's um it seems to fit in together right because yesterday's farm if you do recall is implement a try and the day before was worth search one and this one coincidentally maybe or planet uh will require a try and a word search so hmm so yeah so basically this is going to be brute force in a way but you can still make it once you know uh you could still reduce the complexity a bit by because you can imagine that um okay let me write out what i would write as a brute force right um what hmm why is my watch keeps pinging oh no and i keep on getting pop-ups okay oh no and i keep on getting pop-ups okay oh no and i keep on getting pop-ups okay um so basically i'm trying to think right i should just copy and paste from the other one right um yeah okay in the interest of time because and because i'm a little bit lazy and it i don't know how much why you get out of seeing me retyping my solution from two days ago if it was longer ago i might actually type it from memory it's not that bad actually you could type in like you know what is it like 15 lines of code maybe 20 lines of code but in the interest of kind of keeping the video moving slightly a lot a little bit uh i am going to load the solution from two days ago right um and yeah and feel free to kind of skip forward as much as you like and actually this is a little bit oh yeah i forgot that i did it kind of this way uh which is that it is not super optimal but let's just say we have this function right uh that lets us get find single word right and so now this we know is true and then you might do something like um i think there are a couple of things that i was talking about which is that uh which i didn't do for this one because this the time is very slow is kind of and we should maybe make some solutions here which is that uh yeah if i plus one is equal to n we return true um because the function cost are expensive for sure right so let's make some optimizations let's actually do these optimizations here um yeah if and this is you know i'm not gonna go into detail too much to be frank because this is from the video two days ago if you do have question about what is what i'm doing here um obviously just watch that video from two days ago uh yeah so something like that right so this would actually improve your timing already by a lot um i have to add some i have to add these if statements here as well so yeah let me do that right so yeah so this is going to this is basically an optimization optimized version of what we had before um and if you just do you know um uh let's see what was that do we return how many times one thing i'm just double checking is whether um you know if a word appears more than once um do we return the answer more than once but that's fine it doesn't seem like it's okay uh so yeah what's the words if find single word of word uh and start a pan of word return answer and then this should pretty much solve this problem as you can imagine um you know we added a for loop we optimized the speed somewhat uh and i'm wrong somewhere uh oh yeah where am i wrong where did i go that's all awkward maybe my optimization kind of mixed it up let's see well this has to be true i don't know why i add this here whoops okay if this is inside if it's not seen in this case i guess no this is okay uh oh i see because it's the same issue that i had actually in the other one which is that i guess we just have to add this here anyway um yeah okay fine huh well this is awkward uh what am i doing incorrectly hmm but yeah but right now i'm just you know going to go try to get it work for uh as naive as possible really but i don't know why this doesn't work to be frank uh yeah oh so this works so eight am i do i just have an off by one maybe i have an off by one two oh this is awkward but next scene oh whoops uh in this case this should be annex and why that copy and paste while i type them huh i don't i think i typed them but i didn't i type the incorrect one that is one problem with python is that it's very easy to kind of make these mistakes um yeah okay so then now i have i do the thing where um uh let's see did i mess up this already is correct um we should this should be the thing i think um and yeah okay that's why i have this here still really bad code though to be honest um anyway my point for teaching is going to be that uh you know this is a little bit of a rewrite of the previous one but it's going to be all right and it works now after i you know correct my typo and so forth um but this is probably going to be a little bit too slow um is it yeah i mean i want to say it um because there are a lot of words right so we're going to do this exponentially for a lot of words this is going to be a little bit too slow so the thing that we can do is uh figure out how to reuse um as much work as possible right and what does that mean that means that for example if we you know right now um i'm not gonna submit it because it's just gonna time limit but the idea is that okay for every possibility we're gonna redo the first six characters every time for every word so what we want to do is kind of do them together in a way such that we do the same the first six character at the same time um and that's basically how i would think about it um yeah um and that should make it fast enough because if not then maybe we have to make more optimizations but that's where i'm gonna start and this is kind of a mess to implement now that i think about it but that's why i also brought it back and the thing that you can do to kind of do it one at a time is with prefix sum oh sorry prefix some prefix tree which is a try um and the question is that okay instead of doing all this per word we can go one character at a time for each direction we ask ourselves can we go in this direction and if we can then we just you know go for it and i think that's where we're gonna do or that's what we're gonna do so let's get started um so yeah so let's create a try um am i lazy today maybe i am let's create let's copy the try solution from yesterday because i guess that's part of the intention anyway uh and like i said usually i do implement these things from scratch uh for every problem um but this is literally yesterday so it's not even like the corpse is not even code yet so i'm gonna at least reuse this part and then yeah and then see as far as we can get things are loading right now so it is what it is okay there you go so i'm going to copy my solution here which i think should be optimal i know that some people uh did some optimal solutions yesterday and it still passed uh well today you can't get away from it uh so you can copy and paste from someone i guess this is fine uh it's just about learning and problem solving these are just lego pieces it's not that big too big of a deal so yeah so now we let's just say we have a try is he going to try um then for word and words try dot insert word i think that should be okay yeah and then now we can go one and then yeah and then now we can go one character at a time let's remove all this i mean maybe i think there's gonna be a lot of overlap but it's okay i'm going to uh yeah i'm gonna copy the directions though because i'm too lazy to type that one again but we'll see what is required of us for this one yeah now that we constructed a try for all the words we can just ask ourselves on the brute force one character at a time um do we need to go any further right so actually yeah so now let's see right so r is equal to length for board c is equal to the length of board of zero and then we're gonna just basically do the same logic here which is this thing um yeah so basically we look at okay can so now we ask ourselves instead of for you know so in the previous word search we ask ourselves okay given the first character um does this current board match the first character right this is the code that we had previously but instead now we ask the question of okay now we're at board of x y read this position is there of any word that starts with this character right and then now that you phrased that question we wrote it instead in terms of your data structure right now i've asked myself is you know given the root is still um an edge to um is there an edge to that has this character right so that's basically what i'm going to do uh yeah let's um how do i want to write that so yeah let's just say uh you know okay so now we have sorry try okay so now we have sorry try okay so now we have sorry try that root and then we want to ask if it has i think i haven't has edge here yeah on the node so i ask us if i have has edge of board of x y if we do have this then we do a recursion right so then we do that so the current node is going to be root.get of root.get of root.get of um board of x y and then yeah and then we go on x y maybe so this is basically the same ideas here um yeah except for we're gonna abuse some global state um yeah okay so for example instead we have an answer away here or maybe a set just in case uh somewhere it may be uh may appear in the answer multiple times um yeah and then now we have this go function which again i am terrible naming things maybe this could be just uh search say slightly better not that much better though to be frank uh but yeah but then here we get a note right and this is basically mirroring the logic of what we had earlier um we're going to go okay if no dad is n what's that called is there no hassan don't remember oh is n and we maybe could have put this into a um a helper function but you know it's a way a property or whatever so yeah if this is the end then answer dot append um well we actually want to include the word up to this point um so you can actually there are a couple of ways you can think about doing this one is just going back up the note tree and then the other is what i'm going to do here which is uh let me just delete this i don't really need this anymore i think maybe not i don't know um but yeah so that means that if this is the end we want to add the current node so actually we want to include this on a stack or something like that um and that's fine right so yeah so the current thing and then here if this is the end we want to add this as a word so we want to do joint of current right uh yeah but just because this is the end this does not make it the base case because it can um some words can be prefixed or something or yeah prefix of other words so you want to keep searching right so then now we do the same thing as before we want to search order um yeah press t y and then here we now want to search yeah um i feel like my thing is always a little bit off by one the way that i'm doing it let me think about this for a second because basically now maybe this resolves it actually because basically now uh we want to go okay can we go in that direction right so if so we can go in that direction if of course it is within bounce because if it goes out of bounds then you can't really go in that direction and the current node has edge of that um of that character right that means that we can go to that character so if that's the case then let's do a search on this um we'll do a current dot append of board of nx ny and then current.pop afterwards of nx ny and then current.pop afterwards of nx ny and then current.pop afterwards um but here we do current and then node.get. so basically we're going to that node and then now we're going to that node that contains that point um and i think that should be mostly good enough except that we have to return the answer and maybe that should be good let's run it real quick and minus order try code which we wrote yesterday this is mostly good enough uh this is try that rule don't i put in a temp variable i guess it's not necessary though so yeah so this looks good is it good for everything uh let's give it a submit and see how it goes watch i get the same wrong answer as this one that would be really sad actually but maybe i get tle because this is taking a while uh can i make some optimization oh no i get the wrong answer oh did i actually literally make the same wrong i guess i'm consistent actually it's kind of funny because i when i was writing this i was like oh yeah because i was looking at um the code from two days ago i was like okay don't forget scene um okay so this is actually a different one but i forgot scene so yeah so we have to actually also keep track of scene yikes right uh sadness yeah um and then here and not scene of um nx ny then here we do want to set c of nx and y is equal to true and then pop it off afterwards and same thing for here oops right so then now let's add that back in oops oh whoops i didn't run the correct test code so let's do that okay why what oh yeah so that's good um what was my wrong answer oh this one let's actually put i guess this one is gonna nap okay let's give it a submit again hopefully i don't get the wrong answer again uh three years in a row i get a wrong answer hopefully i don't do worse than last time though because that would be really sad okay wow my code is way slower than last time now i'm curious why huh what did i do let's take a quick look actually but yeah but like i said this is gonna be exponential so you're gonna be doing things about the same way but i'm curious maybe i added an additional pruning now this is mostly the same idea anyway uh huh a year and three months ago so i am consistent in a lot of things but why is it that much slower maybe this takes more operation maybe this pop takes more operation as well i don't know huh that is weird huh why does why is this code so much faster like i don't think i see anything that is really obvious as to why it is slower um like maybe minor things here and there but not really right i guess the um don't know huh yeah maybe there are just more test cases from then but that's i don't know that this is eight seconds is cutting it close though so it's a little bit actually sad to see anyway but yeah but as i mentioned even in the one from two days ago with search one this is going to be like an exponential solution no matter what you do so you can only aim to optimize it as much as you can and here we are dangerously close and we can think about optimizing even more i'm not going to do it today but this hopefully gives you a place to kind of begin to kind of think about that optimization let me know what you think uh that's all i have for this one stay good stay healthy to good mental health i'll see you later bye
Word Search II
word-search-ii
Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_. Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. **Example 1:** **Input:** board = \[\[ "o ", "a ", "a ", "n "\],\[ "e ", "t ", "a ", "e "\],\[ "i ", "h ", "k ", "r "\],\[ "i ", "f ", "l ", "v "\]\], words = \[ "oath ", "pea ", "eat ", "rain "\] **Output:** \[ "eat ", "oath "\] **Example 2:** **Input:** board = \[\[ "a ", "b "\],\[ "c ", "d "\]\], words = \[ "abcb "\] **Output:** \[\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 12` * `board[i][j]` is a lowercase English letter. * `1 <= words.length <= 3 * 104` * `1 <= words[i].length <= 10` * `words[i]` consists of lowercase English letters. * All the strings of `words` are unique.
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
Array,String,Backtracking,Trie,Matrix
Hard
79,1022,1433
1,562
hey what's up guys this is john and today let's take a look at this lead code problem uh 1562 find latest group of size m so this is one of the weekly contest problem okay so i mean it's a medium but i to me i feel like it's more like bit medium hard at least i didn't solve this problem during this weekly contest you know i had a hunch that is i should use the union fine but i just i didn't have time to finish the coding so yeah anyway let's take a look uh given like an array that represents the permutation of numbers from one to n okay and you have a binary string of size and that initially has always been set to zero basically at the beginning you for example if you're given like a five arrays here five elements here right so which means you will have like five zeros at the beginning and at each step the position that the index at the three here one base will be flipped to one for example this one here three is one so the first time the three will become one then the third number okay and the second step five means the fifth one the fifth element will become sorry so the fifth element will become one here and same so i'll continue so uh at the third step the first one will become one and at the fourth step the second one will become one and the last one the last step four will become one okay so and then the question is very interesting it asks you to find the latest step at where there's still like exist at least one group of ones of one of ones of the length m here of length exactly am for example the this in this example the m equals to one which means we need to find the last step that still has at least uh one group of ones see at the beginning here right so the first one is one here when after the second step we have two group of one at the third step we have three but one we when we have when we add at four step you know once we insert flip the beat to one at the second place basically this two one will be merged into a into us three ones which only leaving us only one group left and when it comes to this the last step everything right everything will become one group okay so that's why the answer for this example is four because at the step four we still have one uh one group of one left but that's step five there's nothing there's no group of one okay so uh and for this example we're looking for like a group of two m uh two ones okay but if we follow the sequence of this array here there's no way we can have like two ones at any step that's why we uh we return minus one okay um i mean the uh the easiest approach not approach i mean the more intuitive thinking is like we should we can use union fine right so it seems like unifying for example this one so when we reach us flip this one here basically we're union the left and right together right and yeah i think that's a you know that's a good start i think unifying can definitely solve this problem we just need to modify the union find a little bit i mean if you guys still remember the template of the union fine basically we have a parent right and then we have a rankings we have ranks basically um uh the i mean the ranking is not that important basically we use rankings to determine like which uh which stop uh which subtree we need to merge to the other right basically the part with smaller ranks will be merged to the part with the higher ranks that's how the unified works right and then but for this problem you know in besides the union fine itself we also need to maintain like the counts basically we need to also remain the counts of each of the groups here i mean basically we're going to have like a group count like group counts so basically this group count means that we need to maintain like how many like for one okay how many ones the count of each consecutive ones since we have like uh in total we will be having like five ones in this case right so we basically the uh the index will uh represents uh this many ones how many gr how many counts we currently have okay and we'll be using this one right basically to uh to maintain the uh at each step uh what's the uh the concept what's the groups what's the counts of that num many ones okay and so that this is the main uh structure we'll be using because so that if we somehow can maintain this variable right and then after each step right we simply can check if the group counts uh m right i mean m is the length we need if this one is greater than zero okay as long as this one is still greater than zero then we know okay we still commit the our requirements right so we just update the step and once we finish everything then we know the latest step will be our answer okay cool and but how can we uh update right how can we update the uh how can we maintain these group counts so since the index is the uh is the counts itself right so in order to make to maintain this one we also need like another counts here another counts basically the count is for each of the root of the union find in i mean in term in terms of the union fine right basically you know unifying you know we have different routes and this counts will be the basically the size of that union of that tree the union find tree okay and we'll be using that one to update this group counts uh cool and so let's try to code these things up here okay uh i mean the coding itself is not trivial basically it's kind of it's a little bit long because we need to maintain like the unifying structure okay so stay with me guys okay i'll try to code uh faster here so basically the first thing is we're gonna have like a you know for the union find we have two methods right here x and we have a find and we have a union okay union is x and y okay so and for the union find we also need the parents right remember so at the beginning each of the parents it's itself right which means we're going to initialize this thing with the range of n right it's just part of the union uh unified template okay and then we have a ranks okay ranks equals zero and n right so these two things are just a very basic unifying thing uh how about we just implement the very basic unifying templates here basically you know for a union find we'll while doing the union find that we are doing the fine we also do a path compression okay if you don't if you guys don't know what the past compression means uh you can try to look for uh some like different videos online we'll try to search on the um we on wikipedia basically every time you know we have a sorry when we have like a we're looking for a length uh of variables here right when we try to find let's say for example this is a root okay any time when we have like a root here we're trying to find what's the root of this note here so by the time we are traversing back to the root we remove any of the notes on our way to under this one let's see one two three and four okay basically we'll be moving this three and four here okay so this thing is gone is also gone so after this one right so the next time we search three and four there we don't have to uh traverse back here right we can just uh we're gonna basically find this three and four in one instead of one okay that's the basic idea of the path compression and the way we're doing it is like basically if the parent's parent x is not equal to x why are we doing this right because at the beginning right the root itself it's parent right that's why we're using this one and then the parent x equals to find parents x okay so only these two lines can help us doing can help us do that it's very powerful and in the end we return the parents x okay basically where you're using a recursive call here okay and then for the union right for the union there's a root one and we find x okay under root two you need to find y okay so and if r1 is not equal to r2 okay because if they are the same there's no point of uni it means that we have they have already been union before okay we only union when they are not when they don't have the same root here basically uh the template is this basically if the rank r1 is equal greater than the ranks of r2 okay and then we assign the parents of r2 to r to r1 okay and the ranks of r1 will be increased by one else we do the opposite we assign the r1 the parents of r1 to r to r2 and then we also do a ranks of r2 plus one i mean here the equal sign here right it doesn't really matter if the ranks are the same we can either do this or do this in this case i just happen to be doing this one okay yeah i mean cool so basically that's the basic of the union fine you know uh yeah so that's that but in order for us to solve this problem like i said we need some other data here like the group we need the counts okay the counts is the count for each of the roots okay and at the beginning you know the count for each root will be one this is kind of easy to understand right because at the beginning each of the route has one count okay and then we have a group count here either group counts or like yeah you can call it group counts here zero and um i think the group counts is also let's see now for the group counts at the beginning it should be zero yeah it should be zero okay and we have n plus one yeah so why we're doing plus one not n here because you see the count is the index right and the count is five and in this case the count is the most count is five okay that's why when we have a group counts five here the n is five right but if we're doing uh five here will be out of the boundaries that's why we do a minor un plus one because the count is one base uh whereas the n here is zero based okay so uh okay so once we have how so how are we going to utilize this these two uh at least to help us maintain that right basically i mean when we union the x and y and we have r1 and r2 okay remember the count itself represents the uh the counts of that root right okay and we have a two counts here you know after we union this these two roots here basically i mean the group counts of those two roots will be decreased by one okay right what i'm say means is this like basically the count of that right so the counts of the r1 right will be decreased by one because those two subgroups is gone basically once when we uh let's say we have one here and then we have a another one here okay and then we have a we and then we add a one here in right in the middle okay so after adding this one here right i mean here we have a count of two here we have a count out of three right and after union this two parts is a cup is the one here right we'll be having like a six here right so the u the new group is six and after we're getting a new group of six okay we know we lost a group of two and a group of three here that's why we need to decrease the for example this is the two group by one same thing for the uh for the other groups okay r2 by one okay and yeah and also you know since we're mainta we have we merged that this is the final one but we also need to update the counts here okay so what does the count mean count means uh the counts of the uh of the basic the root one of the cons equals to root two will become the counts r1 plus counts of r2 oh i'm sorry okay actually here uh i think this example is not a very good one because here we're only merging like two parts yeah so there won't be any of these parts basically only this part only uh the only this side yeah so basically uh so we will have three here so the one is one right so the one is here and then basically we'll be losing the group of one the group of two but we're getting a group of three okay uh yeah and after that right since we have a union those two groups right the counts of the r1 and r2 should be the same right because they should have all have the same counts which is the sum of the r1 and r2 okay and now let's add that the new combined group here okay r1 okay plot plus one right because at this moment since the r1 and r2 are the same it doesn't really matter like which one we'll be uh using we can use either one cool i mean that's basically how we maintain this group of group counts here okay so now we have that structure set uh let's do an answer here so let's try to do the main logic here the answer is this right we start from minus one and we do a step and then the index okay in enumerate array the value here is three here but remember i mean the first thing we need to do is that we have to uh convert this index uh to a zero base remember this thing is like it's one base right three but we uh since we only uh allocate and space here that's why we need to do a index minus one i mean if you don't want to do this i mean you maybe i think you can like uh change this thing to unplus one and plus one okay but in this case i still i'm still keeping the zero base index here okay uh cool so let's see what's next okay so now every time we have a number here right it's a one it means that the groups the group of counts of one is will be increased by one so that's the first thing we need to do here because every time we have one we know okay it's a group of one okay at this moment we have a new group of one okay cool so and now we'll be and now we'll we will try to uh um we will try to uh union with the left side and the right side okay so for the left side uh we have to check the index right basically if the index minus one is still greater than zero then we know okay we can go to the left side but how can we know if the left side is one or not right basically we uh let me think we have to know three yeah basically we need another like uh another like array to tell us okay if this if the left side or the right side has been already has already been set to one okay we can simply have a visited one here right so false to n okay and will be only union when that thing is or we don't if we don't use visited we can also maintain like array here we check if that position has a one or not but the true or false will also work okay or like uh or we can do this like current uh current what's the value here current string okay we can also do this current string okay so and we check if the current string if that's the i the index you know i'll do i here i think index is too long uh is it's shorter okay so if this index right is one right so if this thing is one then we know okay we can union those two the union the uh i and i my minus one okay same thing for the other side i select uh to end and current string i plus one okay oops it's one then we also union that right we're also using the uh in the i and i plus one okay so after that we just need to uh yeah so first let's try let's make these things uh i equals to one okay so we set this one to make first so that the next one can we set the current one to be current position to one so we mark right there's a one at this position now at each at the end of each step we simply check if the groups counts of the uh m right it's still greater than zero yeah or we can skip that and then we answer we update the answer step plus one and then in the end we simply return the answer so here step plus one is like since the step is zero based and the answer is one based okay right that's why we uh we do a plus one here yeah i think that's pretty much it is okay let's let me try to run this code okay cool so this one passed submit oops uh out of index hmm ranks r1 and oops sorry r2 missing an r there yeah cool so it passed i mean uh yeah i mean this thing this one is like it's not very easy one definitely not an easy problem i mean it seems like you know using the union fund is a little bit overkill you know because as you guys can see we have a lot of like codes just to maintain this union find but it's a definitely a good solution i mean so basically okay just to work to recap real quick we are we use the union find template but we are besides the unifying we also maintain like these group counts by using these counts here basically every time we union two parts right we uh we lose those two counts first right and then we get a new we instead we're getting a new bigger counts that's why we uh i mean we keep the counts up for each of the subgroup and then we unite them together and then we create a new counts a new group count and here we just uh using that structure and try to make uh check the value here the group counts value okay so that's that you know actually there i'm going to talk about another uh easier or con more con concise solution here actually that's that one uses it uses a similar uh similar like concept you know but it has a lot well much lesser codes uh okay cool so for that one you know for that one actually the idea is this like basically we have a one right and then we let's see if there's like another side this is the left side okay and this is the right side let's see one okay so this is the right side okay so the idea is like now let's say we have a one here we have a one we're adding a one here basically now we're actually using those left side and right side together okay and uh actually it's using the similar like concept here we're still maintaining like accounts of the group here okay but instead of you of using a union find we simply uh update that you know because at this moment let's see the left side the count is two okay and the length is two on the right side the length is four okay and by union these two lengths together right we have like what we have seven yeah right we have a two plus four plus one which is seven okay so same thing right basically the same thing here so for the when we have one in this group counts here basically we'll be uh removing one we'll be removing uh decrease the number for two by one decrease the number uh four by one but we will be increasing the number of seven by one okay so that's a that's similar okay now the question is how are we how can we get the left side length and the right side length okay so that's the question we need to figure out here and you know in the union fine we use the root right we use the roots to get the length of the left side and the right side but here i mean the here the brilliant the trick here is that uh on each basically um for example on for each of the sub array right for each of the sub group here actually all we need to maintain is the starting point and the ending point if we can just have the latest up-to-date length value for the latest up-to-date length value for the latest up-to-date length value for the starting and the end then we can easily find that because why is that because you know when we try to find the left side right we actually we're looking at the last element of the left the on the left group and when we are finding the right letters the length of the right side we're looking at the first element of the right group okay so for that you know every time when we have like this one uh we have this left and right and we update it right now all we need to do is we just need to we simply need to update the left side the left this one we just need to update this the first element and the last element of our new combined group basically all we need to do just update this one to seven and we also update this one to seven okay because the next time right no matter which one will be using this subgroup it can be either added to here a one here right we can either like combine from here or we can either combine from this side but either side right whenever they're looking for that like the length uh from the start or from the end they will always get the seven okay so that's the trick here basically we don't have to update all the outer the length in the range in between okay all we need to carry we only care the starting point and the ending point okay cool so with that being said let's try to code these things here uh basically same thing we need a length of array right that's the length of array and then we'll be uh we'll be getting the uh we'll maintain a length okay basically that's the group uh let's do a count right so basically the first one will be the counts okay so that counts it's zero times you know here we do an n plus two okay and then we have a group count here right we have group count uh it's basically the zero times uh um unplug n plus one okay so why we're doing like un plus two here because uh we'll be looking for okay basically first we'll be traversing from the first one to the last one and every time we'll be looking for the left side and the right side right so in order to make sure that our index will not go out outside of the boundaries you know we will be adding one buffer on the left side and one buffer on the right side so that uh it won't it will never go out of the boundaries that's why we do n plus two here so here for the m plus one i have already explained that because the uh the index here is the counts okay is the cons so that's why we do one plus one here so now okay uh we have an answer of course minus one okay so now we just need to loop through the this array here so we have uh i the right step and i and then in enumerate same thing here okay so that's that and left right so the left side we have the left count or you can call the left okay let's do a left count here uh counts uh i minus one right remember so we so at because at this moment actually for the left uh left sub subgroup where we're using the last element from the left parts okay and the right count is the count the i plus one so for this one for the right parts we're using the first element of the right part to get counts okay now actually the new counts right so the counts of the um actually now the count of the so now we need to form the new count the new group right and the first element in the new group is this right it's the uh i minors left count okay right because if let's say if there are two ones on the left side and our current is i here right so the beginning of the new group will be i minus left count okay and the end of the new group will be a i plus right count okay and we update those to the start and end by summer like by combining the counts okay right count plus one right now let's update the group counts here right so the group count is the actually we will be losing the original counts right which is the left counts okay right by one and we'll also be losing the right counts by one okay but instead we're getting a new group counts of uh we can use either one yeah the count of i let's use the beginning right beginning of the of this new group plus one okay yeah here we can either use uh i minus this or we can use this one because we they have the same value here and same thing here right basically we just do a if group counts m right and then we do a to answer equals to a step plus one okay right and in the end we simply return the answer okay let's try to run this yeah so this one pass submit yeah as you guys can see this one is like it's faster than the union find it so why is that because as you can see you guys can see so the space complexity for this one is o of n right because we only loop through it once and here it's just a one right and under the space complexity is also of n but for the union find so what how what's the complexity of union fine you know first we have this o n here okay but on each step we have a union so what's the complexity of a unit okay oh first we do a find we do a uh we do a find and the complexity of the find we uh we usually consider it as o1 so i think i briefly discussed about that uh earlier because even though the first find will be o of n but since we were doing this uh past compression you know the next time will be oh so the next time when you look for the same x it will be o of one and when it comes to amortized right amortize the time complexity we consider this one to define to uh o of one and what else we have these things here we do uh that well basically this thing is like you know it's just it's more than uh o of one right i mean it's a little bit like log n maybe yeah i'm not quite sure about the complexity of this unit the unit here because we do a two finds and then we do a uh a uni i think this part is obviously o of one but the union part is like um i mean this part is all of one but the fine part is uh basically it's more than a one maybe a lot maybe o log n uh maybe yeah but okay but for this one it's p is strictly o of n because we don't have that we don't need to maintain this uh this union find the tree structure right we don't have to maintain this root here we simply uh just maintain this two group here by uh by marking the beginning and the end to the with the new length okay so that we can be use it later on because again so when we look for the left side we use the lock the end of the left sub group and when we are looking for the right count we're using the start of the right group that's why we have to update both the left the start and end in the uh so that later on when the new group uh got merged uh both sides will have the correct length okay cool i think that's yeah that's pretty much i want to talk about this problem yeah it's very interesting problem yeah okay cool thank you so much for watching the video guys and i hope you guys learned something yeah and stay tuned and okay see you guys soon bye
Find Latest Group of Size M
people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list
Given an array `arr` that represents a permutation of numbers from `1` to `n`. You have a binary string of size `n` that initially has all its bits set to zero. At each step `i` (assuming both the binary string and `arr` are 1-indexed) from `1` to `n`, the bit at position `arr[i]` is set to `1`. You are also given an integer `m`. Find the latest step at which there exists a group of ones of length `m`. A group of ones is a contiguous substring of `1`'s such that it cannot be extended in either direction. Return _the latest step at which there exists a group of ones of length **exactly**_ `m`. _If no such group exists, return_ `-1`. **Example 1:** **Input:** arr = \[3,5,1,2,4\], m = 1 **Output:** 4 **Explanation:** Step 1: "00100 ", groups: \[ "1 "\] Step 2: "00101 ", groups: \[ "1 ", "1 "\] Step 3: "10101 ", groups: \[ "1 ", "1 ", "1 "\] Step 4: "11101 ", groups: \[ "111 ", "1 "\] Step 5: "11111 ", groups: \[ "11111 "\] The latest step at which there exists a group of size 1 is step 4. **Example 2:** **Input:** arr = \[3,1,5,4,2\], m = 2 **Output:** -1 **Explanation:** Step 1: "00100 ", groups: \[ "1 "\] Step 2: "10100 ", groups: \[ "1 ", "1 "\] Step 3: "10101 ", groups: \[ "1 ", "1 ", "1 "\] Step 4: "10111 ", groups: \[ "1 ", "111 "\] Step 5: "11111 ", groups: \[ "11111 "\] No group of size 2 exists during any step. **Constraints:** * `n == arr.length` * `1 <= m <= n <= 105` * `1 <= arr[i] <= n` * All integers in `arr` are **distinct**.
Use hashing to convert company names in numbers and then for each list check if this is a subset of any other list. In order to check if a list is a subset of another list, use two pointers technique to get a linear solution for this task. The total complexity will be O(n^2 * m) where n is the number of lists and m is the maximum number of elements in a list.
Array,Hash Table,String
Medium
null
1,519
hello welcome to JB's k-school we are hello welcome to JB's k-school we are hello welcome to JB's k-school we are going to talk about the daily question number of nodes in the stop tree with the same ladder um so if you see here um we will have three and then um zero is alphabet a and then if top three has same alphabet a we are gonna return the amount of the subtree and then it has so ub2 and then the one is B because the B his sub 3 doesn't have the B so others are same and then for here 's this software one two three has the B 's this software one two three has the B 's this software one two three has the B so this one is four this one has sub 3 HP so this one is two and then this one is one and this one is the same so we are gonna backtrack to serve this so we are going to start by like four five one and then three six two and then if you go to the zero so when we reach the general yes we already tracked the last of the trees we know how many alphabets they have so we are gonna count the total so first of all we are gonna make the array and then we are gonna put value inside an array so you push it away so for zero give equal to one two for one if you go to zero four five four two equal for zero three six like this and then um as I said like we are gonna keep counting how many are alphabet we have so we are going to make the counter rate so our puppet since alphabet is 26 so we set lands at 26 and then there will be lizard and then we are gonna iterate so iterate from 0 because it's starting point is zero and then we are gonna check the previous one and then we are going to pass this character array so you'll be in the assembly and then character array and then let's put our will be so first of all I'm gonna show you how it will be backtracking foreign like continued because when it leads you to zero four five here we will go to the four this is one then if you back to zero four five again so we want to skip this that's why I like I write the continue here so if you see here so I take something like you will be just backtracking four five one so this Factory is done for zero and the three six two this slot three is down for zero so before we start from zero so we count to the total like how many the alphabet having now so in counter array minus 97 and then keep at the input so since we are going to keep tracking the how many hour probably we have so we are gonna increase this one and then finally the lizard index will be so we know now like how many total alphabet we have so this total arpa band minus this current total and if we learn oh I didn't turn the widget um that's it so the how the way we are serving discussion is we are backtracking from the last of trees node and then we are gonna track how many R public they have and then we already set each part as totar so finally we were subtract from how many alphabets we have from n to total that's everything thank you for watching today
Number of Nodes in the Sub-Tree With the Same Label
minimum-subsequence-in-non-increasing-order
You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` `edges`. The **root** of the tree is the node `0`, and each node of the tree has **a label** which is a lower-case character given in the string `labels` (i.e. The node with the number `i` has the label `labels[i]`). The `edges` array is given on the form `edges[i] = [ai, bi]`, which means there is an edge between nodes `ai` and `bi` in the tree. Return _an array of size `n`_ where `ans[i]` is the number of nodes in the subtree of the `ith` node which have the same label as node `i`. A subtree of a tree `T` is the tree consisting of a node in `T` and all of its descendant nodes. **Example 1:** **Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], labels = "abaedcd " **Output:** \[2,1,1,1,1,1,1\] **Explanation:** Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree. Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself). **Example 2:** **Input:** n = 4, edges = \[\[0,1\],\[1,2\],\[0,3\]\], labels = "bbbb " **Output:** \[4,2,1,1\] **Explanation:** The sub-tree of node 2 contains only node 2, so the answer is 1. The sub-tree of node 3 contains only node 3, so the answer is 1. The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2. The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4. **Example 3:** **Input:** n = 5, edges = \[\[0,1\],\[0,2\],\[1,3\],\[0,4\]\], labels = "aabab " **Output:** \[3,2,1,1,1\] **Constraints:** * `1 <= n <= 105` * `edges.length == n - 1` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * `labels.length == n` * `labels` is consisting of only of lowercase English letters.
Sort elements and take each element from the largest until accomplish the conditions.
Array,Greedy,Sorting
Easy
2316
377
hello everyone welcome back here is Vanessa and today we have a fascinating problem on our hands combination sum four so it's just one that allow us to dive deep into the words of dynamic programming so stick around and by the end of this video you will become a dynamic programming wizard so uh let's start by understanding the problem we have an array of unique integers and we have a Target sum and the task is to find out how many different combination of number from this RI can sum up to the Target but here is the catch the order matter so for example one two and also 2 1 are two different combination so uh we will dive into dynamic programming so now how do we solve this we will use dynamic programming and imagine you are building a pyramid right and the base of the pyramid is when the target is zero and the peak is our final Target and each block of the pyramid is a small problem contributing to the main problem so let's dive into implementation right away so first dp0 times Target plus one and dp0 will be 1. so here DP I um will store the number of combination that make up I and dp0 is 1 because there is only one way to make zero and this is with zero itself so not picking any element so then we have 4 I in range 1 2 Target plus one and four num in nums and if I minus num greater than 0 BPI Plus DP I minus num and return DP Target as simple as this so here is a damaging each DP I is made up of small DP J values and a word J is any number that could have added to a number in nums to make I so yeah and for example if we have nums uh one two and I equals three will be just DP 2 plus DP at uh one so and uh yeah we're returning the result and this is our pyramid Peak so uh let's run it for some test cases to verify it's working so yeah all good and uh a DP Target so this value will contain the total number of different combination that makes up the target so uh what is the time complexity so time complexity is o n times Target where n is the size of nums and space complexity is just o Target so for the DP array because we have a here is space complexity Target plus one yeah so uh let's submit it for unsynthesis cases as well to verify yeah so all good and as you can see our implementation bit 84 with respect to memory and also 74 with respect to uh runtime I think I previously run this code and it was even faster so yeah even 36 seconds but probably it's depend on the test case so for those interested in order programming languages than python I got implementation of this solution in multiple languages like go rust C plus and more so check the video and description for this list and all right so that's it for today and this problem is beautiful example of how dynamic programming can make our lives so much easier so I hope you found this session useful and engaging and if you enjoyed this video please give it a thumbs up share it with your friends and don't forget to subscribe for more awesome uh coding adventure and until next time keep practicing stay motivated and coding
Combination Sum IV
combination-sum-iv
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`. The test cases are generated so that the answer can fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[1,2,3\], target = 4 **Output:** 7 **Explanation:** The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. **Example 2:** **Input:** nums = \[9\], target = 3 **Output:** 0 **Constraints:** * `1 <= nums.length <= 200` * `1 <= nums[i] <= 1000` * All the elements of `nums` are **unique**. * `1 <= target <= 1000` **Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
null
Array,Dynamic Programming
Medium
39
1,047
foreign the problem name is remove all adjacent duplicate instead let us read a description what it says so you're given a string as consisting lower case English letters a duplicate removal consisting of choosing two adjacent and equal letters removing them okay let us in removing them we repeatedly make duplicate removals on as until we are we have no longer can we no longer can be simple return the final string after all such duplicate removal has been made it can be proven that the answer is unique okay so that is what they are given the S is this one which is string a b a c a so the output is a how this output came like B and B are this one B and B are duplicates so we are removing both of them then we came for a after removing this so a will be coming together so a also will removing and CNA will remain at the last so we just need to remove uh for example in this case we'll see you can they have given that we have removed BB since the letters are existed and equal and this is only possible move okay the result of this move is that the string is becoming like this AAC of which a is possible so the final string is CA okay and for this example also x is removed Z is removed a y remains so that is it this simple problem let us try to uh you can pause the video and try to solve it by yourself also hint one thing I can give that you can use a stack for this and yeah you can pause and try to write The Code by yourself so let us try to understand the approach that we are going to be using to solve this problem the approach is that we are going to be using a stack okay so we'll make a stack here so initially it will be empty stack and what we will do we'll start our iteration from here we'll try to convert that into character array and take one by one each values so we have this a so this is also character type stack only so we'll push that a into our stack okay because it is empty we don't have anything so just put this element now again we reach to the B so B also will check that top of the stack is not equals to this current element which is B so we'll push that to here then again when we come for the B we can see the top of the stack is equals to the current character so we'll just remove this so we'll pop it out okay now we're again went for a so a now top of the stack is what a current is also a so we'll pop it out so this is also popped out then again we have C so C is at the top of the stack so we'll remove C we'll put the C there and then we have a top of the stack is C also put a here okay so this values are A and C we can use string Builder to form the strings and see AC will be written from this okay so uh that is the answer that we want in our program there is a small correction that whenever you are iterating the stack it will be like not AC it will be written as CA only so it will read from here from bottom to top so CA will be the returned string from not AC so which is uh matching to our required output okay so that is it now let us try to write the code for this so first thing first we are going to be making a stack in which we'll be storing our characters so I am making a stack for character you can call that as St equals to new stack okay that we have created now what we're going to be doing uh we are going to be iterating in our this one what we call as Str so for each and every value so for I was like for character C in our Str dot to character array okay so for each and every character we'll be having some few functions few things which we want to be doing so first thing that if our St if ever if our stack is empty we don't have anything in this stack so we'll be doing first thing which is SG St Dot push that character which character C character else if our stack it's not and if you have something you know stack so we are going to be checking that if our St dot Peak which is the topmost element becomes equals to C at that time will be just popping that element copying basically the stack the top of the stack and else part will be just pushing that into all this one else St dot push will do the character C so these things we'll be doing after this one will be making a string s or answer string okay and what we'll be doing will be just iterating in this stack for character C in our stack SD okay take each and every value and add append it to the C appendicular answer and just return the answer from here okay let us try to run the code for this it's successfully accepted let us try to submit the code as well solution code will happen from here so it is clear separate let us try to understand one more uh way one more thing one more like again seeing the problem so we have stacked we have created a stack here we have just the character stack for each and every character we are vibrating we are checking three conditions if it is empty we are just pushing that if the top of the stack is equal to the current um character we are just popping it if and in else condition we are just pushing that any new values new characters in double stack and uh we are just simply creating an answer string and uh iterating in each in our stack and taking values and just appending and returning the answer so that was a simple problem so that's it for this video if you've got the basic idea of the problem we'll meet in the language unless this problem thank you for watching foreign
Remove All Adjacent Duplicates In String
maximize-sum-of-array-after-k-negations
You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them. We repeatedly make **duplicate removals** on `s` until we no longer can. Return _the final string after all such duplicate removals have been made_. It can be proven that the answer is **unique**. **Example 1:** **Input:** s = "abbaca " **Output:** "ca " **Explanation:** For example, in "abbaca " we could remove "bb " since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca ", of which only "aa " is possible, so the final string is "ca ". **Example 2:** **Input:** s = "azxxzy " **Output:** "ay " **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters.
null
Array,Greedy,Sorting
Easy
2204
53
hello everyone in this video we are going to discuss the solution to the problem max zoom suburi the description says that given in integer n announce find the continuous every containing at least one number which has the largest sum and return it's some so we'll look at the example so the example is this we have to return a continuous survey which has the largest sum so if we look you can try finding each survey starting from each index let's say we are starting from the 0th index and the sub areas are - - 0th index and the sub areas are - - 0th index and the sub areas are - - another separate could be -2 + 1 then - another separate could be -2 + 1 then - another separate could be -2 + 1 then - 2 1 - 3 - 2 1 - 3 + 4 like this there 2 1 - 3 - 2 1 - 3 + 4 like this there 2 1 - 3 - 2 1 - 3 + 4 like this there can be n such sub arrays then we can look sever is starting from index 1 - look sever is starting from index 1 - look sever is starting from index 1 - 3 1 - 3 4 similarly we will keep on 3 1 - 3 4 similarly we will keep on 3 1 - 3 4 similarly we will keep on going and we will have n minus 1 such severe is now if we keep doing this process we will end up generating all the possible sub arrays and then finally we can find the answer using Big O of n square time complexity so this way you will be able to find the answer so answer in this cases starting from 4 till 1 so from 4 till 1 this is the same array which we are looking for but there's another optimized approach which uses a famous algorithm well-known uses a famous algorithm well-known uses a famous algorithm well-known algorithm called Caddy's algorithm you will try to simulate cadiz algorithm using the same example so the algorithm goes something like this initially we are having an empty bag with us and our answer initially will be in min or negative infinity now we will put each element one by one into our bag starting from the 0th index now inside the bag we have negative two we will what we will do we will maximize our answer now the answer becomes minus two next we are having one now as the bag contains a negative element which is a baggage for the next one so what we are going to do we are going to empty the bag here itself so emptying the bag will give us zero inside the bag the next element is one so now the bike contains one answer becomes one now in the next step there is minus three putting this inside of our bag will give us minus two now answer will remain one itself and as the bag is negative we are going to again empty two entire bag and it will become zero next step we will have four now the answer will become four then we will have three answer will not change next step we will have five in this case answer will change answer will be five then we get six in the bag we are here so adding one in five will give us six the answer will become six next we have minus five which will give us one inside the bag and next we have four which will give us fine inside the bag now we have to verse the entire array and the maximum which we got is six so six is the answer in this case why we are doing this step or this step when we are having something negative inside the bag we are going to leave all the elements which are previous to this let's say suppose in this example we were starting from two and then making this array now the sum was minus one if we start from here now if we leave this part and start from here the sum will be one now let us consider up to here if we start from negative two and there are still four we will get zero but if we start from one and Trevor still four will get two in this case so we are going to leave whatever part is giving us the negative sum similarly when we were here so when we came up to here the sum was minus two plus -3 minus here the sum was minus two plus -3 minus here the sum was minus two plus -3 minus 5 and then 1 which is equals to minus 4 we left this part and we made the bag zero so we are leaving the negative part so this is what we are doing in cadiz algorithm so this was a pretty simple problem you could try solving this yourself the code is pretty simple if you are unable to solve then you can look at the code so we are initially having our answer as int min and sum is equals to 0 we will traverse each element we will add keep adding those elements in the sum and we will maximize our answer Unser's equals to maximum of previous answer and the current sum if the sum is negative we will make it 0 and finally we will read none of our answer so this is it for this problem thank you
Maximum Subarray
maximum-subarray
Given an integer array `nums`, find the subarray with the largest sum, and return _its sum_. **Example 1:** **Input:** nums = \[-2,1,-3,4,-1,2,1,-5,4\] **Output:** 6 **Explanation:** The subarray \[4,-1,2,1\] has the largest sum 6. **Example 2:** **Input:** nums = \[1\] **Output:** 1 **Explanation:** The subarray \[1\] has the largest sum 1. **Example 3:** **Input:** nums = \[5,4,-1,7,8\] **Output:** 23 **Explanation:** The subarray \[5,4,-1,7,8\] has the largest sum 23. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` **Follow up:** If you have figured out the `O(n)` solution, try coding another solution using the **divide and conquer** approach, which is more subtle.
null
Array,Divide and Conquer,Dynamic Programming
Easy
121,152,697,1020,1849,1893
1,415
hello so today we are going to look at this problem called k happy string of length n so the problem asks us to return the k happy string of length n such that a string is happy if it has these two conditions first the letters in the string are only a b and c and there are no adjacent letters that are equal as in for ev for all the indices of i um s i has to be different than s i plus one and so we want the k happy string of length n so we are considering only the strings of length n and happy means has only these characters here abc and there are no adjacent letters that are equal right so if we take an example here with n equal to 3 and k equal to 9 all the happy strings of length 3 so what we want is the ninth happy string of length three right so all the happy strings that we can construct from abc of length three are aba abc aca acb you get the idea and so here um one thing i should mention here is cave in sorted lexicographical order right so they need to be sorted so here you can see they are sorted um and the ninth one since we can't have a for example because that value is this condition right so let's just enumerate these so this is one and this is two right and so here um they are sorted and if we pick the ninth one two three four five six seven eight nine this is the ninth one in sorted order and so we could just return we should just return that cab right so that's the idea um now let's see how we can solve it um okay so let's see how we can um how we can solve this problem so um one thing that the problem asks us to do is implicitly just enumerate all the eliminate the strings um of line three the happy strings of length three right so in the example that we um that we explored that we saw earlier we had n equal to 3 and k equal to 9 right so this was the first example and in that example what this would mean is that we want the ninth happy string of length um three right so what this would mean here is that well we will need to generate them right so what we do is we say okay let's generate them in generate all strings of length n that obey um one and two right the two criteria that we mentioned in the problem and take the kth one well one caveat one thing that we need to mention there is we want them in sorted order in lexicographically sorted order graphical sorted order and then we will need to take and take the k um string right so this is the gist of the problem right and so um to do that for example for n equal to three well we want to generate all strings of like three that obey one and one in two so let's just write down one and two here so that so one is that um so one for us is um characters right characters have to be in the s set a b and c right the second um requirement is that well we want s i to be different than s i plus 1 for all i in the range 0 and length of s minus 2 right minus 2 because we want to be able to get the take the i plus 1. um right and so now for now we know the what the problem asks us to do here um for example one if we go back to our example one right we had n equal to three and k equal to nine so for that one um if we try to just enumerate them down and see what we can do there so we have a b a we can't take a because that violates two we can't take aaa again that's val is two so the only thing we can take is a and two different letters a b and a c this one is the first one and so the we have aba abc and let me just and then aca but how do we take them like how can we take them in sorts of order so we have this abc right so we can do is well let's just take a and then now we have to take only from b and c so let's take from the first one they are this is sorted order right so let's just take in the assorted order then and so the we take a and then we choose from b and c so we have to take b first and then we have c first c here but for this one well we have only c left so we take abc now this has length three so this is one of the candidates right and then this one well if we choose c then the remaining is just b so we have acb so this is our second one length three so this is our second one so this is the first choice second choice and then once this we finished exploring uh a first so now we explore b first uh sorry i forgot to something here so for a b once we put b now we can take a again because we don't have the constraint of s i different than s i plus one violated and so here we could take a b a as well and here we could take c we can take a again so we have aca as well right and so actually what would happen is that this is two and this is one this is the first choice this is two uh so let me just clarify this a little bit more so first we take a we have the choice to take only b and c because of two and so we take b and then we have c now here we have the choice to take a and c right because b because of b we can take a b again so here we can take a and c so we have two choices a b a and a b c right for this one well we have the choice to take a or b right so we take first a gives us aca and we have the choice to take b so acb right and so this is the order we have one two three four right so the order is always you take one the one that we just place it we don't consider it we skip it but the order is still the order in this array here so this is a very classical backtracking um problem right because we will need to enumerate all the choices and we will need to skip some of them um but the main idea here is enumerating all the choices and so how can we um solve this with backtracking so backtracking requires us to um find a couple of things so first the base case right um what is the what are the parameters that we need to pass to our recursive function let's call this our state here and then the second thing we need to do is how are we going to recurse right and in this recursion we will need to make a choice then explore then and choose so it's called this choose instead explore and then choose this is the general template of solving backtracking problems let's first focus on the state here so to be able to determine if the string is a happy string right of length n we need what we've chosen so far let's say for example at this point we need to know that we have chosen a b so far right and so we need the chosen so far and then we also um with the chosen we can determine the length right so we can determine the length if we should end or not um and so our base case here is if we the chosen the length of the chosen string that we have so far is equal to n that means we are done right um that means that's potential candidate we just need to check if it's the k string or not right um and that's pretty much all we need we just need to pass the chosen so far we could have said like for example test the remaining length so for example if we have chosen let's say 2 and we are looking for strings of length one we can pass the remaining length as one but that's not needed because we can infer that from the chosen length right from the chosen um string length now what is the choice well the choice is just picking one of the string right so the choices we have at this point are every time it's a b and c right but we just need to skip the one that occurred before so that we don't violate two so the choices are a b and c every time because we have repetitions because we allow aba right but skip if chosen the last character of chosen right last character uh is equal to the choice right whatever string we chose we need to skip because if we are at a b we can choose b so we have to skip it if we are at ac we can't choose c because that will validate two so we'd have to skip it and so when we're choosing what do we need to do well choosing just means that we add the character that we chosen let's call the choice here ch well we need to add that one to the choice right and in python we can just consider this string as an array and add an array of one letter so that we can concatenate them and the exploring here would just mean calling whatever our recursive function is let's call it helper with this choice here right and then choosing means if we modify so let's say we modified chosen so we passed chosen here then we will need to remove this character so we'd have to say chosen.pop which would have to say chosen.pop which would have to say chosen.pop which would remove the latestly added character and that's pretty much it we have our base case our state we know how we will recurse so we can start writing our function now um so our function let's call it kth a happy string and we pass n and k right and so we need our recursive function here the scores helper so our recursive function let's call it helper and we need to pass chosen the state that we mentioned earlier and our base case as we said is if the length is equal to n we will need to do something process it basically check if it's the kth and then um if it's the case use that we will do that later but in the else case let's give some space here and in the else case we want to explore all the choices which are as we said order letters in abc right and then well we want to check if we need to skip right but we need to skip only if chosen already contains an element if we are at the start and chosen is empty we can pick any element right a b or c so only if chosen is empty in python we could use that with not chosen or if the last character we can do minus one here in python is different than the current choice then we can process it if it's equal we skip so we can protect it with this choice here and so if it's not equal that means we are good with the second condition here two um then at that point we can um we can recurse right so we could do chosen here right and just add to that the character that we just chose and then call helper with chosen and then and choose here by saying chosen. so this is our choose step this is our explore step and this is our and shoe step so this is what backtracking does and then this is the base case here and now we need to um set up the function call so just before writing that function here we will need to launch the call right so initially the first call a helper is the chosen is just an empty list right we haven't chosen any letter so chosen it's empty list but we need to determine when we have reached the um when we have the um the k um the kth string right the case happy string so one way we can do that is just keep a counter of them right and then keep this is the case we will set it when the counter reaches k so initially just an empty string because that's the default that the problem wants us to return if we can't find um a k happy string and so we return that here and now in the base case processing we can just check if so we need to increase the counter because we found a happy string here so that would mean here initially we will need to say self dot count plus one and then check if that's the kth one um at that point we can assign the k string to be equal to chosen right and that's pretty much it and yeah so this case backtracking but here with exploring the choices skipping those that we shouldn't uh process and then doing the two step explore step and then the intro step and the at the end return the result here um so yeah so that's a pretty much actually for this problem now let's write it down um run it on an example and try to improve it a little bit um the solution that we just saw in the overview so the main um so the main thing here is this backtracking function here um we initialize the call by passing into an empty list because that's the first initial um chosen that we start with and then we explore we try first with um so here we try the choices first with a and then we from a we try to get b this two other characters and we satisfy the second constraint here so that no two um adjacent letters are equal so if they are equal we skip otherwise we explore um and here i just optimize it so before we had something like this where we did this and past chosen and then we do chosen.pop so it's clear and then we do chosen.pop so it's clear and then we do chosen.pop so it's clear but actually adding it this way and removing is the same as just passing here that way we don't modify chosen in place but we pass the modified version right so this is the equivalent to that um also we could instead of skipping here we could just only explore if either the chosen is empty or if we didn't we are not violating the second constraint right so we could do that as well um so i have here a couple of examples that we can make sure it works so for string happy strings of length n to get the third one we should get b a and for half piece strings with length five the eighth one is this one um and so let's just run it confirm its works it works for all of them so that's great um now one thing we may not like is this self dot case here so to avoid doing that we could definitely just pass as a res here and at that point instead of we could just add it right so that's another way to do this so we can just add it like this and here we could just say return res at position k -1 right so we can start the index from -1 right so we can start the index from -1 right so we can start the index from zero um let's see that it seems to be let's print rest and see let's just start with the first example yep so the problem here is that the string that we added is not is a another way right so we need to join it first so we can do it this way and that gives us what we want and so if we try that again it passes right so let's try with all of them and remove the print all of the test cases pass right so that's one way to do it um we might also want to if um the length of res is equal to k we might want to return because there is no need to explore we need just k so we can stop there so at that point we could stop and then here just to make this look consistent just written there and have this like that and this should work the same way right it should all pass cool so this is so that we could um return and not explore after k because we are only interested in the k element um and yeah so that's it for the backtracking solution next we will see how we can solve the same problem using bfs um we can solve it using bfs so let's try that um okay so i have here the solution that we just saw in the overview so the next letter is for each letter and then we start support this import at the front here and then we start our bfs procedure with the queue here with the dq so that we can pop from the front and add to the end and then for each node we look at the neighbors which are the possible characters for the last character that we have so far in the node and so we get those are the neighbors we add them and then we add them to the queue and then at the end we are at the last level which is the level where strings have length n because of this while loop for condition here and then we pick the kth um string if we have k at least k strings otherwise we just return the empty list um and so let's just run this on the examples and it passes still fine cool um yeah so that's it for this problem we solved it using two methods backtracking and using the um using a bfs here yeah so that's it thanks for watching and see you on the next one
The k-th Lexicographical String of All Happy Strings of Length n
students-and-examinations
A **happy string** is a string that: * consists only of letters of the set `['a', 'b', 'c']`. * `s[i] != s[i + 1]` for all values of `i` from `1` to `s.length - 1` (string is 1-indexed). For example, strings **"abc ", "ac ", "b "** and **"abcbabcbcb "** are all happy strings and strings **"aa ", "baa "** and **"ababbc "** are not happy strings. Given two integers `n` and `k`, consider a list of all happy strings of length `n` sorted in lexicographical order. Return _the kth string_ of this list or return an **empty string** if there are less than `k` happy strings of length `n`. **Example 1:** **Input:** n = 1, k = 3 **Output:** "c " **Explanation:** The list \[ "a ", "b ", "c "\] contains all happy strings of length 1. The third string is "c ". **Example 2:** **Input:** n = 1, k = 4 **Output:** " " **Explanation:** There are only 3 happy strings of length 1. **Example 3:** **Input:** n = 3, k = 9 **Output:** "cab " **Explanation:** There are 12 different happy string of length 3 \[ "aba ", "abc ", "aca ", "acb ", "bab ", "bac ", "bca ", "bcb ", "cab ", "cac ", "cba ", "cbc "\]. You will find the 9th string = "cab " **Constraints:** * `1 <= n <= 10` * `1 <= k <= 100`
null
Database
Easy
null
43
the multiply strings problem on Lee code asks you to multiply two given strings representing non-negative integers here representing non-negative integers here representing non-negative integers here are three approaches to solve it you can use the Brute Force approach where you convert the input strings to integers perform the multiplication and convert the result back to a string this approach has a Time complexity of Big O of n times M where n and M are the lengths of the input strings grade school multiplication you simulate the multiplication process as you would do it manually creating a right to store the intermediate results and perform digit by digit multiplication this approaches a Time complexity of big Over N times M but it uses additional space optimize multiplication use the carissable algorithm to perform efficient multiplication of large numbers these algorithms divide the numbers into smaller parts reducing the number of multiplications required they have the time complexity of Big O of n log n where n is the maximum of the lengths of the input strings
Multiply Strings
multiply-strings
Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string. **Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly. **Example 1:** **Input:** num1 = "2", num2 = "3" **Output:** "6" **Example 2:** **Input:** num1 = "123", num2 = "456" **Output:** "56088" **Constraints:** * `1 <= num1.length, num2.length <= 200` * `num1` and `num2` consist of digits only. * Both `num1` and `num2` do not contain any leading zero, except the number `0` itself.
null
Math,String,Simulation
Medium
2,66,67,415
798
so uh uh so uh uh so so up could you give us a chance oh love one day that's how you feel you win we should just is is i my so two please so you foreign uh this um so so so um oh so bye so oh so so so so so [Laughter] [Laughter] [Laughter] huh uh uh oh yes uh thank uh you
Smallest Rotation with Highest Score
transform-to-chessboard
You are given an array `nums`. You can rotate it by a non-negative integer `k` so that the array becomes `[nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]]`. Afterward, any entries that are less than or equal to their index are worth one point. * For example, if we have `nums = [2,4,1,3,0]`, and we rotate by `k = 2`, it becomes `[1,3,0,2,4]`. This is worth `3` points because `1 > 0` \[no points\], `3 > 1` \[no points\], `0 <= 2` \[one point\], `2 <= 3` \[one point\], `4 <= 4` \[one point\]. Return _the rotation index_ `k` _that corresponds to the highest score we can achieve if we rotated_ `nums` _by it_. If there are multiple answers, return the smallest such index `k`. **Example 1:** **Input:** nums = \[2,3,1,4,0\] **Output:** 3 **Explanation:** Scores for each k are listed below: k = 0, nums = \[2,3,1,4,0\], score 2 k = 1, nums = \[3,1,4,0,2\], score 3 k = 2, nums = \[1,4,0,2,3\], score 3 k = 3, nums = \[4,0,2,3,1\], score 4 k = 4, nums = \[0,2,3,1,4\], score 3 So we should choose k = 3, which has the highest score. **Example 2:** **Input:** nums = \[1,3,0,2,4\] **Output:** 0 **Explanation:** nums will always have 3 points no matter how it shifts. So we will choose the smallest k, which is 0. **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] < nums.length`
null
Array,Math,Bit Manipulation,Matrix
Hard
null
139
hello everyone welcome back myself rahul so today we are going to solve a problem related to recursion so the problem name is word break so it's very simple problem let's go through the problem statement uh here we are given a string s and a dictionary of strings word dictionary we have to return true if s can be segmented into space separated sequence of one or more dictionary words note that the same word in the dictionary may be reused multiple times in the segmentation so we are given a string called suppose lead code and there is one dictionary is also given with the strings as lead and code so we just basically need to check whether the given string can be formed using the words present in the dictionary so the lead is present in the dictionary c o d e is also present in the dictionary so we have to return true in this case the other example can be apple pen apple so apple is also present in the string then if i see pe and pen is present then apple again is also present so here as well we will return true right so we have to see like whatever there can be multiple combinations but uh if there exists some order in the word dictionary based on which like if our complete string gets covered right if it gets completely covered then we have to return true otherwise we have to return false right so i guess the problem statement is clear so i will try to explain uh how recursion can be used in this problem with an example so let me take a example over here so let's suppose the string is a b p e n a p right and uh yeah so let's take an example string is uh a b e n a b right so this is the given string to us and what is the word dictionary given to us let's suppose the dictionary given is uh p is one of the words then a p e and pen is one of the words and ap is one of the words right so are we able to compute this whole string using these words in the dictionary we have to basically check that right so first word is p so if we go via this a p e so it is present but naap like till this part it is present but uh nah is not present but if we take instead of a p e if i take just uh suppose first two characters ap then p e n uh yeah still here as well like i am not able to cover a b right so here i will be returning false so like how the recursion will come into this picture problem is i will try to uh draw a recursion tree so we are given a string a b p right so we have to tell whether we are able to construct this whole string using the words in the dictionary or not so this length is one two three four five six seven eight right the length of the string is eight so it can be the case that like if we draw a recursion so can be that like we take the first seven characters and one after that one character separately so it can be that like we are taking seven plus one characters like we are creating the first seven characters string first and the other last character separately right so if we are somehow able to construct this string and this string separately then both of these would be returning true to the original string and finally we would be able to create the original string right so if we are able to create this string independently then obviously would we would be able to create the actual string independently correct so this is one way of uh breaking this problem the other tree that we can create over here is like instead of seven plus one we i distributed six plus two so i take the first six characters a b p and a this is the these are six characters and other two characters ap separately right so if we are somehow able to create a p n a from this from the words present in the dictionary and i'm able to create ap as well using the words in the dictionary then both of these will be returning true and finally i will be able to create the original string right so this is one part of the recursion tree this is the separate part of the recursion tree similarly i have breakdown into six plus three if i use first three characters first five and then three right so if i use first five a b p e n so this is one string and the other string would be a b so for this string to be returning true both of these has to be returned as true which means this string has to be constructed independently using the words in the dictionary and also this string as well right so let's go down a bit in the same recursion tree so suppose we are at this part of the recursion tree we further so this length is seven so if seven can further break down into six plus one right so here the string would be a b p and a and the other part would be a this is one recursion tree similarly for this it will be five plus two similarly it will be four plus three right so there will be multiple recursion trees created over here so one thing uh we have to notice over here is like firstly like this actually this tree would also be further distributed like this length is uh 6 right so we can distribute it in 5 plus 1 4 plus 2 3 plus 3 but one thing to note over here is when we are distributing this right so this problem statement a b p and a p n a this statement this substring is also present over here so somehow suppose like we are able to uh solve for this recursive tree and it has finally returned falls to the original string and then we are going to the second part of the recursion which is this branch like this branch is already solved we are coming to this branch right so here as well we are again computing whether this string is present in the word dictionary or not so here we would be recomputing what was already computed over here so that's why it's kind of overlapping sub problems so like the sub problems are overlapping like whatever we have computed in the past can it somehow be used in the future as well so that's why this recursion can be converted this problem of recursion can be converted to a dp problem right so that's where our using the dp solution comes into picture so that's where we develop the intuition of using dynamic programming all right so now like we are a bit clear like why we have to switch from recursion to a memorization approach like let's see like what thing we have to memorize basically right so suppose we are given a string a b e let's take this example only right so we have to tell whether this string can be conver can be created using the words in this dictionary or not right so if we somehow break this string into two problems two sub strings suppose this is a string and i break it over here right so what i need to do is i need to see whether this substring was present in the uh word dictionary or not and also whether this dictionary was whether this substring was present in the dictionary or not right if both of them were present then only i will be returning true right if but even one of them can't be created the words in the dictionary then i have to return false so can i uh start like can i use a bottom up method approach over here in which like if i have to create a string of length x then if i somehow know all the sub strings like status of all the substrings whose length is less than x whether they can be created using the words in the dictionary or not so let me like i am going to create one array of the same length as that of string so here the length of the string is three four five six seven eight right two three four five six seven length is eight so the iron length is seven right so this is the extra space that i am going to use so the value add a particular index in this new array is going to denote whether a string the input string can be created till this particular index so suppose i am at the ith index suppose i is 2 which so this index is going to tell me whether i can create a string from zeroth index to second index using the words in the dictionary so i'm going to start from the zeroth index so zeroth index just contain a so whether a is present in the dictionary or not no it is not so i am going to mark it as 0 then i comes at index 1 so string present between 0 to 1 would be ap so i will see whether ap is present in the word dictionary or not yes it is presents and i am going to mark it as one denotes that string present between zero to if index is present or can be constructed using the words in the dictionary then i am going to the second index the string would be a b right so whether a p is present no it is not then what i need to do over here is uh i need to see like here the so here suppose my i is at this particular index and i already know the status till this point of time right using this tp array so my new index is at this particular p so firstly i see whether the new string app is present in the uh input array or not over dictionary or not it is not present then not an issue what i am going to do over here is i will create one variable called j which will be initialized to this index only and firstly i will see whether a string present between 0 to j is present in the word dictionary or not so string present between 0 to j is app only so app is not present in the word dictionary then it is not an issue then i am going to decrement j by 1. so j will come over here so i will see again whether string is present between 0 to j which will be a of ap so whether ap is present in this word dictionary or not so for that i don't need to again look into the word dictionary i can reuse the new dp array which i had created using this index because this index was denoting whether ap string can be constructed using the word dictionary or not right so basically we are reusing whatever we had stored earlier so a b was value one right so i am able to construct a string a b and uh right so i had gone basically zero j is over here i minus one so zero to i minus one has been covered then i need to cover basically 0 to j has been covered then i need to cover j string between j to i as well right so the string between j 2 i is just p so p is also present in the word dictionary right so it will return true so i'm returning basically true from both the places so i will mark this also as one i hope this step is clear right then i am going to increment i will move over here i am going to check whether app is present in the word dictionary or not yes it is present then i am going to mark it as one uh then i am going to see a pb en then i moves over here so a b e n right so i is over here so this whole string is not present in the word dictionary then not an issue i will create one variable called j which will be initialized to this particular index and i am going to see whether a string is present between 0 to j in the word dictionary or not it is not present then i am going to decrement j will come out 2 over here so string between 0 to j would be a ppe right so this string whether this string is present in the word direction you are not we don't need to look into the word dictionary again we can again reuse whatever v values we had populated so this value over here one is basically denoting whether a p e can be constructed using the word dictionary or not so it will return true so string between 0 to j is a p b e so it has return 1 but string between j to i which is nothing but string n it is not present in the word dictionary so it will return so 1 and 0 if i take the end of that it will give me 0 so i will populate 0 over here so in this way i am going to populate that my dp array and whatever the value of my last index is it will tell me whether the whole string can be constructed using the words dictionary or not i hope the solution is clear so i had already written the code for this i will try to explain the step by step yeah so here we are given a words dictionary and a string s so instead of like uh always checking in the word dictionary whether a word is present in this dictionary or not i've created a set in which i am going to insert this word dictionary elements strings so that uh the lookup time doesn't come out to be the size of the word dictionary on an average basis if i look a string into the unordered set it would come out to be one right so this is a string and in this is a set and in this set i am just inserting all the elements present in my dictionary then i am going to iterate over each individual index like one by one and i'm initializing one variable j which is nothing but the current index only right and i'm going to do this process till j is greater than zero so i had told you that like i will be decrementing j right so i have the decrement operation has to be done till the point j is uh greater than zero right and one check i put over here is if i is equal to j which means like i have initialized j as i only so if j is equal to i which means that uh basically i need to check the complete string into the word dictionary right so here i'm checking st dot find whatever the string is present between 0 to j plus 1 eth length so sub str is the stl provided in the string so this is the first argument in this sub str function denotes the starting index of the search and the second argument here denotes the length of the string so i am going to start from the zeroth index and the length of the string to be considered is j plus 1 right so in that way i will be reaching jth index if i start from the zeroth index if it would have it was one over here then i could have just placed j over here but it is starting from the zeroth index then that's why i have to put j plus 1 so i'm just checking whether this string is present in the already defined set is nothing but the new version of word dictionary so if it is present then in that case i'm marking the new created db array for that particular index as one and i can break the value from that particular point right if i is not equal to j which means that this complete string is not present in the word dictionary i need to decrement j somehow right so firstly i need to see whether the dp of j like i had already decremented j by 1 over here so if i was initially equal to j and this if condition wasn't executed then i would have reached over here and j would have decremented right so if this is the string i is over here and j would have been one value less than i so this exit condition would have been executed and i would be checking whether dp of j is 1 or not dp of j equal to 1 denotes that uh that the substring between substring 0 to jth index can be constructed using dictionary words if this is equal to 1 but if it is not equal to 1 which means the substring present between 0 to j can't be constructed using the word sectionary right so suppose if we can construct a string between 0 to jth index so we also need to check the remaining substring which is present between the j to i so that's what we are doing over here st dot find and in that case like we are updating the dp of i is equal to 1 and if both of these conditions are valid then i am marking dp of i equal to 1 and breaking the while loop right and if we have reached the starting of the array and till this point the dp of i hasn't been marked as 1 then i can just mark dp of eyes as 0 which means that substring cannot be created using the words in the dictionary right so finally i have to return basically return the last value present in the dpn s dot size minus 1 denotes the last index right so i will run this code yeah i will remove this c out statement yeah runtime and memory usage are also fine so like it was a very uh very good problem related to dp and recursion so i will recommend you to draw the recursion tree that i have drawn over here and try to understand where we are generating the overlapping sub problems and why do we need to specifically jump to the uh db part dynamic programming part because like here we have overlapping sub problems and if we somehow maintain the results that we have already solved for then we can somehow use those sub problems in the coming calculation of the greater problem right so i guess yeah you are clear with the solution so for this the time complexity would be like if we are at a particular index we are going through all the previous indexes so the time complexity for this would be of n square the space complexity would be of n only time is of n square and space is of n right i guess this is the optimized solution and if you guys have any better approach to this problem please do comment and i hope the solution is clear and if you haven't subscribed to the channel please do and i will see you next time with another problem thank you everyone
Word Break
word-break
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\] **Output:** true **Explanation:** Return true because "leetcode " can be segmented as "leet code ". **Example 2:** **Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\] **Output:** true **Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ". Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** false **Constraints:** * `1 <= s.length <= 300` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 20` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**.
null
Hash Table,String,Dynamic Programming,Trie,Memoization
Medium
140
312
200 Chanting With Another Problem In The Calling Series Welcome Guys Stress Problems For Best Payday Loans Guitar Level Problem Width Like Basu Many People Admit Quite Interesting Infection Let's Give In The Next 20 - And Prohibition Painted With The Numbers Next 20 - And Prohibition Painted With The Numbers Next 20 - And Prohibition Painted With The Numbers And Represented By Are Not Absolute Terms In Terms of its OK 100 - 110 In Terms of its OK 100 - 110 In Terms of its OK 100 - 110 to 120 grams Paneer 181 quarts What we do it is back to find how they can gather Maximum various forms where given answer for this slow induce water treaty setting one first features setting on embroidery 2128 elements to multiply Is the element 19321 25 attributed since 2009 0253 * * * * * 324 323 341 323 12818 0253 * * * * * 324 323 341 323 12818 0253 * * * * * 324 323 341 323 12818 points 69 hai to electricity interested no the order of australia de give the answer but he give to your mind will simply any other roadways just stand for in 3.5 Days But Will Not Get stand for in 3.5 Days But Will Not Get stand for in 3.5 Days But Will Not Get Maximum Volume Points Criticizing Less Than 160 70 Correct Order Of What You Have Given You Will Have To Now Is Dynasty Versus Divided In Three Dhan More Basically List Right To Find The Logic Mode On Inch Montu Coding Slept With 900 Just A Random elements of two or three and powers are not absolute must satisfy this aspect declare variables and two declarative what does this mean that all we have elements with an example 12512 31-01-2014 800 alto 800 properly to make it easier for me to go In This Way Yog Invented Ok Sur This Is My Home Made Tricks And Improves Us Hero Kamar 0m 120 Eighth Class Twelve Acting Celebrate And Quort Look Name 2126 Element In Waiting For Ur Looking For A Job In The Valley Dash Liquid * * Series Page Job In The Valley Dash Liquid * * Series Page Job In The Valley Dash Liquid * * Series Page 4 Sale 20118 A Horrible Element Is Dare And Desert In Next One Ok In Ubuntu Linux Element In K Insiders Balloon Three Days Foreign 2325 Discern This Person Then * 325 667 26 May DP Discern This Person Then * 325 667 26 May DP Discern This Person Then * 325 667 26 May DP Table Live Word Support Cyber ​​Affair Table Live Word Support Cyber ​​Affair Table Live Word Support Cyber ​​Affair Blast Ok All Right In The Same Color Gimmick Joker Subscribe To Make Consisting Of Elements Battu Class Twelfth Bus Stand To The Volume To Entertain Will Be 12336 OK Plus Seat Belt Tighten Last Date For Withdrawal From The Satanic Verses From The One More David 3000 1000 131 211 To 231 seats from getting into foreign tours side now bus stand to already 2522 the well that we can see from this and defeated after 0 comments road 800m 120 to isse zor in the temple complex Delhi Twenty-20 slaves in that complex Delhi Twenty-20 slaves in that complex Delhi Twenty-20 slaves in that You Will Not Change 3331 Reminder Table OK Morning WhatsApp To Find The Maximum Per Of Form For Joint Secretary Candidate Surat Is Greater Than The Will Destroy The Evil Act Me Uda Gaye Sabari Super Cars Bhare My First Inductors Backem One Of Us Can Access Welcome To Front They can even give examples for this NGO's name moving forward there way into a as well as for the last three subscribe * * * * last three subscribe * * * * than body bus stand 300 bursting three daily point se target will be easy for that pati jatin text-22 waist 260 rate fifty jatin text-22 waist 260 rate fifty jatin text-22 waist 260 rate fifty plus to z f one waist to record started one and engaged in next to ok in this website by third last in that case 23.25 6 to 53030 point to 0ld case 23.25 6 to 53030 point to 0ld case 23.25 6 to 53030 point to 0ld just and only and reset inductive winner debatable one going ICOS Roadshow 15r Will Be Appointed Versus Story Are Nominated For Salaried The Validity Nurses Or Let's Move Forward To The Next Now Are Diverted Swinton A Prosperous Tagged I Will Get The Benefits Of 2014 It Will Be Straight Line One Question File Also Versus In Cases And Arresting Serial Blasts Youth Also Foreign 2321 April Plus Form Busting 504 506 323 Waist Three Layer 715 In Ru Temples Him Loud Districts November Cigarette Blast In That Case Point To Point 2 F Butting And Worms Three Idiots 2128 Straight Grade Pay 2400 OK So IF They reduce elements for all the length of quick shampoo change I length 2391 details December 19 length 360 The summary of evidence from where it starts from or is it next to right in defiance starting and ending in the history of cases in which enables one to another In Vitamin B12 The Best For Class Five What Is The Value Of Elements To Give The Element Why Element Please Give Me The Best 2518 Elements With The First Subscribe Now To The Value Of Time 15122 * Fight Will Be 200 Okay Plus The 15122 * Fight Will Be 200 Okay Plus The 15122 * Fight Will Be 200 Okay Plus The Value Of Quality Testing 4343 Returned Guidance From The Forest And Deductive With Our So In The Table Of One Two Hundred Dresses To Consider Som Vikram 0002 Subscribe To Next9 Forward Next 9 News Room Se Viewers Welcome To Points On I Let Me Right Side Clearly Or In The Morning Just for last and this is my breeding * * * * last and this is my breeding * * * * last and this is my breeding * * * * * The Video then subscribe to The Amazing Toys From The Two Value 6 Total Number Of Vs 1000 243 But 3513 To Take One Two Three Two Front Part Plus 2 And 4 Others Like This Vriddhi Table Started 10 And Eggs One From 3rd T20 Mobile ICDS Value 36 Inches Plus 345 Se Zor Dinner Table Saw A Changes Move Forward In Hot Scenes Vaart Na Dharai Festival 320 States Us Mudde All Are Of Three Elements By Beneficial As Well As Malefic Bus Flash Lights 138 Subscribe to Channel * 2ND ED AM ED 1ST AND 2ND Subscribe to Channel * 2ND ED AM ED 1ST AND 2ND Subscribe to Channel * 2ND ED AM ED 1ST AND 2ND GRADE THREE SHOULD AWARE OF IT TO AVOID TOURS AND TOURS SO BASICLY HERE IN THE ARE NOT STARTING FROM INDEX ONE AND REDUCED 30 TWIST ROAD NEAR OK ENZYMO FORWARD LINE BURST 3138 The Video then subscribe to the Page if you liked The Video then subscribe to the Page jethalal sebastian fatal aap isse vada quality bus stand for in 300mb setting fight last week hai world best friend 300 waste oil bursting after A Glassful Between To Front To 10 And Avoid Food And Recited One And Animated Stories From The Defeated By No if one and all elements in to-do No if one and all elements in to-do No if one and all elements in to-do list two that consider all the cases against like always so this phone how is this one kiss become just stuart law sport last three now last and fair lers so let's get valve's own only fiber stuart last date For Withdrawal B12 Into One Shouldn't Be And Two Plus Security Bursting 4315 Buddhists In Electronics To The Way Liquid Will Start From The Table Of Three Distincts In Electronics 300 From The Table Of The Number Three Layer I Can See The Television0 Tourism And Twelfth Services Kamar Thriller All Hare OK Forward-Forward To The Place Where Is All Hare OK Forward-Forward To The Place Where Is All Hare OK Forward-Forward To The Place Where Is Best For Class Fourth Class Tenth Twelfth Class 12421 Video A Plus Seat Notice Puberty Setting For Last Five Widow And 315 Subha Burst Into The Valley Of Coins Patel Get Clicked From The Index Of Zero Respectively Zero is forced Velvet Stored in the Table and 315 Morning Setting 315 Give Me the Valley Blood Boil Stored and the Temple of 12323 for 6 Total Six Class 8th 472 Nurses Old Stories Show A Disk Is Useless Let's Move Power to the Next This Lineage of K Is Consider Him By Sticking Free At Last Ok Should Strive To Resist But No Confusion Reviews Alarm Ko * Best Serial Reviews Alarm Ko * Best Serial Reviews Alarm Ko * Best Serial Blasts Took From Posting Third Class 10th Points At A Given To Three In To-Do Points At A Given To Three In To-Do Points At A Given To Three In To-Do List 3 Plus Awardee Just Stand To Rent 500ml Busting 2 and for the value of positive body to beautiful dutiable starting from new updates 120 amavasya spent that way and wealth but in favor of what the value of caused a candidate from dead table of three on low flame it should be defined isi 3015 plus 358 Witnesses To Calm Forward And Up And Jha And Batting Pfizer Last K Swarnim Batting For Its Very Embarrassing Fair Lovely For Executive 12521 Redmi 5 Plus Avoid 214 344 For Entertainment Awards Calculated From If Dutiable Suggest Se Zinc Shirt Index To From Zero Waist 210 0 a solid and pass great and they can change this value and can use this value to decorate the answer maximum number of presence arrested from the head of research size -1.2 solar decoding this au declare the first president will have to the value of intent and Good thought for programming in order to give the opposite word parameter time giving us aslam start side is next parameters but i will have to give this factor in 10m if given answer site question examples where for web metrics and good to give 100 initially and decided to Give Condition Note Size Classes Monday Forward Know The Top Most Obscure Tours From One To Three Four Elements And Subscribe Old Play List That Atoms Follow On Developed To Start With Okay First To Give Another For That They Will Have To Start With The Distance Of The Subscribe Schooling From Outside - Mon Subscribe Schooling From Outside - Mon Subscribe Schooling From Outside - Mon Mid Length Please Do This In Just One Example Mon One Act 2012 Range's Easy Love First Look 209 153 Aayi Hai Vikram One Ok 11 2012 Ranges From No0 - subscribe to the Page Ranges From No0 - subscribe to the Page Ranges From No0 - subscribe to the Page if you liked The Video then subscribe to the Page if minus one plus minus one considers it is equal to two to the element nothing but a plus length of element kata dhirendra time minus one side and logically soon they will be i plus and minus one patron white 333 miles 283 solutions with subscribe Button Two Three Four Wheel Simply Declare Slap To Everyone Right Value's Select Festival To Give One Sudhir Values ​​In That Festival To Give One Sudhir Values ​​In That Festival To Give One Sudhir Values ​​In That Is Vikram Ji's 108 Names - One Who Will Is Vikram Ji's 108 Names - One Who Will Is Vikram Ji's 108 Names - One Who Will Not Be Considered As One Is Not Equal 2012 - 1224 Size - Similarly in the right 2012 - 1224 Size - Similarly in the right 2012 - 1224 Size - Similarly in the right value will just a that I right when you will welcome not 100 z plus one ok so let's move forward not going to and declare or before and after the interview 2030 example love you consider me 0385 the use of but before and after Declaring Before And After And Is Not Equal 2012 New Delhi Current Footage From Dar Details Should E P F We Overlap To Right That I And Vital K Minus One Prem Similarly After Deeds Not Equal To K Daily Bad Time After Value Will B D P O Ao Hai Ki Plus One 3G Set Sudesh Will Visit And Dums Have Elected Mlas Most Important Statement Miss Statement Of Amazed To The Value Of Time Now Competes With All Its True Value K So Let's Move To The Volume To Good Night Before And After two days later this is the president loot after all the three for lips rock on celebs tourist on dpo 0n adams start size - 151 let's check the blood value of things have written sparing of northern way loot is not the value of this issue with the Function And Share And Subscribe Like And Subscribe To Slate Me Too Late Now Improved Steer With A Respecting And Semi Total OK Select Axis Bank Disclosing This For Next Practice For Watching This Pollution Extracted Disclosing This For You Very Good Election Vision Don't And This Practice Close My Function Suzy Back It's Not Need A Ajay Ko Hai That Yashwant Working Right Now Let's Submit NC See Lot Yes I Think It's Working Pant Successful So Thank You For Bearing With Me
Burst Balloons
burst-balloons
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons. If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, then treat it as if there is a balloon with a `1` painted on it. Return _the maximum coins you can collect by bursting the balloons wisely_. **Example 1:** **Input:** nums = \[3,1,5,8\] **Output:** 167 **Explanation:** nums = \[3,1,5,8\] --> \[3,5,8\] --> \[3,8\] --> \[8\] --> \[\] coins = 3\*1\*5 + 3\*5\*8 + 1\*3\*8 + 1\*8\*1 = 167 **Example 2:** **Input:** nums = \[1,5\] **Output:** 10 **Constraints:** * `n == nums.length` * `1 <= n <= 300` * `0 <= nums[i] <= 100`
null
Array,Dynamic Programming
Hard
1042
203
so today we are looking at lead code number two zero three remove linked list elements so here we have a linked list one two six three four five six we wanna remove all the sixes from that linked list and return the link list if the value is not in the linked list we just go ahead and return whatever the link list is and if all the values in the linked list or if there's duplicates we want to remove all of those as well as you can see in example 2 over here and example three okay so this is this can be a tricky question and there's a pattern underneath underlying this that um that can make these types of questions a little bit easier there can be some edge cases with link list and removals and additions and deletions and so using a trick which i'll go over here in a little bit can really be helpful let's just kind of go over the conceptual overview and then we'll kind of look at how we can use a pattern that can be helpful with this so here we have one two six three four five six we have one two uh one two six three four five and six and what we wanna do is remove the six okay so let's take a look at this let's say we only use one pointer okay i'll just call this the current node i use a different color i'll call this the current node at 1. and our target value is going to be 6. so we can increment this current let's say we go current from 1 to 2 to 6 and we check okay we hit 6 now we have to remove this node and unfortunately there's no way to remove this node because to remove a node what we have to do is we have to take this previous node the pointer there and we have to move it to this three but if we are only using one pointer there's no we don't have access to the previous node there's no way to access that previous node and because of that we can't just use one pointer we have to use two pointers okay so let's take a look at how we could do this with two pointers okay so let's say we put our previous over here and our current over here and i'll say our target is again it's six now we iterate over this list by twos so current is going to come here and previous is going to come here we're going to check is the current equal the target it does and so all we have to do now is just go ahead and break this pointer over here at 2 and set it to the dot next and then we can go ahead and increment our current and then we continue on with the iteration we go ahead and move current over here we move previous over here does current equal six it does not we move current over here previous over here this current equals six it does not we move current over here and previous over here and we checked as current equals six it does and so what do we want to go ahead and take the previous dot next this pointer over here and set it to current.next which is here and set it to current.next which is here and set it to current.next which is null we'll set that to null and now we have gone through the entire list and the nodes that we have left are 1 2 3 4 5 and 6. okay so two pointers works but there is an edge case here there is an edge case okay and let's go ahead and see if we can move this uh let me go ahead and grab my pointer tool here we'll go ahead and move this over here and let's take a look at and if we have a list here one two six three four five and six okay and let's say our target value is one it's at the head but if we set our previous here and our current here and we're checking here on current there's no way to check what was behind it okay and so this would not equal six we would move the current we'd move the previous and we would totally miss the target node that we're trying to remove and so a way we can get around this is and this is a good method to know anytime you're dealing with any sort of linked list that deals with addition or subtraction removal or addition of a linked list is you want to use a method where you use a dummy node okay we're going to create a node and just set it to -1 just set it to -1 just set it to -1 before the head and point it to the head okay and then what we're going to do is we're going to set our previous node actually one step behind the head on a dummy node we'll instantiate a whole new node and then we will set our previous to that dummy node and the next will point to the head okay so this will now be our current and now it follows the same pattern as it did up here for how we traversed it on the top example and so again if current is one this previous will break over here it'll point to current dot next we'll increment current and we'll go traverse to the whole list when we get to the end and everything's removed then all we have is we have a variable we can call it dummy and it's pointing to that dummy head even though the previous is gone all the way to the end current will be over here previous will be here we still have this pointer pointing to this dummy head okay and then all we do is return dummy.next and then all we do is return dummy.next and then all we do is return dummy.next and for this list right over here the final list should look like two six three four five and six if we're removing one okay and then all we're going to do is return dummy.next which will be pointing to this two node right there okay it'll be pointing to the head node the new head and that'll return that list all right so let's go ahead and code this up so what we want to do is first we want to create that dummy node so we can say let dummy equals new list node and we'll just set it to -1 node and we'll just set it to -1 node and we'll just set it to -1 and then we're going to set dummy.next to our head node and then we have two pointers we're going to have a previous so we can say let prev equals dummy and let ker equals head okay and now we just want to traverse through this list which is we can just say while current is true we want to say if current.val equals if current.val equals if current.val equals val what do we want to set our previous dot next to our current dot next and then we want to increment our current okay else what do we want to do else we want to increment our previous and then increment our current okay and then at the end of all of this we just want to return dummy.next okay let's go ahead and run that and we have success and so that is lead code number 203 now before we go let's just take a look at time and space complexity so what is our time complexity here well we how many times are we going over this list we're only going over it once we're iterating over at once and we're just dynamically removing the duplicates we're not creating a new list we're not pushing it into an array and then pulling those numbers out we're just iterating over the list once and just taking out the duplicates as we iterate over the list so our time complexity here is going to be o of n okay and what about space well the only new space we're creating is this dummy here beside and then you know we're creating some pointers but we're not creating generating any new space relative to the size of the input and so let me move this one here so it's an s so our space is actually going to be constant okay we'll have constant space so linear time constant space which is not bad which is pretty good okay so that is elite code number 203 remove link list hope you enjoyed it and i will see you on the next one
Remove Linked List Elements
remove-linked-list-elements
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_. **Example 1:** **Input:** head = \[1,2,6,3,4,5,6\], val = 6 **Output:** \[1,2,3,4,5\] **Example 2:** **Input:** head = \[\], val = 1 **Output:** \[\] **Example 3:** **Input:** head = \[7,7,7,7\], val = 7 **Output:** \[\] **Constraints:** * The number of nodes in the list is in the range `[0, 104]`. * `1 <= Node.val <= 50` * `0 <= val <= 50`
null
Linked List,Recursion
Easy
27,237,2216